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

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

Webmaster