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

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

Webmaster