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

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

Webmaster