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

1.1       abaird      1: // HttpManager.java
1.30    ! abaird      2: // $Id: HttpManager.java,v 1.29 1997/01/28 16:44:33 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:     /**
                    392:      * Get the appropriate server object for handling request to given target.
                    393:      * @param key The server's identifier encoded as a <code>host:port</code>
                    394:      * String.
                    395:      * @return An object complying to the HttpServer interface.
                    396:      * @exception HttpException If the given host name couldn't be resolved.
                    397:      */
                    398: 
1.5       abaird    399:     protected synchronized HttpServer lookupServer(String host, int port)
1.1       abaird    400:        throws HttpException
                    401:     {
1.5       abaird    402:        int    p  = (port == -1) ? 80 : port;
                    403:        String id = (p == 80) ? host : (host +":"+p);
1.1       abaird    404:        // Check for an existing server:
                    405:        HttpServer server = (HttpServer) servers.get(id);
                    406:        if ( server != null )
                    407:            return server;
                    408:        // Create and register a new server:
1.17      abaird    409:        try {
                    410:            server = (HttpServer) serverclass.newInstance();
                    411:        } catch (Exception ex) {
                    412:            String msg = ("Unable to create an instance of \""
                    413:                          + serverclass.getName()
                    414:                          + "\", invalid config, check the "
                    415:                          + SERVER_CLASS_P + " property.");
1.21      abaird    416:            throw new HttpException(ex, msg);
1.17      abaird    417:        }
1.9       abaird    418:        server.initialize(this, new HttpServerState(server), host, p);
1.1       abaird    419:        servers.put(id, server);
                    420:        return server;
                    421:     }
1.5       abaird    422: 
1.1       abaird    423:     /**
1.9       abaird    424:      * The given connection is about to be used.
1.4       abaird    425:      * Update our list of available servers.
1.9       abaird    426:      * @param conn The idle connection.
1.4       abaird    427:      */
                    428: 
1.9       abaird    429:     public void notifyUse(HttpConnection conn) {
                    430:        connectionsLru.remove(conn);
1.4       abaird    431:     }
                    432: 
                    433:     /**
1.9       abaird    434:      * The given connection can be reused, but is now idle.
                    435:      * @param conn The connection that is now idle.
1.4       abaird    436:      */
                    437: 
1.9       abaird    438:     public void notifyIdle(HttpConnection conn) {
                    439:        connectionsLru.toHead(conn);
1.4       abaird    440:     }
                    441: 
                    442:     /**
1.9       abaird    443:      * The given connection has just been created.
                    444:      * @param conn The newly created connection.
                    445:      */
                    446: 
                    447:     protected synchronized void notifyConnection(HttpConnection conn) {
                    448:        if ( ++conn_count > conn_max )
                    449:            closeAnyConnection();
                    450:     }
                    451: 
                    452:     /**
                    453:      * The given connection has been deleted.
                    454:      * @param conn The deleted connection.
                    455:      */
                    456: 
                    457:     protected void deleteConnection(HttpConnection conn) {
                    458:        HttpServerState ss = conn.getServer().getState();
                    459:        ss.deleteConnection(conn);
                    460:        synchronized(this) {
                    461:            --conn_count;
                    462:            notifyAll();
                    463:        }
                    464:     }
                    465: 
                    466:     protected synchronized boolean tooManyConnections() {
                    467:        return conn_count > conn_max;
                    468:     }
                    469: 
                    470:     /**
                    471:      * Try reusing one of the idle connection of that server, if any.
                    472:      * @param server The target server.
                    473:      * @return An currently idle connection to the given server.
1.4       abaird    474:      */
                    475: 
1.9       abaird    476:     protected HttpConnection getConnection(HttpServer server) {
                    477:        HttpServerState ss = server.getState();
                    478:        return ss.getConnection();
                    479:     }
                    480: 
                    481:     protected synchronized void waitForConnection(HttpServer server)
                    482:        throws InterruptedException
                    483:     {
                    484:        wait();
1.4       abaird    485:     }
                    486: 
                    487:     /**
1.9       abaird    488:      * Close one connection, but pickling the least recently used one.
                    489:      * @return A boolean, <strong>true</strong> if a connection was closed
                    490:      * <strong>false</strong> otherwise.
1.4       abaird    491:      */
                    492: 
