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