Annotation of java/classes/org/w3c/www/protocol/http/HttpManager.java, revision 1.57
1.1 abaird 1: // HttpManager.java
1.57 ! ylafon 2: // $Id: HttpManager.java,v 1.56 1999/12/08 14:23:02 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...
1.55 bmahe 213: if (( proxy != null ) && (proxy.getHost() != 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 can be reused, but is now idle.
471: * @param conn The connection that is now idle.
1.4 abaird 472: */
473:
1.57 ! ylafon 474: protected synchronized void notifyIdle(HttpConnection conn) {
1.45 ylafon 475: if (debug)
476: System.out.println("+++ connection idle");
1.9 abaird 477: connectionsLru.toHead(conn);
1.43 ylafon 478: HttpServerState ss = conn.getServer().getState();
479: ss.registerConnection(conn);
1.47 ylafon 480: notify();
1.4 abaird 481: }
482:
483: /**
1.9 abaird 484: * The given connection has just been created.
485: * @param conn The newly created connection.
486: */
487:
488: protected synchronized void notifyConnection(HttpConnection conn) {
1.45 ylafon 489: if (debug)
490: System.out.println("+++ notify conn_count " + (conn_count+1)
491: + " / " + conn_max);
1.9 abaird 492: if ( ++conn_count > conn_max )
493: closeAnyConnection();
494: }
495:
496: /**
497: * The given connection has been deleted.
498: * @param conn The deleted connection.
499: */
500:
1.57 ! ylafon 501: protected synchronized void deleteConnection(HttpConnection conn) {
1.9 abaird 502: HttpServerState ss = conn.getServer().getState();
503: ss.deleteConnection(conn);
1.57 ! ylafon 504: --conn_count;
! 505: if (debug)
! 506: System.out.println("+++ delete conn_count: " + conn_count);
! 507: notify();
1.9 abaird 508: }
509:
1.57 ! ylafon 510: /** Are there too many connections to create a new one? */
1.9 abaird 511: protected synchronized boolean tooManyConnections() {
1.51 ylafon 512: return conn_count >= conn_max;
1.9 abaird 513: }
514:
515: /**
516: * Try reusing one of the idle connection of that server, if any.
517: * @param server The target server.
518: * @return An currently idle connection to the given server.
1.4 abaird 519: */
520:
1.57 ! ylafon 521: protected synchronized HttpConnection getConnection(HttpServer server) {
1.9 abaird 522: HttpServerState ss = server.getState();
1.57 ! ylafon 523: HttpConnection conn = ss.getConnection();
! 524: if ( conn != null ) {
! 525: connectionsLru.remove( conn );
! 526: if (debug)
! 527: System.out.println("+++ connection used");
! 528: }
! 529: return conn;
1.9 abaird 530: }
531:
1.47 ylafon 532: /**
533: * Wait for a connection to come up.
534: * @param server, the target server.
1.48 bmahe 535: * @exception InterruptedException If interrupted..
1.47 ylafon 536: */
537:
1.9 abaird 538: protected synchronized void waitForConnection(HttpServer server)
539: throws InterruptedException
540: {
1.57 ! ylafon 541: // Only wait if there are still too many connections to make a new one. This
! 542: // test avoids a race condition.
! 543: if ( tooManyConnections() )
! 544: wait();
1.4 abaird 545: }
546:
547: /**
1.57 ! ylafon 548: * Close some connections, but picking the least recently used ones.
1.45 ylafon 549: * One third of the max number of connection is cut. This is done to
550: * eliminate the old connections that should be broken already.
551: * (no Socket.isAlive());
1.9 abaird 552: * @return A boolean, <strong>true</strong> if a connection was closed
553: * <strong>false</strong> otherwise.
1.4 abaird 554: */
555:
1.57 ! ylafon 556: protected synchronized boolean closeAnyConnection() {
1.45 ylafon 557: boolean saved = false;
1.47 ylafon 558: int max = Math.max(conn_max/3, 1);
1.45 ylafon 559: for (int i=0; i < max; i++) {
560: HttpConnection conn = (HttpConnection) connectionsLru.removeTail();
561: if ( conn != null ) {
562: conn.close();
563: deleteConnection(conn);
1.57 ! ylafon 564: saved = true;
1.45 ylafon 565: if (debug)
566: System.out.println("+++ close request");
1.47 ylafon 567: } else
568: break;
1.9 abaird 569: }
1.45 ylafon 570: return saved;
1.4 abaird 571: }
572:
573: /**
1.1 abaird 574: * One of our server handler wants to open a connection.
575: * @param block A boolean indicating whether we should block the calling
576: * thread until a token is available (otherwise, the method will just
577: * peek at the connection count, and return the appropriate result).
578: * @return A boolean, <strong>true</strong> if the connection can be
579: * opened straight, <strong>false</strong> otherwise.
580: */
581:
1.9 abaird 582: protected boolean negotiateConnection(HttpServer server) {
583: HttpServerState ss = server.getState();
1.10 abaird 584: if ( ! tooManyConnections() ) {
1.4 abaird 585: return true;
1.10 abaird 586: } else if ( ss.notEnoughConnections() ) {
587: return closeAnyConnection();
1.9 abaird 588: } else if ( servers.size() > conn_max ) {
589: return closeAnyConnection();
1.4 abaird 590: }
1.9 abaird 591: return false;
1.1 abaird 592: }
593:
594: /**
595: * Run the given request, in synchronous mode.
596: * This method will launch the given request, and block the calling thread
597: * until the response headers are available.
598: * @param request The request to run.
599: * @return An instance of Reply, containing all the reply
600: * informations.
1.42 bmahe 601: * @exception HttpException If something failed during request processing.
1.1 abaird 602: */
603:
604: public Reply runRequest(Request request)
605: throws HttpException
606: {
1.19 abaird 607: Reply reply = null;
608: int fcalls = 0;
1.1 abaird 609: // Now run through the ingoing filters:
610: RequestFilter filters[] = filteng.run(request);
611: if ( filters != null ) {
612: for (int i = 0 ; i < filters.length ; i++) {
1.19 abaird 613: if ((reply = filters[fcalls].ingoingFilter(request)) != null)
614: break;
615: fcalls++;
1.1 abaird 616: }
617: }
1.16 abaird 618: // Locate the appropriate target server:
1.31 abaird 619: URL target = request.getURL();
1.19 abaird 620: if ( reply == null ) {
1.32 abaird 621: HttpServer srv = null;
1.22 ylafon 622: boolean rtry ;
1.21 abaird 623: do {
1.22 ylafon 624: rtry = false;
1.21 abaird 625: try {
1.32 abaird 626: URL proxy = request.getProxy();
627: if ( proxy != null )
628: srv = lookupServer(proxy.getHost(), proxy.getPort());
629: else
630: srv = lookupServer(target.getHost(), target.getPort());
1.30 abaird 631: request.setServer(srv);
1.21 abaird 632: reply = srv.runRequest(request);
633: } catch (HttpException ex) {
634: for (int i = 0; i < fcalls; i++)
635: rtry = rtry || filters[i].exceptionFilter(request, ex);
1.23 abaird 636: if ( ! rtry )
1.22 ylafon 637: throw ex;
1.30 abaird 638: } finally {
639: request.unsetServer();
1.21 abaird 640: }
641: } while (rtry);
1.16 abaird 642: }
1.1 abaird 643: // Apply the filters on the way back:
644: if ( filters != null ) {
1.19 abaird 645: while (--fcalls >= 0) {
646: Reply frep = filters[fcalls].outgoingFilter(request, reply);
647: if ( frep != null ) {
648: reply = frep;
649: break;
650: }
1.3 abaird 651: }
1.1 abaird 652: }
653: return reply;
654: }
655:
656: /**
657: * Get this manager's reply factory.
658: * The Reply factory is used when prsing incomming reply from servers, it
659: * decides what object will be created to hold the actual reply from the
660: * server.
661: * @return An object compatible with the MimeParserFactory interface.
662: */
663:
664: MimeParserFactory factory = null ;
665:
1.9 abaird 666: public MimeParserFactory getReplyFactory() {
1.1 abaird 667: return factory;
668: }
669:
670: /**
671: * Add a new request filter.
672: * Request filters are called <em>before</em> a request is launched, and
673: * <em>after</em> the reply headers are available. They allow applications
674: * to setup specific request headers (such as PICS, or PEP stuff) on the
675: * way in, and check the reply on the way out.
676: * <p>Request filters are application wide: if their scope matches
677: * the current request, then they will always be aplied.
678: * <p>Filter scopes are defined inclusively and exclusively
1.15 abaird 679: * @param incs The URL domains for which the filter should be triggered.
680: * @param exs The URL domains for which the filter should not be triggered.
1.1 abaird 681: * @param filter The request filter to add.
682: */
683:
684: public void setFilter(URL incs[], URL exs[], RequestFilter filter) {
685: if ( incs != null ) {
686: for (int i = 0 ; i < incs.length ; i++)
687: filteng.setFilter(incs[i], true, filter);
688: }
689: if ( exs != null ) {
690: for (int i = 0 ; i < exs.length ; i++)
691: filteng.setFilter(exs[i], false, filter);
692: }
693: return;
694: }
695:
1.15 abaird 696: /**
697: * Add a global filter.
698: * The given filter will <em>always</em> be invoked.
699: * @param filter The filter to install.
700: */
701:
1.1 abaird 702: public void setFilter(RequestFilter filter) {
703: filteng.setFilter(filter);
704: }
705:
706: /**
1.15 abaird 707: * Find back an instance of a global filter.
708: * This methods allow external classes to get a pointer to installed
709: * filters of a given class.
710: * @param cls The class of the filter to look for.
711: * @return A RequestFilter instance, or <strong>null</strong> if not
712: * found.
1.1 abaird 713: */
714:
1.15 abaird 715: public RequestFilter getGlobalFilter(Class cls) {
716: return filteng.getGlobalFilter(cls);
1.1 abaird 717: }
718:
719: /**
720: * Create a new default outgoing request.
721: * This method should <em>always</em> be used to create outgoing requests.
722: * It will initialize the request with appropriate default values for
723: * the various headers, and make sure that the request is enhanced by
724: * the registered request filters.
725: * @return An instance of Request, suitable to be launched.
726: */
727:
728: public Request createRequest() {
729: return (Request) template.getClone() ;
730: }
731:
732: /**
733: * Global settings - Set the max number of allowed connections.
734: * Set the maximum number of simultaneous connections that can remain
735: * opened. The manager will take care of queuing requests if this number
736: * is reached.
737: * <p>This value defaults to the value of the
1.38 bmahe 738: * <code>org.w3c.www.http.maxConnections</code> property.
1.1 abaird 739: * @param max_conn The allowed maximum simultaneous open connections.
740: */
741:
1.13 abaird 742: public synchronized void setMaxConnections(int max_conn) {
743: this.conn_max = max_conn;
1.35 ylafon 744: }
745:
746: /**
747: * Global settings - Set the timeout on the socket
748: *
749: * <p>This value defaults to the value of the
1.38 bmahe 750: * <code>org.w3c.www.http.Timeout</code> property.
1.35 ylafon 751: * @param timeout The allowed maximum microsecond before a timeout.
752: */
753:
754: public synchronized void setTimeout(int timeout) {
755: this.timeout = timeout;
756: Enumeration e = servers.elements();
757: while (e.hasMoreElements()) {
758: ((HttpServer) e.nextElement()).setTimeout(timeout);
759: }
1.1 abaird 760: }
761:
762: /**
763: * Global settings - Set an optional proxy to use.
764: * Set the proxy to which all requests should be targeted. If the
1.38 bmahe 765: * <code>org.w3c.www.http.proxy</code> property is defined, it will be
1.1 abaird 766: * used as the default value.
767: * @param proxy The URL for the proxy to use.
768: */
769:
770: public void setProxy(URL proxy) {
1.5 abaird 771: template.setProxy(proxy);
1.30 abaird 772: }
773:
774: /**
775: * Does this manager uses a proxy to fulfill requests ?
776: * @return A boolean.
777: */
778:
779: public boolean usingProxy() {
780: return template.hasProxy();
1.1 abaird 781: }
782:
783: /**
784: * Global settings - Set the request timeout.
785: * Once a request has been emited, the HttpManager will sit for this
786: * given number of milliseconds before the request is declared to have
787: * timed-out.
788: * <p>This timeout value defaults to the value of the
1.38 bmahe 789: * <code>org.w3c.www.http.requestTimeout</code> property value.
1.1 abaird 790: * @param ms The timeout value in milliseconds.
791: */
792:
793: public void setRequestTimeout(int ms) {
794: }
795:
796: /**
797: * Global settings - Define a global request header.
798: * Set a default value for some request header. Once defined, the
799: * header will automatically be defined on <em>all</em> outgoing requests
800: * created through the <code>createRequest</code> request.
801: * @param name The name of the header, case insensitive.
802: * @param value It's default value.
803: */
804:
805: public void setGlobalHeader(String name, String value) {
806: template.setValue(name, value);
807: }
808:
1.18 abaird 809: /**
810: * Global settings - Get a global request header default value.
811: * @param name The name of the header to get.
812: * @return The value for that header, as a String, or <strong>
813: * null</strong> if undefined.
814: */
815:
1.1 abaird 816: public String getGlobalHeader(String name) {
817: return template.getValue(name);
1.18 abaird 818: }
819:
820:
821: /**
822: * Dump all in-memory cached state to persistent storage.
823: */
824:
825: public void sync() {
826: filteng.sync();
1.1 abaird 827: }
828:
829: /**
830: * Create a new HttpManager.
1.33 abaird 831: * FIXME Making this method protected breaks the static method
832: * to create HttpManager instances (should use a factory here)
1.1 abaird 833: * @param props The properties from which the manager should initialize
834: * itself, or <strong>null</strong> if none are available.
835: */
836:
1.33 abaird 837: protected HttpManager() {
1.9 abaird 838: this.template = new Request(this);
839: this.servers = new Hashtable();
840: this.filteng = new FilterEngine();
841: this.connectionsLru = new SyncLRUList();
1.1 abaird 842: }
843:
844: /**
845: * DEBUGGING !
846: */
847:
848: public static void main(String args[]) {
849: try {
850: // Get the manager, and define some global headers:
851: HttpManager manager = HttpManager.getManager();
852: manager.setGlobalHeader("User-Agent", "Jigsaw/1.0a");
853: manager.setGlobalHeader("Accept", "*/*;q=1.0");
854: manager.setGlobalHeader("Accept-Encoding", "gzip");
1.34 bmahe 855: PropRequestFilter filter =
1.38 bmahe 856: new org.w3c.www.protocol.http.cookies.CookieFilter();
1.34 bmahe 857: filter.initialize(manager);
1.45 ylafon 858: PropRequestFilter pdebug =
1.38 bmahe 859: new org.w3c.www.protocol.http.DebugFilter();
1.45 ylafon 860: pdebug.initialize(manager);
1.1 abaird 861: Request request = manager.createRequest();
862: request.setURL(new URL(args[0]));
863: request.setMethod("GET");
864: Reply reply = manager.runRequest(request);
1.34 bmahe 865: //Display some infos:
1.1 abaird 866: System.out.println("last-modified: "+reply.getLastModified());
867: System.out.println("length : "+reply.getContentLength());
868: // Display the returned body:
869: InputStream in = reply.getInputStream();
870: byte buf[] = new byte[4096];
871: int cnt = 0;
872: while ((cnt = in.read(buf)) > 0)
1.56 ylafon 873: System.out.print(new String(buf, 0, cnt));
1.1 abaird 874: System.out.println("-");
875: in.close();
1.34 bmahe 876: manager.sync();
1.1 abaird 877: } catch (Exception ex) {
878: ex.printStackTrace();
879: }
880: System.exit(1);
881: }
882: }
1.34 bmahe 883:
884:
885:
Webmaster