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

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

Webmaster