Annotation of java/classes/org/w3c/www/protocol/http/HttpManager.java, revision 1.84
1.1 abaird 1: // HttpManager.java
1.84 ! ylafon 2: // $Id: HttpManager.java,v 1.83 2004/01/09 16:04:21 ylafon Exp $
1.1 abaird 3: // (c) COPYRIGHT MIT and INRIA, 1996.
4: // Please first read the full copyright statement in file COPYRIGHT.html
5:
1.38 bmahe 6: package org.w3c.www.protocol.http ;
1.1 abaird 7:
1.65 ylafon 8: import java.util.Enumeration;
9: import java.util.Hashtable;
10: import java.util.Properties;
11:
12: import java.net.URL;
13:
14: import java.io.InputStream;
15: import java.io.PrintStream;
16:
17: import org.w3c.www.mime.MimeHeaderHolder;
18: import org.w3c.www.mime.MimeParser;
19: import org.w3c.www.mime.MimeParserFactory;
20:
21: import org.w3c.util.LRUList;
22: import org.w3c.util.ObservableProperties;
23: import org.w3c.util.PropertyMonitoring;
24: import org.w3c.util.SyncLRUList;
1.1 abaird 25:
1.25 abaird 26: class ManagerDescription {
27: HttpManager manager = null;
28: Properties properties = null;
29:
30: final HttpManager getManager() {
31: return manager;
32: }
33:
34: final boolean sameProperties(Properties props) {
1.54 bmahe 35: if (props.size() != properties.size())
36: return false;
37: Enumeration enum = props.propertyNames();
38: while (enum.hasMoreElements()) {
39: String name = (String) enum.nextElement();
40: String prop = properties.getProperty(name);
41: if ((prop == null) || (! prop.equals(props.getProperty(name))))
42: return false;
43: }
44: return true;
1.25 abaird 45: }
46:
47: ManagerDescription(HttpManager manager, Properties props) {
48: this.manager = manager;
1.54 bmahe 49: this.properties = (Properties)props.clone();
1.25 abaird 50: }
51: }
52:
1.1 abaird 53: class ReplyFactory implements MimeParserFactory {
1.65 ylafon 54:
1.1 abaird 55: public MimeHeaderHolder createHeaderHolder(MimeParser parser) {
56: return new Reply(parser);
57: }
58:
59: }
60:
61: /**
62: * The client side HTTP request manager.
63: * This class is the user interface (along with the other public classes of
64: * this package) for the W3C client side library implementing HTTP.
65: * A typicall request is launched though the following sequence:
66: * <pre>
67: * HttpManager manager = HttpManager.getManager() ;
1.36 ylafon 68: * Request request = manager.createRequest() ;
1.1 abaird 69: * request.setMethod(HTTP.GET) ;
70: * request.setURL(new URL("http://www.w3.org/pub/WWW/"));
71: * Reply reply = manager.runRequest(request) ;
72: * // Get the reply input stream that contains the actual data:
73: * InputStream in = reply.getInputStream() ;
74: * ...
75: * </pre>
76: */
77:
1.13 abaird 78: public class HttpManager implements PropertyMonitoring {
1.45 ylafon 79:
80: private static final boolean debug = false;
81:
1.17 abaird 82: private static final
1.38 bmahe 83: String DEFAULT_SERVER_CLASS = "org.w3c.www.protocol.http.HttpBasicServer";
1.17 abaird 84:
85: /**
86: * The name of the property indicating the class of HttpServer to use.
87: */
88: public static final
1.38 bmahe 89: String SERVER_CLASS_P = "org.w3c.www.protocol.http.server";
1.17 abaird 90:
1.2 abaird 91: /**
92: * The name of the property containing the ProprequestFilter to launch.
93: */
1.12 abaird 94: public static final
1.38 bmahe 95: String FILTERS_PROP_P = "org.w3c.www.protocol.http.filters";
1.5 abaird 96: /**
1.43 ylafon 97: * The maximum number of simultaneous connectionlrus.
1.11 abaird 98: */
99: public static final
1.38 bmahe 100: String CONN_MAX_P = "org.w3c.www.protocol.http.connections.max";
1.11 abaird 101: /**
1.35 ylafon 102: * The SO_TIMEOUT of the client socket.
103: */
104: public static final
1.38 bmahe 105: String TIMEOUT_P = "org.w3c.www.protocol.http.connections.timeout";
1.35 ylafon 106: /**
1.82 ylafon 107: * The connection timeout of the client socket.
108: */
109: public static final
110: String CONN_TIMEOUT_P ="org.w3c.www.protocol.http.connections.connTimeout";
111: /**
1.5 abaird 112: * Header properties - The allowed drift for getting cached resources.
113: */
114: public static final
1.38 bmahe 115: String MAX_STALE_P = "org.w3c.www.protocol.http.cacheControl.maxStale";
1.5 abaird 116: /**
117: * Header properties - The minium freshness required on cached resources.
118: */
119: public static final
1.38 bmahe 120: String MIN_FRESH_P = "org.w3c.www.protocol.http.cacheControl.minFresh";
1.5 abaird 121: /**
122: * Header properties - Set the only if cached flag on requests.
123: */
124: public static final
1.39 ylafon 125: String ONLY_IF_CACHED_P=
126: "org.w3c.www.protocol.http.cacheControl.onlyIfCached";
1.5 abaird 127: /**
128: * Header properties - Set the user agent.
129: */
130: public static final
1.38 bmahe 131: String USER_AGENT_P = "org.w3c.www.protocol.http.userAgent";
1.5 abaird 132: /**
133: * Header properties - Set the accept header.
134: */
135: public static final
1.38 bmahe 136: String ACCEPT_P = "org.w3c.www.protocol.http.accept";
1.5 abaird 137: /**
138: * Header properties - Set the accept language.
139: */
140: public static final
1.38 bmahe 141: String ACCEPT_LANGUAGE_P = "org.w3c.www.protocol.http.acceptLanguage";
1.5 abaird 142: /**
143: * Header properties - Set the accept encodings.
144: */
145: public static final
1.38 bmahe 146: String ACCEPT_ENCODING_P = "org.w3c.www.protocol.http.acceptEncoding";
1.5 abaird 147: /**
1.62 ylafon 148: * Header properties - are we parsing answers in a lenient way?
149: */
150: public static final
151: String LENIENT_P = "org.w3c.www.protocol.http.lenient";
152: /**
1.79 ylafon 153: * Header properties - should we reuse a connection for POST?
154: */
155: public static final
156: String KEEPBODY_P = "org.w3c.www.protocol.http.keepbody";
157: /**
1.5 abaird 158: * Header properties - Should we use a proxy ?
159: */
160: public static final
1.12 abaird 161: String PROXY_SET_P = "proxySet";
1.5 abaird 162: /**
163: * Header properties - What is the proxy host name.
164: */
165: public static final
1.12 abaird 166: String PROXY_HOST_P = "proxyHost";
1.5 abaird 167: /**
168: * Header properties - What is the proxy port number.
169: */
170: public static final
1.12 abaird 171: String PROXY_PORT_P = "proxyPort";
1.2 abaird 172:
1.7 abaird 173: /**
174: * The default value for the <code>Accept</code> header.
175: */
176: public static final
177: String DEFAULT_ACCEPT = "*/*";
178: /**
179: * The default value for the <code>User-Agent</code> header.
180: */
181: public static final
1.84 ! ylafon 182: String DEFAULT_USER_AGENT = "Jigsaw/2.2.4";
1.7 abaird 183:
1.24 abaird 184: /**
185: * This array keeps track of all the created managers.
186: * A new manager (kind of HTTP client side context) is created for each
187: * diffferent set of properties.
188: */
1.25 abaird 189: private static ManagerDescription managers[] = new ManagerDescription[4];
1.65 ylafon 190:
1.1 abaird 191: /**
1.17 abaird 192: * The class to instantiate to create new HttpServer instances.
193: */
194: protected Class serverclass = null;
195: /**
1.13 abaird 196: * The properties we initialized from.
197: */
198: ObservableProperties props = null;
199: /**
1.1 abaird 200: * The server this manager knows about, indexed by FQDN of target servers.
201: */
202: protected Hashtable servers = null;
203: /**
204: * The template request (the request we will clone to create new requests)
205: */
1.4 abaird 206: protected Request template = null ;
207: /**
1.9 abaird 208: * The LRU list of connections.
1.4 abaird 209: */
1.9 abaird 210: protected LRUList connectionsLru = null;
1.1 abaird 211: /**
212: * The filter engine attached to this manager.
213: */
214: FilterEngine filteng = null;
215:
1.35 ylafon 216: protected int timeout = 300000;
1.82 ylafon 217: protected int conn_timeout = 1000;
1.9 abaird 218: protected int conn_count = 0;
219: protected int conn_max = 5;
1.62 ylafon 220: protected boolean lenient = true;
1.79 ylafon 221: protected boolean keepbody = false;
1.9 abaird 222:
1.83 ylafon 223: protected Hashtable _tmp_servers = null; // synced during creation
224:
1.1 abaird 225: /**
1.13 abaird 226: * Update the proxy configuration to match current properties setting.
227: * @return A boolean, <strong>true</strong> if change was done,
228: * <strong>false</strong> otherwise.
229: */
230:
231: protected boolean updateProxy() {
232: boolean set = props.getBoolean(PROXY_SET_P, false);
233: if ( set ) {
234: // Wow using a proxy now !
235: String host = props.getString(PROXY_HOST_P, null);
236: int port = props.getInteger(PROXY_PORT_P, -1);
237: URL proxy = null;
238: try {
239: proxy = new URL("http", host, port, "/");
240: } catch (Exception ex) {
241: return false;
242: }
243: // Now if a proxy...
1.55 bmahe 244: if (( proxy != null ) && (proxy.getHost() != null))
1.24 abaird 245: template.setProxy(proxy);
1.13 abaird 246: } else {
1.24 abaird 247: template.setProxy(null);
1.13 abaird 248: }
249: return true;
250: }
251:
252: /**
1.24 abaird 253: * Get this manager properties.
254: * @return An ObservableProperties instance.
255: */
256:
257: public final ObservableProperties getProperties() {
258: return props;
259: }
260:
261: /**
1.13 abaird 262: * PropertyMonitoring implementation - Update properties on the fly !
263: * @param name The name of the property that has changed.
264: * @return A boolean, <strong>true</strong> if change is accepted,
265: * <strong>false</strong> otherwise.
266: */
267:
268: public boolean propertyChanged(String name) {
1.24 abaird 269: Request tpl = template;
1.13 abaird 270: if ( name.equals(FILTERS_PROP_P) ) {
1.37 ylafon 271: // FIXME
272: return true;
273: // return false;
1.35 ylafon 274: } else if ( name.equals(TIMEOUT_P) ) {
275: setTimeout(props.getInteger(TIMEOUT_P, timeout));
276: return true;
1.82 ylafon 277: } else if ( name.equals(CONN_TIMEOUT_P) ) {
278: setConnTimeout(props.getInteger(CONN_TIMEOUT_P, conn_timeout));
279: return true;
1.13 abaird 280: } else if ( name.equals(CONN_MAX_P) ) {
281: setMaxConnections(props.getInteger(CONN_MAX_P, conn_max));
282: return true;
283: } else if ( name.equals(MAX_STALE_P) ) {
284: int ival = props.getInteger(MAX_STALE_P, -1);
285: if ( ival >= 0 )
286: tpl.setMaxStale(ival);
287: return true;
288: } else if ( name.equals(MIN_FRESH_P) ) {
289: int ival = props.getInteger(MIN_FRESH_P, -1);
290: if ( ival >= 0 )
291: tpl.setMinFresh(ival);
292: return true;
1.62 ylafon 293: } else if ( name.equals(LENIENT_P) ) {
1.78 ylafon 294: lenient = props.getBoolean(LENIENT_P, lenient);
1.62 ylafon 295: return true;
1.79 ylafon 296: } else if ( name.equals(KEEPBODY_P) ) {
297: keepbody = props.getBoolean(KEEPBODY_P, keepbody);
298: return true;
1.62 ylafon 299: } if ( name.equals(ONLY_IF_CACHED_P) ) {
1.13 abaird 300: tpl.setOnlyIfCached(props.getBoolean(ONLY_IF_CACHED_P, false));
301: return true;
302: } else if ( name.equals(USER_AGENT_P) ) {
303: tpl.setValue("user-agent"
304: , props.getString(USER_AGENT_P
305: , DEFAULT_USER_AGENT));
306: return true;
307: } else if ( name.equals(ACCEPT_P) ) {
308: tpl.setValue("accept"
309: , props.getString(ACCEPT_P, DEFAULT_ACCEPT));
310: return true;
311: } else if ( name.equals(ACCEPT_LANGUAGE_P) ) {
312: String sval = props.getString(ACCEPT_LANGUAGE_P, null);
313: if ( sval != null )
314: tpl.setValue("accept-language", sval);
315: return true;
316: } else if ( name.equals(ACCEPT_ENCODING_P) ) {
317: String sval = props.getString(ACCEPT_ENCODING_P, null);
318: if ( sval != null )
319: tpl.setValue("accept-encoding", sval);
320: return true;
321: } else if ( name.equals(PROXY_SET_P)
322: || name.equals(PROXY_HOST_P)
323: || name.equals(PROXY_PORT_P) ) {
324: return updateProxy();
325: } else {
326: return true;
327: }
328: }
329:
330: /**
1.4 abaird 331: * Allow the manager to interact with the user if needed.
332: * This will, for example, allow prompting for paswords, etc.
333: * @param onoff Turn interaction on or off.
334: */
335:
336: public void setAllowUserInteraction(boolean onoff) {
337: template.setAllowUserInteraction(onoff);
338: }
339:
1.66 bmahe 340: protected static synchronized
341: HttpManager getManager(Class managerclass, Properties p)
342: {
1.24 abaird 343: // Does such a manager exists already ?
344: for (int i = 0 ; i < managers.length ; i++) {
345: if ( managers[i] == null )
346: continue;
1.54 bmahe 347: if ( managers[i].sameProperties(p) )
1.25 abaird 348: return managers[i].getManager();
1.24 abaird 349: }
350: // Get the props we will initialize from:
1.28 abaird 351: ObservableProperties props = null;
1.24 abaird 352: if ( p instanceof ObservableProperties )
1.28 abaird 353: props = (ObservableProperties) p;
1.24 abaird 354: else
1.28 abaird 355: props = new ObservableProperties(p);
356: // Create a new manager for this set of properties:
1.66 bmahe 357: HttpManager manager = null;;
358: try {
359: Object o = managerclass.newInstance();
360: if (o instanceof HttpManager) {
361: manager = (HttpManager) o;
362: } else { // default value
363: manager = new HttpManager();
364: }
365: } catch (Exception ex) {
366: ex.printStackTrace();
367: manager = new HttpManager();
368: }
1.28 abaird 369: manager.props = props;
1.24 abaird 370: // Initialize this new manager filters:
371: String filters[] = props.getStringArray(FILTERS_PROP_P, null);
372: if ( filters != null ) {
373: for (int i = 0 ; i < filters.length ; i++) {
374: try {
375: Class c = Class.forName(filters[i]);
376: PropRequestFilter f = null;
377: f = (PropRequestFilter) c.newInstance();
378: f.initialize(manager);
379: } catch (PropRequestFilterException ex) {
380: System.out.println("Couldn't initialize filter \""
381: + filters[i]
382: + "\" init failed: "
383: + ex.getMessage());
384: } catch (Exception ex) {
385: System.err.println("Error initializing prop filters:");
386: System.err.println("Coulnd't initialize ["
387: + filters[i]
388: + "]: " + ex.getMessage());
389: ex.printStackTrace();
390: System.exit(1);
1.2 abaird 391: }
392: }
1.24 abaird 393: }
394: // The factory to create MIME reply holders:
1.66 bmahe 395: manager.factory = manager.getReplyFactory();
1.24 abaird 396: // The class to create HttpServer instances from
397: String c = props.getString(SERVER_CLASS_P, DEFAULT_SERVER_CLASS);
398: try {
1.34 bmahe 399: manager.serverclass = Class.forName(c);
1.24 abaird 400: } catch (Exception ex) {
401: System.err.println("Unable to initialize HttpManager: ");
402: System.err.println("Class \""+c+"\" not found, from property "
403: + SERVER_CLASS_P);
404: ex.printStackTrace();
405: System.exit(1);
406: }
407: // Setup the template request:
408: Request tpl = manager.template;
409: // Set some default headers value (from props)
410: // Check for a proxy ?
411: manager.updateProxy();
412: // CacheControl, only-if-cached
413: tpl.setOnlyIfCached(props.getBoolean(ONLY_IF_CACHED_P, false));
414: // CacheControl, maxstale
415: int ival = props.getInteger(MAX_STALE_P, -1);
416: if ( ival >= 0 )
417: tpl.setMaxStale(ival);
418: // CacheControl, minfresh:
419: ival = props.getInteger(MIN_FRESH_P, -1);
420: if ( ival >= 0 )
421: tpl.setMinFresh(ival);
1.62 ylafon 422: // general, lenient
423: manager.lenient = props.getBoolean(LENIENT_P, true);
1.79 ylafon 424: manager.keepbody = props.getBoolean(KEEPBODY_P, false);
1.24 abaird 425: // General, User agent
1.68 ylafon 426: String sval;
1.24 abaird 427: tpl.setValue("user-agent"
428: , props.getString(USER_AGENT_P
429: , DEFAULT_USER_AGENT));
430: // General, Accept
431: tpl.setValue("accept"
432: , props.getString(ACCEPT_P, DEFAULT_ACCEPT));
433: // General, Accept-Language
1.68 ylafon 434: sval = props.getString(ACCEPT_LANGUAGE_P, null);
1.67 ylafon 435: if ( sval != null ) {
436: if (sval.trim().length() > 0) {
437: tpl.setValue("accept-language", sval);
438: }
439: }
1.24 abaird 440: // General, Accept-Encoding
441: sval = props.getString(ACCEPT_ENCODING_P, null);
1.68 ylafon 442: if ( sval != null ) {
443: if (sval.trim().length() > 0) {
444: tpl.setValue("accept-encoding", sval);
445: }
446: }
1.24 abaird 447: // Maximum number of allowed connections:
448: manager.conn_max = props.getInteger(CONN_MAX_P, 5);
1.58 ylafon 449: // timeout value
1.59 ylafon 450: manager.timeout = props.getInteger(TIMEOUT_P, manager.timeout);
1.82 ylafon 451: // connection timeout
452: manager.conn_timeout = props.getInteger(CONN_TIMEOUT_P,
453: manager.conn_timeout);
1.24 abaird 454: // Register ourself as a property observer:
455: props.registerObserver(manager);
456: // Register that manager in our knwon managers:
457: for (int i = 0 ; i < managers.length ; i++) {
458: if ( managers[i] == null ) {
1.25 abaird 459: managers[i] = new ManagerDescription(manager, p);
1.24 abaird 460: return manager;
1.17 abaird 461: }
1.1 abaird 462: }
1.25 abaird 463: ManagerDescription nm[] = new ManagerDescription[managers.length << 1];
464: System.arraycopy(managers, 0, nm, 0, managers.length);
465: nm[managers.length] = new ManagerDescription(manager, p);
466: managers = nm;
1.1 abaird 467: return manager;
468: }
1.66 bmahe 469:
470:
471: /**
472: * Get an instance of the HTTP manager.
473: * This method returns an actual instance of the HTTP manager. It may
474: * return different managers, if it decides to distribute the load on
475: * different managers (avoid the HttpManager being a bottleneck).
476: * @return An application wide instance of the HTTP manager.
477: */
478:
479: public static synchronized HttpManager getManager(Properties p) {
480: return getManager(HttpManager.class, p);
481: }
1.1 abaird 482:
1.24 abaird 483: public static HttpManager getManager() {
484: return getManager(System.getProperties());
485: }
1.1 abaird 486:
487: /**
1.32 abaird 488: * Get the String key for the server instance handling that request.
489: * This method takes care of any proxy setting (it will return the key
490: * to the proxy when required.)
491: * @return A uniq identifier for the handling server, as a String.
492: */
493:
494: public final String getServerKey(Request request) {
495: URL proxy = request.getProxy();
496: URL target = request.getURL();
497: String key = null;
498: if ( proxy != null ) {
499: return ((proxy.getPort() == 80)
500: ? proxy.getHost().toLowerCase()
501: : (proxy.getHost().toLowerCase()+":"+proxy.getPort()));
502: } else {
503: return ((target.getPort() == 80)
504: ? target.getHost().toLowerCase()
505: : (target.getHost().toLowerCase()+":"+target.getPort()));
506: }
507: }
508:
509: /**
1.1 abaird 510: * Get the appropriate server object for handling request to given target.
1.32 abaird 511: * @param key The server's key, as returned by <code>getServerKey</code>.
1.1 abaird 512: * @return An object complying to the HttpServer interface.
513: * @exception HttpException If the given host name couldn't be resolved.
514: */
515:
1.76 ylafon 516: protected HttpServer lookupServer(String host, int port)
1.1 abaird 517: throws HttpException
518: {
1.5 abaird 519: int p = (port == -1) ? 80 : port;
1.32 abaird 520: String id = ((p == 80)
521: ? host.toLowerCase()
522: : (host.toLowerCase() +":"+p));
1.1 abaird 523: // Check for an existing server:
524: HttpServer server = (HttpServer) servers.get(id);
1.83 ylafon 525: if ( server != null ) {
1.1 abaird 526: return server;
1.83 ylafon 527: }
1.1 abaird 528: // Create and register a new server:
1.83 ylafon 529: synchronized (_tmp_servers) {
530: if (_tmp_servers.containsKey(id)) {
531: server = (HttpServer) _tmp_servers.get(id);
532: synchronized (server) {
533: while (server.state == null ||
534: server.state.state != HttpServerState.PREINIT) {
535: try {
536: wait(100);
537: } catch (InterruptedException ex) {
538: } catch (IllegalMonitorStateException ex) {
539: break;
540: }
541: }
542: }
543: if (server.state.state == HttpServerState.OK) {
544: return server;
545: } else if (server.state.ex != null) {
546: throw server.state.ex;
547: } else {
548: throw new RuntimeException("Unexpected error "+
549: "in lookupServer");
550: }
551: } else {
552: try {
553: server = (HttpServer) serverclass.newInstance();
554: } catch (Exception ex) {
555: String msg = ("Unable to create an instance of \""
556: + serverclass.getName()
557: + "\", invalid config, check the "
558: + SERVER_CLASS_P + " property.");
559: throw new HttpException(ex, msg);
560: }
561: }
562: }
1.17 abaird 563: try {
1.83 ylafon 564: synchronized (server) {
565: server.initialize(this, new HttpServerState(server), host, p,
566: timeout);
567: try {
568: notifyAll();
569: } catch (IllegalMonitorStateException imse) {};
570: }
571: // FIXME for long running servers the growing hashtable is
572: // a potential leak. This is a hard way of taking care of that
573: // if (servers.size() > conn_max) {
574: // closeAnyConnection();
575: // servers = new Hashtable(conn_max);
576: // }
577: } finally {
578: synchronized (_tmp_servers) {
579: if (server.state.state == HttpServerState.OK) {
580: servers.put(id, server);
581: } else {
582: // System.err.println("ERROR State is "+server.state.state
583: // +" for " + server);
584: }
585: _tmp_servers.remove(id);
586: }
1.71 ylafon 587: }
1.1 abaird 588: return server;
589: }
1.5 abaird 590:
1.1 abaird 591: /**
1.60 ylafon 592: * The given connection is about to be used.
593: * Update our list of available servers.
594: * @param conn The idle connection.
595: */
596:
1.83 ylafon 597: public synchronized void notifyUse(HttpConnection conn) {
1.60 ylafon 598: if (debug)
599: System.out.println("+++ connection used");
600: connectionsLru.remove(conn);
601: }
602:
603: /**
1.9 abaird 604: * The given connection can be reused, but is now idle.
605: * @param conn The connection that is now idle.
1.4 abaird 606: */
607:
1.60 ylafon 608: public synchronized void notifyIdle(HttpConnection conn) {
1.45 ylafon 609: if (debug)
610: System.out.println("+++ connection idle");
1.9 abaird 611: connectionsLru.toHead(conn);
1.63 ylafon 612: notifyAll();
1.4 abaird 613: }
614:
615: /**
1.9 abaird 616: * The given connection has just been created.
617: * @param conn The newly created connection.
618: */
619:
620: protected synchronized void notifyConnection(HttpConnection conn) {
1.45 ylafon 621: if (debug)
622: System.out.println("+++ notify conn_count " + (conn_count+1)
623: + " / " + conn_max);
1.9 abaird 624: if ( ++conn_count > conn_max )
625: closeAnyConnection();
626: }
627:
628: /**
629: * The given connection has been deleted.
630: * @param conn The deleted connection.
631: */
632:
1.83 ylafon 633: protected synchronized void deleteConnection(HttpConnection conn) {
634: --conn_count;
635: if (debug)
636: System.out.println("+++ delete conn_count: " + conn_count);
637: notifyAll();
1.9 abaird 638: }
639:
640: protected synchronized boolean tooManyConnections() {
1.51 ylafon 641: return conn_count >= conn_max;
1.9 abaird 642: }
643:
644: /**
645: * Try reusing one of the idle connection of that server, if any.
646: * @param server The target server.
647: * @return An currently idle connection to the given server.
1.4 abaird 648: */
649:
1.83 ylafon 650: protected synchronized HttpConnection getConnection(HttpServer server) {
1.9 abaird 651: HttpServerState ss = server.getState();
1.83 ylafon 652: HttpConnection hcn = ss.getConnection();
653: if (hcn != null) {
654: notifyUse(hcn);
655: }
656: return hcn;
1.9 abaird 657: }
658:
1.47 ylafon 659: /**
660: * Wait for a connection to come up.
661: * @param server, the target server.
1.48 bmahe 662: * @exception InterruptedException If interrupted..
1.47 ylafon 663: */
664:
1.9 abaird 665: protected synchronized void waitForConnection(HttpServer server)
666: throws InterruptedException
667: {
1.74 ylafon 668: wait(30000); // FIXME should be tunable, now set to 30s
1.4 abaird 669: }
670:
671: /**
1.60 ylafon 672: * Close some connections, but pickling the least recently used ones.
1.45 ylafon 673: * One third of the max number of connection is cut. This is done to
674: * eliminate the old connections that should be broken already.
675: * (no Socket.isAlive());
1.9 abaird 676: * @return A boolean, <strong>true</strong> if a connection was closed
677: * <strong>false</strong> otherwise.
1.4 abaird 678: */
679:
1.83 ylafon 680: protected synchronized boolean closeAnyConnection() {
1.45 ylafon 681: boolean saved = false;
1.47 ylafon 682: int max = Math.max(conn_max/3, 1);
1.45 ylafon 683: for (int i=0; i < max; i++) {
684: HttpConnection conn = (HttpConnection) connectionsLru.removeTail();
685: if ( conn != null ) {
686: conn.close();
1.83 ylafon 687: // deleteConnection(conn);
1.45 ylafon 688: if (debug)
689: System.out.println("+++ close request");
1.60 ylafon 690: saved = true;
1.83 ylafon 691: } else {
1.47 ylafon 692: break;
1.83 ylafon 693: }
694: }
695: // now purge the server Hashtable
696: synchronized (servers) {
697: Enumeration e = servers.keys();
698: while (e.hasMoreElements()) {
699: String id = (String) e.nextElement();
700: if (id != null) {
701: HttpServer server = (HttpServer) servers.get(id);
702: if (server.state.getConnectionCount() == 0) {
703: servers.remove(id);
704: }
705: }
706: }
1.9 abaird 707: }
1.45 ylafon 708: return saved;
1.4 abaird 709: }
710:
711: /**
1.1 abaird 712: * One of our server handler wants to open a connection.
713: * @param block A boolean indicating whether we should block the calling
714: * thread until a token is available (otherwise, the method will just
715: * peek at the connection count, and return the appropriate result).
716: * @return A boolean, <strong>true</strong> if the connection can be
717: * opened straight, <strong>false</strong> otherwise.
718: */
719:
1.9 abaird 720: protected boolean negotiateConnection(HttpServer server) {
721: HttpServerState ss = server.getState();
1.10 abaird 722: if ( ! tooManyConnections() ) {
1.4 abaird 723: return true;
1.10 abaird 724: } else if ( ss.notEnoughConnections() ) {
725: return closeAnyConnection();
1.9 abaird 726: } else if ( servers.size() > conn_max ) {
727: return closeAnyConnection();
1.4 abaird 728: }
1.9 abaird 729: return false;
1.60 ylafon 730: }
731:
732: /**
733: * A new client connection has been established.
734: * This method will try to maintain a maximum number of established
735: * connections, by closing idle connections when possible.
736: * @param server The server that has established a new connection.
737: */
738:
739: protected final synchronized void incrConnCount(HttpServer server) {
740: if ( ++conn_count > conn_max )
741: closeAnyConnection();
742: if (debug)
743: System.out.println("+++ incr conn_count: " + conn_count);
744: }
745:
746: /**
747: * Decrement the number of established connections.
748: * @param server The server that has closed one connection to its target.
749: */
750:
751: protected final synchronized void decrConnCount(HttpServer server) {
752: --conn_count;
753: if (debug)
754: System.out.println("+++ decr conn_count: " + conn_count);
1.83 ylafon 755: if (conn_count < 0) {
756: System.err.println(this);
757: }
1.1 abaird 758: }
759:
760: /**
761: * Run the given request, in synchronous mode.
762: * This method will launch the given request, and block the calling thread
763: * until the response headers are available.
764: * @param request The request to run.
765: * @return An instance of Reply, containing all the reply
766: * informations.
1.42 bmahe 767: * @exception HttpException If something failed during request processing.
1.1 abaird 768: */
1.65 ylafon 769:
1.1 abaird 770: public Reply runRequest(Request request)
771: throws HttpException
772: {
1.19 abaird 773: Reply reply = null;
774: int fcalls = 0;
1.1 abaird 775: // Now run through the ingoing filters:
776: RequestFilter filters[] = filteng.run(request);
777: if ( filters != null ) {
778: for (int i = 0 ; i < filters.length ; i++) {
1.19 abaird 779: if ((reply = filters[fcalls].ingoingFilter(request)) != null)
780: break;
781: fcalls++;
1.1 abaird 782: }
783: }
1.16 abaird 784: // Locate the appropriate target server:
1.31 abaird 785: URL target = request.getURL();
1.19 abaird 786: if ( reply == null ) {
1.32 abaird 787: HttpServer srv = null;
1.22 ylafon 788: boolean rtry ;
1.21 abaird 789: do {
1.22 ylafon 790: rtry = false;
1.21 abaird 791: try {
1.32 abaird 792: URL proxy = request.getProxy();
793: if ( proxy != null )
794: srv = lookupServer(proxy.getHost(), proxy.getPort());
795: else
796: srv = lookupServer(target.getHost(), target.getPort());
1.30 abaird 797: request.setServer(srv);
1.21 abaird 798: reply = srv.runRequest(request);
799: } catch (HttpException ex) {
800: for (int i = 0; i < fcalls; i++)
801: rtry = rtry || filters[i].exceptionFilter(request, ex);
1.23 abaird 802: if ( ! rtry )
1.22 ylafon 803: throw ex;
1.30 abaird 804: } finally {
805: request.unsetServer();
1.21 abaird 806: }
807: } while (rtry);
1.16 abaird 808: }
1.1 abaird 809: // Apply the filters on the way back:
810: if ( filters != null ) {
1.19 abaird 811: while (--fcalls >= 0) {
812: Reply frep = filters[fcalls].outgoingFilter(request, reply);
813: if ( frep != null ) {
814: reply = frep;
815: break;
816: }
1.3 abaird 817: }
1.1 abaird 818: }
819: return reply;
820: }
821:
822: /**
823: * Get this manager's reply factory.
824: * The Reply factory is used when prsing incomming reply from servers, it
825: * decides what object will be created to hold the actual reply from the
826: * server.
827: * @return An object compatible with the MimeParserFactory interface.
828: */
829:
830: MimeParserFactory factory = null ;
831:
1.9 abaird 832: public MimeParserFactory getReplyFactory() {
1.66 bmahe 833: if (factory == null) {
834: factory = new ReplyFactory();
835: }
1.1 abaird 836: return factory;
837: }
838:
839: /**
840: * Add a new request filter.
841: * Request filters are called <em>before</em> a request is launched, and
842: * <em>after</em> the reply headers are available. They allow applications
843: * to setup specific request headers (such as PICS, or PEP stuff) on the
844: * way in, and check the reply on the way out.
845: * <p>Request filters are application wide: if their scope matches
846: * the current request, then they will always be aplied.
847: * <p>Filter scopes are defined inclusively and exclusively
1.15 abaird 848: * @param incs The URL domains for which the filter should be triggered.
849: * @param exs The URL domains for which the filter should not be triggered.
1.1 abaird 850: * @param filter The request filter to add.
851: */
852:
853: public void setFilter(URL incs[], URL exs[], RequestFilter filter) {
854: if ( incs != null ) {
855: for (int i = 0 ; i < incs.length ; i++)
856: filteng.setFilter(incs[i], true, filter);
857: }
858: if ( exs != null ) {
859: for (int i = 0 ; i < exs.length ; i++)
860: filteng.setFilter(exs[i], false, filter);
861: }
862: return;
863: }
864:
1.15 abaird 865: /**
866: * Add a global filter.
867: * The given filter will <em>always</em> be invoked.
868: * @param filter The filter to install.
869: */
1.65 ylafon 870:
1.1 abaird 871: public void setFilter(RequestFilter filter) {
872: filteng.setFilter(filter);
873: }
874:
875: /**
1.15 abaird 876: * Find back an instance of a global filter.
877: * This methods allow external classes to get a pointer to installed
878: * filters of a given class.
879: * @param cls The class of the filter to look for.
880: * @return A RequestFilter instance, or <strong>null</strong> if not
881: * found.
1.1 abaird 882: */
883:
1.15 abaird 884: public RequestFilter getGlobalFilter(Class cls) {
885: return filteng.getGlobalFilter(cls);
1.1 abaird 886: }
887:
888: /**
889: * Create a new default outgoing request.
890: * This method should <em>always</em> be used to create outgoing requests.
891: * It will initialize the request with appropriate default values for
892: * the various headers, and make sure that the request is enhanced by
893: * the registered request filters.
894: * @return An instance of Request, suitable to be launched.
895: */
896:
897: public Request createRequest() {
898: return (Request) template.getClone() ;
899: }
900:
901: /**
902: * Global settings - Set the max number of allowed connections.
903: * Set the maximum number of simultaneous connections that can remain
904: * opened. The manager will take care of queuing requests if this number
905: * is reached.
906: * <p>This value defaults to the value of the
1.82 ylafon 907: * <code>org.w3c.www.http.connections.max</code> property.
1.1 abaird 908: * @param max_conn The allowed maximum simultaneous open connections.
909: */
910:
1.13 abaird 911: public synchronized void setMaxConnections(int max_conn) {
912: this.conn_max = max_conn;
1.35 ylafon 913: }
914:
915: /**
916: * Global settings - Set the timeout on the socket
917: *
918: * <p>This value defaults to the value of the
1.82 ylafon 919: * <code>org.w3c.www.http.connections.timeout</code> property.
1.35 ylafon 920: * @param timeout The allowed maximum microsecond before a timeout.
921: */
922:
923: public synchronized void setTimeout(int timeout) {
924: this.timeout = timeout;
925: Enumeration e = servers.elements();
926: while (e.hasMoreElements()) {
927: ((HttpServer) e.nextElement()).setTimeout(timeout);
928: }
1.62 ylafon 929: }
930:
931: /**
1.82 ylafon 932: * Global settings - Set the connection timeout for the socket
933: *
934: * <p>This value defaults to the value of the
935: * <code>org.w3c.www.protocol.http.connections.connTimeout</code> property
936: * @param timeout The allowed maximum microsecond before a timeout.
937: */
938:
939: public synchronized void setConnTimeout(int conn_timeout) {
940: this.conn_timeout = conn_timeout;
941: Enumeration e = servers.elements();
942: while (e.hasMoreElements()) {
943: ((HttpServer) e.nextElement()).setConnTimeout(conn_timeout);
944: }
945: }
946:
947: /**
1.62 ylafon 948: * Global settings - set the HTTP parsing lenient or not.
949: * @param lenient, true by default, false to detect wrong servers
950: */
951: public void setLenient(boolean lenient) {
952: this.lenient = lenient;
953: }
954:
955: /**
956: * Is this manager parsing headers in a lenient way?
957: * @return A boolean.
958: */
959: public boolean isLenient() {
960: return lenient;
1.1 abaird 961: }
962:
963: /**
964: * Global settings - Set an optional proxy to use.
965: * Set the proxy to which all requests should be targeted. If the
1.38 bmahe 966: * <code>org.w3c.www.http.proxy</code> property is defined, it will be
1.1 abaird 967: * used as the default value.
968: * @param proxy The URL for the proxy to use.
969: */
970:
971: public void setProxy(URL proxy) {
1.5 abaird 972: template.setProxy(proxy);
1.30 abaird 973: }
974:
975: /**
976: * Does this manager uses a proxy to fulfill requests ?
977: * @return A boolean.
978: */
979:
980: public boolean usingProxy() {
981: return template.hasProxy();
1.1 abaird 982: }
983:
984: /**
985: * Global settings - Set the request timeout.
986: * Once a request has been emited, the HttpManager will sit for this
987: * given number of milliseconds before the request is declared to have
988: * timed-out.
989: * <p>This timeout value defaults to the value of the
1.38 bmahe 990: * <code>org.w3c.www.http.requestTimeout</code> property value.
1.1 abaird 991: * @param ms The timeout value in milliseconds.
992: */
993:
994: public void setRequestTimeout(int ms) {
995: }
996:
997: /**
998: * Global settings - Define a global request header.
999: * Set a default value for some request header. Once defined, the
1000: * header will automatically be defined on <em>all</em> outgoing requests
1001: * created through the <code>createRequest</code> request.
1002: * @param name The name of the header, case insensitive.
1003: * @param value It's default value.
1004: */
1.65 ylafon 1005:
1.1 abaird 1006: public void setGlobalHeader(String name, String value) {
1007: template.setValue(name, value);
1008: }
1009:
1.18 abaird 1010: /**
1011: * Global settings - Get a global request header default value.
1012: * @param name The name of the header to get.
1013: * @return The value for that header, as a String, or <strong>
1014: * null</strong> if undefined.
1015: */
1016:
1.1 abaird 1017: public String getGlobalHeader(String name) {
1018: return template.getValue(name);
1.18 abaird 1019: }
1020:
1.65 ylafon 1021:
1.18 abaird 1022: /**
1023: * Dump all in-memory cached state to persistent storage.
1024: */
1025:
1026: public void sync() {
1027: filteng.sync();
1.1 abaird 1028: }
1029:
1030: /**
1031: * Create a new HttpManager.
1.33 abaird 1032: * FIXME Making this method protected breaks the static method
1033: * to create HttpManager instances (should use a factory here)
1.1 abaird 1034: * @param props The properties from which the manager should initialize
1035: * itself, or <strong>null</strong> if none are available.
1036: */
1037:
1.33 abaird 1038: protected HttpManager() {
1.9 abaird 1039: this.template = new Request(this);
1040: this.servers = new Hashtable();
1.83 ylafon 1041: this._tmp_servers = new Hashtable();
1.9 abaird 1042: this.filteng = new FilterEngine();
1043: this.connectionsLru = new SyncLRUList();
1.1 abaird 1044: }
1045:
1.83 ylafon 1046:
1.1 abaird 1047: /**
1048: * DEBUGGING !
1049: */
1050:
1.83 ylafon 1051: public synchronized String toString() {
1052: StringBuffer sb = new StringBuffer();
1053: HttpConnection hcn = (HttpConnection) connectionsLru.getHead();
1054: sb.append("Connections: ");
1055: sb.append(conn_count);
1056: sb.append(" out of ");
1057: sb.append(conn_max);
1058: sb.append("\n\n");
1059: if (hcn != null) {
1060: sb.append("**** Idle Connections list ****\n");
1061: while (hcn != null) {
1062: sb.append(" ");
1063: sb.append(hcn.toString());
1064: sb.append('\n');
1065: try {
1066: hcn = (HttpConnection) hcn.getNext();
1067: } catch (ClassCastException ccex) {
1068: break;
1069: }
1070: }
1071: } else {
1072: sb.append ("*** NO IDLE CONNECTIONS ***\n");
1073: }
1074: sb.append(servers);
1075: return sb.toString();
1076: }
1077:
1.1 abaird 1078: public static void main(String args[]) {
1079: try {
1080: // Get the manager, and define some global headers:
1081: HttpManager manager = HttpManager.getManager();
1.84 ! ylafon 1082: manager.setGlobalHeader("User-Agent", DEFAULT_USER_AGENT);
1.1 abaird 1083: manager.setGlobalHeader("Accept", "*/*;q=1.0");
1084: manager.setGlobalHeader("Accept-Encoding", "gzip");
1.34 bmahe 1085: PropRequestFilter filter =
1.38 bmahe 1086: new org.w3c.www.protocol.http.cookies.CookieFilter();
1.34 bmahe 1087: filter.initialize(manager);
1.45 ylafon 1088: PropRequestFilter pdebug =
1.38 bmahe 1089: new org.w3c.www.protocol.http.DebugFilter();
1.45 ylafon 1090: pdebug.initialize(manager);
1.1 abaird 1091: Request request = manager.createRequest();
1092: request.setURL(new URL(args[0]));
1093: request.setMethod("GET");
1094: Reply reply = manager.runRequest(request);
1.34 bmahe 1095: //Display some infos:
1.1 abaird 1096: System.out.println("last-modified: "+reply.getLastModified());
1097: System.out.println("length : "+reply.getContentLength());
1098: // Display the returned body:
1099: InputStream in = reply.getInputStream();
1100: byte buf[] = new byte[4096];
1101: int cnt = 0;
1.83 ylafon 1102: while ((cnt = in.read(buf)) >= 0) {
1103: // System.out.print(new String(buf, 0, cnt));
1104: }
1.1 abaird 1105: System.out.println("-");
1106: in.close();
1.34 bmahe 1107: manager.sync();
1.83 ylafon 1108: System.err.println(manager);
1.1 abaird 1109: } catch (Exception ex) {
1110: ex.printStackTrace();
1.80 ylafon 1111: if (ex instanceof HttpException) {
1112: ((HttpException) ex).getException().printStackTrace();
1113: }
1.1 abaird 1114: }
1115: System.exit(1);
1116: }
1117: }
1.34 bmahe 1118:
1119:
Webmaster