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