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