01: package org.apache.commons.httpclient.contrib.ssl;
02:
03: import org.apache.commons.httpclient.HostConfiguration;
04: import org.apache.commons.httpclient.HttpHost;
05: import org.apache.commons.httpclient.protocol.Protocol;
06:
07: /**
08: * A kind of HostConfiguration that can retain its Protocol when its host name
09: * or port changes. HttpClient may clone its HostConfigurationWithStickyProtocol
10: * and change the host URL, without changing the specialized Protocol.
11: * <p>
12: * This is useful for integrating a specialized Protocol or SocketFactory; for
13: * example, a SecureSocketFactory that authenticates via SSL. Use
14: * HttpClient.setHostConfiguration to install a
15: * HostConfigurationWithStickyProtocol that contains the specialized Protocol or
16: * SocketFactory.
17: * <p>
18: * An alternative is to use Protocol.registerProtocol to register a specialized
19: * Protocol. But that has drawbacks: it makes it hard to integrate modules (e.g.
20: * web applications in a servlet container) with different strategies, because
21: * they share the specialized Protocol (Protocol.PROTOCOLS is static). Also, it
22: * can't handle multiple socket factories for the same host and port, since the
23: * URL path isn't a parameter to Protocol.getProtocol or socket factory methods.
24: *
25: * @author John Kristian
26: */
27: public class HostConfigurationWithStickyProtocol extends
28: HostConfiguration {
29: public HostConfigurationWithStickyProtocol() {
30: }
31:
32: public HostConfigurationWithStickyProtocol(
33: HostConfiguration hostConfiguration) {
34: super (hostConfiguration);
35: }
36:
37: public Object clone() {
38: return new HostConfigurationWithStickyProtocol(this );
39: }
40:
41: public synchronized void setHost(String host, int port,
42: String scheme) {
43: setHost(new HttpHost(host, port, getNewProtocol(host, port,
44: scheme)));
45: }
46:
47: /**
48: * Select a Protocol to be used for the given host, port and scheme. The
49: * current Protocol may be selected, if appropriate. This method need not be
50: * thread-safe; the caller must synchronize if necessary.
51: * <p>
52: * This implementation returns the current Protocol if it has the given
53: * scheme; otherwise it returns the Protocol registered for that scheme.
54: */
55: protected Protocol getNewProtocol(String host, int port,
56: String scheme) {
57: final Protocol oldProtocol = getProtocol();
58: if (oldProtocol != null) {
59: final String oldScheme = oldProtocol.getScheme();
60: if (oldScheme == scheme
61: || (oldScheme != null && oldScheme
62: .equalsIgnoreCase(scheme))) {
63: // The old {rotocol has the desired scheme.
64: return oldProtocol; // Retain it.
65: }
66: }
67: return Protocol.getProtocol(scheme);
68: }
69:
70: }
|