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

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

Webmaster