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