1.9       abaird    493:     protected boolean closeAnyConnection() {
                    494:        HttpConnection conn = (HttpConnection) connectionsLru.removeTail();
                    495:        if ( conn != null ) {
                    496:            conn.close();
                    497:            deleteConnection(conn);
                    498:            return true;
                    499:        } else {
                    500:            return false;
                    501:        }
1.4       abaird    502:     }
                    503: 
                    504:     /**
1.1       abaird    505:      * One of our server handler wants to open a connection.
                    506:      * @param block A boolean indicating whether we should block the calling
                    507:      * thread until a token is available (otherwise, the method will just
                    508:      * peek at the connection count, and return the appropriate result).
                    509:      * @return A boolean, <strong>true</strong> if the connection can be
                    510:      * opened straight, <strong>false</strong> otherwise.
                    511:      */
                    512: 
1.9       abaird    513:     protected boolean negotiateConnection(HttpServer server) {
                    514:        HttpServerState ss = server.getState();
1.10      abaird    515:        if ( ! tooManyConnections() ) {
1.4       abaird    516:            return true;
1.10      abaird    517:        } else if ( ss.notEnoughConnections() ) {
                    518:            return closeAnyConnection();
1.9       abaird    519:        } else if ( servers.size() > conn_max ) {
                    520:            return closeAnyConnection();
1.4       abaird    521:        }
1.9       abaird    522:        return false;
                    523:     }
                    524: 
                    525:     /**
                    526:      * A new client connection has been established.
                    527:      * This method will try to maintain a maximum number of established
                    528:      * connections, by closing idle connections when possible.
                    529:      * @param server The server that has established a new connection.
                    530:      */
                    531: 
                    532:     protected final synchronized void incrConnCount(HttpServer server) {
                    533:        if ( ++conn_count > conn_max )
                    534:            closeAnyConnection();
                    535:     }
                    536: 
                    537:     /**
                    538:      * Decrement the number of established connections.
                    539:      * @param server The server that has closed one connection to its target.
                    540:      */
                    541: 
                    542:     protected final synchronized void decrConnCount(HttpServer server) {
                    543:        --conn_count;
1.1       abaird    544:     }
                    545: 
                    546:     /**
                    547:      * Run the given request, in synchronous mode.
                    548:      * This method will launch the given request, and block the calling thread
                    549:      * until the response headers are available.
                    550:      * @param request The request to run.
                    551:      * @return An instance of Reply, containing all the reply 
                    552:      * informations.
                    553:      * @exception HTTPException If something failed during request processing.
                    554:      */
                    555:     
                    556:     public Reply runRequest(Request request)
                    557:        throws HttpException
                    558:     {
1.19      abaird    559:        URL   target = request.getURL();
                    560:        Reply reply  = null;
                    561:        int   fcalls = 0;
1.1       abaird    562:        // Now run through the ingoing filters:
                    563:        RequestFilter filters[] = filteng.run(request);
                    564:        if ( filters != null ) {
                    565:            for (int i = 0 ; i < filters.length ; i++) {
1.19      abaird    566:                if ((reply = filters[fcalls].ingoingFilter(request)) != null)
                    567:                    break;
                    568:                fcalls++;
1.1       abaird    569:            }
                    570:        }
1.16      abaird    571:        // Locate the appropriate target server:
1.19      abaird    572:        if ( reply == null ) {
1.21      abaird    573:            HttpServer srv    = null;
1.22      ylafon    574:            URL        proxy;
                    575:            boolean    rtry ;
1.21      abaird    576:            do {
1.22      ylafon    577:                rtry = false;
1.21      abaird    578:                try {
1.22      ylafon    579:                    proxy = request.getProxy();
1.21      abaird    580:                    srv = ((proxy != null)
                    581:                           ? lookupServer(proxy.getHost(), proxy.getPort())
                    582:                           : lookupServer(target.getHost(), target.getPort()));
1.30    ! abaird    583:                    request.setServer(srv);
1.21      abaird    584:                    reply = srv.runRequest(request);
                    585:                } catch (HttpException ex) {
                    586:                    for (int i = 0; i < fcalls; i++)
                    587:                        rtry = rtry || filters[i].exceptionFilter(request, ex);
1.23      abaird    588:                    if ( ! rtry )
1.22      ylafon    589:                        throw ex;
1.30    ! abaird    590:                } finally {
        !           591:                    request.unsetServer();
1.21      abaird    592:                }
                    593:            } while (rtry);
1.16      abaird    594:        }
1.1       abaird    595:        // Apply the filters on the way back:
                    596:        if ( filters != null ) {
1.19      abaird    597:            while (--fcalls >= 0) {
                    598:                Reply frep = filters[fcalls].outgoingFilter(request, reply);
                    599:                if ( frep != null ) {
                    600:                    reply = frep;
                    601:                    break;
                    602:                }
1.3       abaird    603:            }
1.1       abaird    604:        }
                    605:        return reply;
                    606:     }
                    607: 
                    608:     /**
                    609:      * Get this manager's reply factory.
                    610:      * The Reply factory is used when prsing incomming reply from servers, it
                    611:      * decides what object will be created to hold the actual reply from the 
                    612:      * server.
                    613:      * @return An object compatible with the MimeParserFactory interface.
                    614:      */
                    615: 
                    616:     MimeParserFactory factory = null ;
                    617: 
