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