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