1.9       abaird    618:     public MimeParserFactory getReplyFactory() {
1.1       abaird    619:        return factory;
                    620:     }
                    621: 
                    622:     /**
                    623:      * Add a new request filter.
                    624:      * Request filters are called <em>before</em> a request is launched, and
                    625:      * <em>after</em> the reply headers are available. They allow applications
                    626:      * to setup specific request headers (such as PICS, or PEP stuff) on the
                    627:      * way in, and check the reply on the way out.
                    628:      * <p>Request filters are application wide: if their scope matches
                    629:      * the current request, then they will always be aplied.
                    630:      * <p>Filter scopes are defined inclusively and exclusively
1.15      abaird    631:      * @param incs The URL domains for which the filter should be triggered.
                    632:      * @param exs The URL domains for which the filter should not be triggered.
1.1       abaird    633:      * @param filter The request filter to add.
                    634:      */
                    635: 
                    636:     public void setFilter(URL incs[], URL exs[], RequestFilter filter) {
                    637:        if ( incs != null ) {
                    638:            for (int i = 0 ; i < incs.length ; i++)
                    639:                filteng.setFilter(incs[i], true, filter);
                    640:        }
                    641:        if ( exs != null ) {
                    642:            for (int i = 0 ; i < exs.length ; i++)
                    643:                filteng.setFilter(exs[i], false, filter);
                    644:        }
                    645:        return;
                    646:     }
                    647: 
1.15      abaird    648:     /**
                    649:      * Add a global filter.
                    650:      * The given filter will <em>always</em> be invoked.
                    651:      * @param filter The filter to install.
                    652:      */
                    653:     
1.1       abaird    654:     public void setFilter(RequestFilter filter) {
                    655:        filteng.setFilter(filter);
                    656:     }
                    657: 
                    658:     /**
1.15      abaird    659:      * Find back an instance of a global filter.
                    660:      * This methods allow external classes to get a pointer to installed
                    661:      * filters of a given class.
                    662:      * @param cls The class of the filter to look for.
                    663:      * @return A RequestFilter instance, or <strong>null</strong> if not
                    664:      * found.
1.1       abaird    665:      */
                    666: 
1.15      abaird    667:     public RequestFilter getGlobalFilter(Class cls) {
                    668:        return filteng.getGlobalFilter(cls);
1.1       abaird    669:     }
                    670: 
                    671:     /**
                    672:      * Create a new default outgoing request.
                    673:      * This method should <em>always</em> be used to create outgoing requests.
                    674:      * It will initialize the request with appropriate default values for 
                    675:      * the various headers, and make sure that the request is enhanced by
                    676:      * the registered request filters.
                    677:      * @return An instance of Request, suitable to be launched.
                    678:      */
                    679: 
                    680:     public Request createRequest() {
                    681:        return (Request) template.getClone() ;
                    682:     }
                    683: 
                    684:     /**
                    685:      * Global settings - Set the max number of allowed connections.
                    686:      * Set the maximum number of simultaneous connections that can remain
                    687:      * opened. The manager will take care of queuing requests if this number
                    688:      * is reached.
                    689:      * <p>This value defaults to the value of the 
                    690:      * <code>w3c.www.http.maxConnections</code> property.
                    691:      * @param max_conn The allowed maximum simultaneous open connections.
                    692:      */
                    693: 
