📄 httpclientconnection.java
字号:
/*
*
* $Id: HttpClientConnection.java,v 1.7 2002/06/19 01:17:36 jice 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 org.apache.log4j.Category;
import org.apache.log4j.Priority;
/**
* Simple messenger that simply posts a message to a URL.
* URL/HttpURLConnection is used, so (depending on your JDK) you will get
* reasonably good persistent connection management.
*/
public class HttpClientConnection implements EndpointMessenger, Runnable {
/** standard log object **/
private static final Category LOG =
Category.getInstance(HttpClientConnection.class.getName());
public static final int MaxNbOfMessages = 40;
private URL url = null;
private boolean waiting = false;
private long lastUsed = 0;
private Thread thread = null;
private EndpointReceiveQueue queue = null; // Type is missnomer. We use
// as a send Queue here.
private long nbOfMessagesSent = 0;
private static final MimeMediaType msgType = new MimeMediaType( "application/x-jxta-msg" );
/** constructs the messenger.
* @param url The URL of where we're going to send the message. This
* may be the final destination, or it may be an intermediary.
* @param localAddress the local peer's address. this is the source
* address for the message.
* @param destAddress the destination peer address. This is the dest
* address for the message.
*/
public HttpClientConnection (URL url) {
this.url = url;
}
private synchronized void setThreadName () {
if (thread != null) {
try {
thread.setName ("HTTP Connection to " + url.toString() + " [" +
queue.getNbOfQueuedMessages() + ", " +
nbOfMessagesSent + " ]");
} catch (Exception ez1) {
if (LOG.isEnabledFor(Priority.ERROR)) LOG.error("Cannot change thread name", ez1);
}
}
}
/**
* Send the message.
*/
private void doSendMessage (Message msg) throws IOException {
// send the message
HttpURLConnection urlConn =
(HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.connect();
BufferedOutputStream out = new BufferedOutputStream(urlConn.getOutputStream());
out.flush(); // flush out http headers
MessageWireFormatFactory.newMessageWireFormat(msgType).writeMessage(out, msg);
out.flush();
out.close();
int code = urlConn.getResponseCode();
if (code!=HttpUtil.HTTP_SC_OK) {
throw new IOException ("Message not accepted: HTTP status " +
"code=" + code + " reason=" +
urlConn.getResponseMessage() );
} else {
++nbOfMessagesSent;
}
setThreadName();
}
/*
* Buffered version
*/
public void sendMessage (Message msg) throws IOException {
connect();
synchronized (this) {
queue.push (msg);
}
setThreadName();
Thread.yield();
}
/*
* unbuffered version.
public void sendMessage (Message msg) throws IOException {
try {
// Wait for messages to be sent.
doSendMessage (msg);
} catch (IOException ez2) {
// The message failed. Notify the failure
notifyFailure();
}
}
*/
// This is the background Thread. While the connection is active, takes
// messages from the queue and send it.
public void run() {
Message msg = null;
while (true) {
try {
// Wait for messages to be sent.
msg = queue.waitForMessage();
setThreadName();
doSendMessage (msg);
} catch (InterruptedException ez1) {
// The connection is just being close. This Thread must exit.
thread = null;
return;
} catch (IOException ez2) {
// The message failed. Notify the failure
notifyFailure();
thread = null;
return;
}
}
}
// Try to connect. This operation is idempotent.
private void connect () {
synchronized (this) {
if (queue == null) {
// There is new queue. Create one.
queue = new EndpointReceiveQueue();
queue.setMaxNbOfMessages (MaxNbOfMessages);
}
// Start the background thread.
if (thread != null) {
// Nothing to do
return;
}
thread = new Thread (this, "HTTP Connection to " + url.toString() + " [Unused]");
thread.start();
}
Thread.yield();
}
private synchronized void notifyFailure() {
close();
}
public synchronized void close() {
if (queue != null) {
queue.close();
queue = null;
}
if (thread != null) {
try {
thread.interrupt();
thread = null;
} catch (Exception ez1) {
if (LOG.isEnabledFor(Priority.WARN)) LOG.warn("Cannot interrupt thread for " + url.toString(), ez1);
}
}
}
public synchronized long getLastUsed () {
return lastUsed;
}
public synchronized void setLastUsed (long time) {
lastUsed = time;
}
// Just in case the code that allocated an instance of this object forgot to do "close".
public void finalize() {
close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -