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