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

📄 httpclientmessagesender.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
字号:
/*
 *
 * $Id: HttpClientMessageSender.java,v 1.14 2002/05/01 17:40:42 hamada Exp $
 *
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights reserved.
 *
 * 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 the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *    must not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * 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 SUN MICROSYSTEMS 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 Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 */

package net.jxta.impl.endpoint.servlethttp;

import net.jxta.impl.endpoint.*;
import net.jxta.endpoint.*;
import net.jxta.document.MimeMediaType;

import java.io.*;
import java.net.*;
import java.util.*;

import org.apache.log4j.Category;
import org.apache.log4j.Priority;

/**
 * Simple HTTP client sender. This is just using the URL/HttpURLConnection
 * classes for connection management.
 */
public class HttpClientMessageSender implements MessageSender {

	/** standard log object **/
	private static final Category LOG =
	    Category.getInstance(HttpClientMessageSender.class.getName());

	/** the local address that this sender puts on messages **/
	private EndpointAddress localAddress = null;

	private static final long HttpClientConnectionGCDelay = 60 * 60 * 1000; // 1 Hour
	private Timer  HttpClientConnectionGCTimer = new Timer();
	private Hashtable    openConnections    = new Hashtable();

	/** Constructs the simple HTTP client sender. You pass in the local
	address that you want to be known by to other people. This is used
	for address outgoing messages.  XXX Note: I don't like this model
	at all with the new transport framework. The endpoint should probably
	address the messages. Jbeatty. **/
	public HttpClientMessageSender (EndpointAddress localAddress) {

		this.localAddress = localAddress;

		// Start the connection GC timer.
		HttpClientConnectionGCTimer.scheduleAtFixedRate (new HttpClientConnectionGCTask (this),
		        HttpClientConnectionGCDelay,
		        HttpClientConnectionGCDelay);
	}

	/**
	 * Creates a simple messenger. Does not make any connections at this
	 * point. 'dest' is converted to a URL and an HttpClientMessenger is
	 * created
	 * @throws IOException This exception is only thrown if the dest cannot
	 *   be turned into a URL.
	 */
	public EndpointMessenger getMessenger (EndpointAddress destAddress)
	throws IOException {

		String urlString = destAddress.getProtocolName() + "://" +
		                   destAddress.getProtocolAddress() + "/";

		return new HttpClientMessenger(this,
		                               new URL(urlString),
		                               localAddress,
		                               destAddress );
	}

	/**
	 * The simple HTTP client messenger does not implement propagation. The
	 * propagation model needs to be a bit more intelligent.
	 */
	public void propagate (Message msg,
	                       String serviceName,
	                       String serviceParams,
	                       String prunePeer) throws IOException {
		return;
	}

	/**
	 * Pings the endpoint address to see if it is alive. Returns true if the
	 * endpoint responded with a 200, false otherwise.
	 * We also must handle the case that 'addr' is the special HTTP relay
	 * client address. For this, we always return false.
	 */
	public boolean ping (EndpointAddress addr) {


		if (addr.getProtocolAddress().indexOf (ServletHttpTransport.MAGIC_WORD) != -1) {
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug ("Ping of relay client: always false");
			}
			return false;
		}

		// result will remain false unless we get a 200
		boolean result = false;

		String urlString = null;
		try {
			urlString = "http://" + addr.getProtocolAddress() + "/ping";
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug ("Trying to ping " + urlString);
			}

			URL url = new URL (urlString);

			HttpURLConnection urlConn =
			    (HttpURLConnection) url.openConnection();

			urlConn.setRequestMethod("GET");
			urlConn.connect();

			int code = urlConn.getResponseCode();
			if (code==HttpUtil.HTTP_SC_OK)
				result = true;

		} catch (IOException e) {
			// no code intended
		}

		if (LOG.isEnabledFor(Priority.DEBUG)){
			LOG.debug ("Ping result to " + urlString + ": " + result);
		}
		return result;
	}

	private synchronized void registerHttpClientConnection (URL url,
	        HttpClientConnection connection) {

		if (LOG.isEnabledFor(Priority.DEBUG)) {
			LOG.debug("Register connection to " + url.toString());
		}

		HttpClientConnection old =
		    (HttpClientConnection) openConnections.put (url.toString(), connection);

		if (old != null) {
			old.close();
		}
	}

	private synchronized void unregisterHttpClientConnection (URL url) {

		HttpClientConnection old =
		    (HttpClientConnection) openConnections.remove (url.toString());

		if (old != null) {
			old.close();
		}
	}

	/**
	 * Get or create a connection for a given destination.
	 **/
	public synchronized HttpClientConnection getHttpClientConnection (URL url) {

		HttpClientConnection connection = null;

		// If there is already a connection, use it.
		if (LOG.isEnabledFor(Priority.DEBUG)) {
			LOG.debug("Looking connection to " + url.toString());
		}

		connection = (HttpClientConnection) openConnections.get (url.toString());

		if (connection == null) {
			// No existing connection. Create one.
			try {
				if (LOG.isEnabledFor(Priority.DEBUG)) {
					LOG.debug("Creating new connection to " + url.toString());
				}
				connection = new HttpClientConnection (url);
				// Register it.
				registerHttpClientConnection (url, connection);
			} catch (Exception e) {
				return null;
			}
		} else {
			if (LOG.isEnabledFor(Priority.DEBUG)) {
				LOG.debug("Reusing existing connection to " + url.toString());
			}
		}

		connection.setLastUsed (System.currentTimeMillis());
		return connection;
	}

	/**
	 * Remove HttpClientConnection that have not been used for more than HttpClientConnectionGCDelay.
	 **/

	protected void httpConnectionGC () {

		if (LOG.isEnabledFor(Priority.DEBUG)) {
			LOG.debug("HttpClientConnectionGC starts");
		}

		Enumeration enum = openConnections.keys();
		if ((enum == null) || (!enum.hasMoreElements())) {
			// There is currentely no HttpClientConnection. Nothing to do.
			if (LOG.isEnabledFor(Priority.DEBUG)) {
				LOG.debug("HttpClientConnectionGC: no connection. Nothing to do.");
			}
			return;
		}

		HttpClientConnection connection = null;
		long                 lastUsed = 0;
		long                 currentTime = 0;
		String               destUrl = null;

		while (enum.hasMoreElements()) {
			try {
				destUrl = (String) enum.nextElement();
				connection = (HttpClientConnection) openConnections.get (destUrl);
				synchronized (this) {
					if (connection == null) {
						// Since this method is not synchronized, the connection may
						// have been removed since the begining of the execution of
						// the loop.
						continue;
					}
					lastUsed = connection.getLastUsed();
					currentTime = System.currentTimeMillis();

					if ((currentTime - lastUsed) >= HttpClientConnectionGCDelay) {
						// This connection has not been used for a while. Delete it.
						connection.close();
						openConnections.remove (destUrl);
						if (LOG.isEnabledFor(Priority.DEBUG)) {
							LOG.debug("HttpClientConnectionGC removes unused connection to " + destUrl);
						}
						continue;
					}
				}

			} catch (Exception ez1) {
				continue;
			}
		}
		if (LOG.isEnabledFor(Priority.DEBUG)) {
			LOG.debug("HttpClientConnectionGC completed.");
		}
	}



	/**
	 * The HttpClientConnection garbage collector class.
	 **/

	public class HttpClientConnectionGCTask extends TimerTask {

		HttpClientMessageSender sender = null;


		/**
		 *Constructor for the GC Task object
		 *
		 */
		public HttpClientConnectionGCTask(HttpClientMessageSender sender) {
			this.sender = sender;
		}


		public void run() {
			// Run the HttpClientConnectionManager GC.
			sender.httpConnectionGC();
		}
	}

}

⌨️ 快捷键说明

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