HTTPConnection.java [plain text]
package gnu.java.net.protocol.http;
import gnu.classpath.Configuration;
import gnu.java.net.protocol.http.event.ConnectionEvent;
import gnu.java.net.protocol.http.event.ConnectionListener;
import gnu.java.net.protocol.http.event.RequestEvent;
import gnu.java.net.protocol.http.event.RequestListener;
import gnu.java.net.EmptyX509TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
public class HTTPConnection
{
public static final int HTTP_PORT = 80;
public static final int HTTPS_PORT = 443;
private static final String userAgent = initUserAgent();
private static String initUserAgent()
{
try
{
StringBuffer buf = new StringBuffer("libgcj");
buf.append(" (");
buf.append(System.getProperty("os.name"));
buf.append("; ");
buf.append(System.getProperty("os.arch"));
buf.append("; ");
buf.append(System.getProperty("user.language"));
buf.append(")");
return buf.toString();
}
catch (SecurityException e)
{
return "inetlib/1.1";
}
}
protected final String hostname;
protected final int port;
protected final boolean secure;
protected final int connectionTimeout;
protected final int timeout;
protected String proxyHostname;
protected int proxyPort;
protected int majorVersion;
protected int minorVersion;
private final List connectionListeners;
private final List requestListeners;
private final List handshakeCompletedListeners;
protected Socket socket;
private SSLSocketFactory sslSocketFactory;
protected InputStream in;
protected OutputStream out;
private Map nonceCounts;
protected CookieManager cookieManager;
public HTTPConnection(String hostname)
{
this(hostname, HTTP_PORT, false, 0, 0);
}
public HTTPConnection(String hostname, boolean secure)
{
this(hostname, secure ? HTTPS_PORT : HTTP_PORT, secure, 0, 0);
}
public HTTPConnection(String hostname, boolean secure,
int connectionTimeout, int timeout)
{
this(hostname, secure ? HTTPS_PORT : HTTP_PORT, secure,
connectionTimeout, timeout);
}
public HTTPConnection(String hostname, int port)
{
this(hostname, port, false, 0, 0);
}
public HTTPConnection(String hostname, int port, boolean secure)
{
this(hostname, port, secure, 0, 0);
}
public HTTPConnection(String hostname, int port, boolean secure,
int connectionTimeout, int timeout)
{
this.hostname = hostname;
this.port = port;
this.secure = secure;
this.connectionTimeout = connectionTimeout;
this.timeout = timeout;
majorVersion = minorVersion = 1;
connectionListeners = new ArrayList(4);
requestListeners = new ArrayList(4);
handshakeCompletedListeners = new ArrayList(2);
}
public String getHostName()
{
return hostname;
}
public int getPort()
{
return port;
}
public boolean isSecure()
{
return secure;
}
public String getVersion()
{
return "HTTP/" + majorVersion + '.' + minorVersion;
}
public void setVersion(int majorVersion, int minorVersion)
{
if (majorVersion != 1)
{
throw new IllegalArgumentException("major version not supported: " +
majorVersion);
}
if (minorVersion < 0 || minorVersion > 1)
{
throw new IllegalArgumentException("minor version not supported: " +
minorVersion);
}
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
}
public void setProxy(String hostname, int port)
{
proxyHostname = hostname;
proxyPort = port;
}
public boolean isUsingProxy()
{
return (proxyHostname != null && proxyPort > 0);
}
public void setCookieManager(CookieManager cookieManager)
{
this.cookieManager = cookieManager;
}
public CookieManager getCookieManager()
{
return cookieManager;
}
public Request newRequest(String method, String path)
{
if (method == null || method.length() == 0)
{
throw new IllegalArgumentException("method must have non-zero length");
}
if (path == null || path.length() == 0)
{
path = "/";
}
Request ret = new Request(this, method, path);
if ((secure && port != HTTPS_PORT) ||
(!secure && port != HTTP_PORT))
{
ret.setHeader("Host", hostname + ":" + port);
}
else
{
ret.setHeader("Host", hostname);
}
ret.setHeader("User-Agent", userAgent);
ret.setHeader("Connection", "keep-alive");
ret.setHeader("Accept-Encoding",
"chunked;q=1.0, gzip;q=0.9, deflate;q=0.8, " +
"identity;q=0.6, *;q=0");
if (cookieManager != null)
{
Cookie[] cookies = cookieManager.getCookies(hostname, secure, path);
if (cookies != null && cookies.length > 0)
{
StringBuffer buf = new StringBuffer();
buf.append("$Version=1");
for (int i = 0; i < cookies.length; i++)
{
buf.append(',');
buf.append(' ');
buf.append(cookies[i].toString());
}
ret.setHeader("Cookie", buf.toString());
}
}
fireRequestEvent(RequestEvent.REQUEST_CREATED, ret);
return ret;
}
public void close()
throws IOException
{
try
{
closeConnection();
}
finally
{
fireConnectionEvent(ConnectionEvent.CONNECTION_CLOSED);
}
}
protected Socket getSocket()
throws IOException
{
if (socket == null)
{
String connectHostname = hostname;
int connectPort = port;
if (isUsingProxy())
{
connectHostname = proxyHostname;
connectPort = proxyPort;
}
socket = new Socket();
InetSocketAddress address =
new InetSocketAddress(connectHostname, connectPort);
if (connectionTimeout > 0)
{
socket.connect(address, connectionTimeout);
}
else
{
socket.connect(address);
}
if (timeout > 0)
{
socket.setSoTimeout(timeout);
}
if (secure)
{
try
{
SSLSocketFactory factory = getSSLSocketFactory();
SSLSocket ss =
(SSLSocket) factory.createSocket(socket, connectHostname,
connectPort, true);
String[] protocols = { "TLSv1", "SSLv3" };
ss.setEnabledProtocols(protocols);
ss.setUseClientMode(true);
synchronized (handshakeCompletedListeners)
{
if (!handshakeCompletedListeners.isEmpty())
{
for (Iterator i =
handshakeCompletedListeners.iterator();
i.hasNext(); )
{
HandshakeCompletedListener l =
(HandshakeCompletedListener) i.next();
ss.addHandshakeCompletedListener(l);
}
}
}
ss.startHandshake();
socket = ss;
}
catch (GeneralSecurityException e)
{
throw new IOException(e.getMessage());
}
}
in = socket.getInputStream();
in = new BufferedInputStream(in);
out = socket.getOutputStream();
out = new BufferedOutputStream(out);
}
return socket;
}
SSLSocketFactory getSSLSocketFactory()
throws GeneralSecurityException
{
if (sslSocketFactory == null)
{
TrustManager tm = new EmptyX509TrustManager();
SSLContext context = SSLContext.getInstance("SSL");
TrustManager[] trust = new TrustManager[] { tm };
context.init(null, trust, null);
sslSocketFactory = context.getSocketFactory();
}
return sslSocketFactory;
}
void setSSLSocketFactory(SSLSocketFactory factory)
{
sslSocketFactory = factory;
}
protected InputStream getInputStream()
throws IOException
{
if (socket == null)
{
getSocket();
}
return in;
}
protected OutputStream getOutputStream()
throws IOException
{
if (socket == null)
{
getSocket();
}
return out;
}
protected void closeConnection()
throws IOException
{
if (socket != null)
{
try
{
socket.close();
}
finally
{
socket = null;
}
}
}
protected String getURI()
{
StringBuffer buf = new StringBuffer();
buf.append(secure ? "https://" : "http://");
buf.append(hostname);
if (secure)
{
if (port != HTTPConnection.HTTPS_PORT)
{
buf.append(':');
buf.append(port);
}
}
else
{
if (port != HTTPConnection.HTTP_PORT)
{
buf.append(':');
buf.append(port);
}
}
return buf.toString();
}
int getNonceCount(String nonce)
{
if (nonceCounts == null)
{
return 0;
}
return((Integer) nonceCounts.get(nonce)).intValue();
}
void incrementNonce(String nonce)
{
int current = getNonceCount(nonce);
if (nonceCounts == null)
{
nonceCounts = new HashMap();
}
nonceCounts.put(nonce, new Integer(current + 1));
}
public void addConnectionListener(ConnectionListener l)
{
synchronized (connectionListeners)
{
connectionListeners.add(l);
}
}
public void removeConnectionListener(ConnectionListener l)
{
synchronized (connectionListeners)
{
connectionListeners.remove(l);
}
}
protected void fireConnectionEvent(int type)
{
ConnectionEvent event = new ConnectionEvent(this, type);
ConnectionListener[] l = null;
synchronized (connectionListeners)
{
l = new ConnectionListener[connectionListeners.size()];
connectionListeners.toArray(l);
}
for (int i = 0; i < l.length; i++)
{
switch (type)
{
case ConnectionEvent.CONNECTION_CLOSED:
l[i].connectionClosed(event);
break;
}
}
}
public void addRequestListener(RequestListener l)
{
synchronized (requestListeners)
{
requestListeners.add(l);
}
}
public void removeRequestListener(RequestListener l)
{
synchronized (requestListeners)
{
requestListeners.remove(l);
}
}
protected void fireRequestEvent(int type, Request request)
{
RequestEvent event = new RequestEvent(this, type, request);
RequestListener[] l = null;
synchronized (requestListeners)
{
l = new RequestListener[requestListeners.size()];
requestListeners.toArray(l);
}
for (int i = 0; i < l.length; i++)
{
switch (type)
{
case RequestEvent.REQUEST_CREATED:
l[i].requestCreated(event);
break;
case RequestEvent.REQUEST_SENDING:
l[i].requestSent(event);
break;
case RequestEvent.REQUEST_SENT:
l[i].requestSent(event);
break;
}
}
}
void addHandshakeCompletedListener(HandshakeCompletedListener l)
{
synchronized (handshakeCompletedListeners)
{
handshakeCompletedListeners.add(l);
}
}
void removeHandshakeCompletedListener(HandshakeCompletedListener l)
{
synchronized (handshakeCompletedListeners)
{
handshakeCompletedListeners.remove(l);
}
}
}