Annotation of java/classes/org/w3c/www/protocol/http/HttpManager.java, revision 1.49

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

Webmaster