1.13      abaird    694:     public synchronized void setMaxConnections(int max_conn) {
                    695:        this.conn_max = max_conn;
1.1       abaird    696:     }
                    697: 
                    698:     /**
                    699:      * Global settings - Set an optional proxy to use.
                    700:      * Set the proxy to which all requests should be targeted. If the
                    701:      * <code>w3c.www.http.proxy</code> property is defined, it will be
                    702:      * used as the default value.
                    703:      * @param proxy The URL for the proxy to use.
                    704:      */
                    705: 
                    706:     public void setProxy(URL proxy) {
1.5       abaird    707:        template.setProxy(proxy);
1.30    ! abaird    708:     }
        !           709: 
        !           710:     /**
        !           711:      * Does this manager uses a proxy to fulfill requests ?
        !           712:      * @return A boolean.
        !           713:      */
        !           714: 
        !           715:     public boolean usingProxy() {
        !           716:        return template.hasProxy();
1.1       abaird    717:     }
                    718: 
                    719:     /**
                    720:      * Global settings - Set the request timeout.
                    721:      * Once a request has been emited, the HttpManager will sit for this 
                    722:      * given number of milliseconds before the request is declared to have
                    723:      * timed-out.
                    724:      * <p>This timeout value defaults to the value of the
                    725:      * <code>w3c.www.http.requestTimeout</code> property value.
                    726:      * @param ms The timeout value in milliseconds.
                    727:      */
                    728: 
                    729:     public void setRequestTimeout(int ms) {
                    730:     }
                    731: 
                    732:     /**
                    733:      * Global settings - Define a global request header.
                    734:      * Set a default value for some request header. Once defined, the
                    735:      * header will automatically be defined on <em>all</em> outgoing requests
                    736:      * created through the <code>createRequest</code> request.
                    737:      * @param name The name of the header, case insensitive.
                    738:      * @param value It's default value.
                    739:      */
                    740:     
                    741:     public void setGlobalHeader(String name, String value) {
                    742:        template.setValue(name, value);
                    743:     }
                    744: 
1.18      abaird    745:     /**
                    746:      * Global settings - Get a global request header default value.
                    747:      * @param name The name of the header to get.
                    748:      * @return The value for that header, as a String, or <strong>
                    749:      * null</strong> if undefined.
                    750:      */
                    751: 
1.1       abaird    752:     public String getGlobalHeader(String name) {
                    753:        return template.getValue(name);
1.18      abaird    754:     }
                    755: 
                    756:     
                    757:     /**
                    758:      * Dump all in-memory cached state to persistent storage.
                    759:      */
                    760: 
                    761:     public void sync() {
                    762:        filteng.sync();
1.1       abaird    763:     }
                    764: 
                    765:     /**
                    766:      * Create a new HttpManager.
                    767:      * This can only be called from this package. The caller must rather
                    768:      * use the <code>getManager</code> method.
                    769:      * @param props The properties from which the manager should initialize 
                    770:      * itself, or <strong>null</strong> if none are available.
                    771:      */
                    772: 
1.28      abaird    773:     HttpManager() {
1.9       abaird    774:        this.template       = new Request(this);
                    775:        this.servers        = new Hashtable();
                    776:        this.filteng        = new FilterEngine();
                    777:        this.connectionsLru = new SyncLRUList();
1.1       abaird    778:     }
                    779: 
                    780:     /**
                    781:      * DEBUGGING !
                    782:      */
                    783: 
                    784:     public static void main(String args[]) {
                    785:        try {
                    786:            // Get the manager, and define some global headers:
                    787:            HttpManager manager = HttpManager.getManager();
                    788:            manager.setGlobalHeader("User-Agent", "Jigsaw/1.0a");
                    789:            manager.setGlobalHeader("Accept", "*/*;q=1.0");
                    790:            manager.setGlobalHeader("Accept-Encoding", "gzip");
                    791:            Request request = manager.createRequest();
                    792:            request.setURL(new URL(args[0]));
                    793:            request.setMethod("GET");
                    794:            Reply       reply   = manager.runRequest(request);
                    795:            // Display some infos:
                    796:            System.out.println("last-modified: "+reply.getLastModified());
                    797:            System.out.println("length       : "+reply.getContentLength());
                    798:            // Display the returned body:
                    799:            InputStream in = reply.getInputStream();
                    800:            byte buf[] = new byte[4096];
                    801:            int  cnt   = 0;
                    802:            while ((cnt = in.read(buf)) > 0) 
                    803:                System.out.print(new String(buf, 0, 0, cnt));
                    804:            System.out.println("-");
                    805:            in.close();
                    806:        } catch (Exception ex) {
                    807:            ex.printStackTrace();
                    808:        }
                    809:        System.exit(1);
                    810:     }
                    811: }

Webmaster