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

1.1       abaird      1: // HttpManager.java
1.67    ! ylafon      2: // $Id: HttpManager.java,v 1.66 2000/10/11 14:14:06 bmahe 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);
1.67    ! ylafon    413:        if ( sval != null ) {
        !           414:            if (sval.trim().length() > 0) {
        !           415:                tpl.setValue("accept-language", sval);
        !           416:            }
        !           417:        }
1.24      abaird    418:        // General, Accept-Encoding
                    419:        sval = props.getString(ACCEPT_ENCODING_P, null);
                    420:        if ( sval != null )
                    421:            tpl.setValue("accept-encoding", sval);
                    422:        // Maximum number of allowed connections:
                    423:        manager.conn_max = props.getInteger(CONN_MAX_P, 5);
1.58      ylafon    424:        // timeout value
1.59      ylafon    425:        manager.timeout = props.getInteger(TIMEOUT_P, manager.timeout);
1.24      abaird    426:        // Register ourself as a property observer:
                    427:        props.registerObserver(manager);
                    428:        // Register that manager in our knwon managers:
                    429:        for (int i = 0 ; i < managers.length ; i++) {
                    430:            if ( managers[i] == null ) {
1.25      abaird    431:                managers[i] = new ManagerDescription(manager, p);
1.24      abaird    432:                return manager;
1.17      abaird    433:            }
1.1       abaird    434:        }
1.25      abaird    435:        ManagerDescription nm[] = new ManagerDescription[managers.length << 1];
                    436:        System.arraycopy(managers, 0, nm, 0, managers.length);
                    437:        nm[managers.length] = new ManagerDescription(manager, p);
                    438:        managers = nm;
1.1       abaird    439:        return manager;
                    440:     }
1.66      bmahe     441:                                                       
                    442: 
                    443:     /**
                    444:      * Get an instance of the HTTP manager.
                    445:      * This method returns an actual instance of the HTTP manager. It may
                    446:      * return different managers, if it decides to distribute the load on
                    447:      * different managers (avoid the HttpManager being a bottleneck).
                    448:      * @return An application wide instance of the HTTP manager.
                    449:      */
                    450: 
                    451:     public static synchronized HttpManager getManager(Properties p) {
                    452:        return getManager(HttpManager.class, p);
                    453:     }
1.1       abaird    454: 
1.24      abaird    455:     public static HttpManager getManager() {
                    456:        return getManager(System.getProperties());
                    457:     }
1.1       abaird    458: 
                    459:     /**
1.32      abaird    460:      * Get the String key for the server instance handling that request.
                    461:      * This method takes care of any proxy setting (it will return the key
                    462:      * to the proxy when required.)
                    463:      * @return A uniq identifier for the handling server, as a String.
                    464:      */
                    465: 
                    466:     public final String getServerKey(Request request) {
                    467:        URL    proxy  = request.getProxy();
                    468:        URL    target = request.getURL();
                    469:        String key   = null;
                    470:        if ( proxy != null ) {
                    471:            return ((proxy.getPort() == 80)
                    472:                    ? proxy.getHost().toLowerCase()
                    473:                    : (proxy.getHost().toLowerCase()+":"+proxy.getPort()));
                    474:        } else {
                    475:            return ((target.getPort() == 80)
                    476:                    ? target.getHost().toLowerCase()
                    477:                    : (target.getHost().toLowerCase()+":"+target.getPort()));
                    478:        }
                    479:     }
                    480: 
                    481:     /**
1.1       abaird    482:      * Get the appropriate server object for handling request to given target.
1.32      abaird    483:      * @param key The server's key, as returned by <code>getServerKey</code>.
1.1       abaird    484:      * @return An object complying to the HttpServer interface.
                    485:      * @exception HttpException If the given host name couldn't be resolved.
                    486:      */
                    487: 
1.5       abaird    488:     protected synchronized HttpServer lookupServer(String host, int port)
1.1       abaird    489:        throws HttpException
                    490:     {
1.5       abaird    491:        int    p  = (port == -1) ? 80 : port;
1.32      abaird    492:        String id = ((p == 80) 
                    493:                     ? host.toLowerCase() 
                    494:                     : (host.toLowerCase() +":"+p));
1.1       abaird    495:        // Check for an existing server:
                    496:        HttpServer server = (HttpServer) servers.get(id);
                    497:        if ( server != null )
                    498:            return server;
                    499:        // Create and register a new server:
1.17      abaird    500:        try {
                    501:            server = (HttpServer) serverclass.newInstance();
                    502:        } catch (Exception ex) {
                    503:            String msg = ("Unable to create an instance of \""
                    504:                          + serverclass.getName()
                    505:                          + "\", invalid config, check the "
                    506:                          + SERVER_CLASS_P + " property.");
1.21      abaird    507:            throw new HttpException(ex, msg);
1.17      abaird    508:        }
1.35      ylafon    509:        server.initialize(this, new HttpServerState(server), host, p, timeout);
1.1       abaird    510:        servers.put(id, server);
                    511:        return server;
                    512:     }
1.5       abaird    513: 
1.1       abaird    514:     /**
1.60      ylafon    515:      * The given connection is about to be used.
                    516:      * Update our list of available servers.
                    517:      * @param conn The idle connection.
                    518:      */
                    519: 
                    520:     public void notifyUse(HttpConnection conn) {
                    521:        if (debug)
                    522:            System.out.println("+++ connection used");
                    523:        connectionsLru.remove(conn);
                    524:     }
                    525: 
                    526:     /**
1.9       abaird    527:      * The given connection can be reused, but is now idle.
                    528:      * @param conn The connection that is now idle.
1.4       abaird    529:      */
                    530: 
1.60      ylafon    531:     public synchronized void notifyIdle(HttpConnection conn) {
1.45      ylafon    532:        if (debug)
                    533:            System.out.println("+++ connection idle");
1.9       abaird    534:        connectionsLru.toHead(conn);
1.43      ylafon    535:        HttpServerState ss = conn.getServer().getState();
                    536:        ss.registerConnection(conn);
1.63      ylafon    537:        notifyAll();
1.4       abaird    538:     }
                    539: 
                    540:     /**
1.9       abaird    541:      * The given connection has just been created.
                    542:      * @param conn The newly created connection.
                    543:      */
                    544: 
                    545:     protected synchronized void notifyConnection(HttpConnection conn) {
1.45      ylafon    546:        if (debug)
                    547:            System.out.println("+++ notify conn_count " + (conn_count+1)
                    548:                               + " / " + conn_max);
1.9       abaird    549:        if ( ++conn_count > conn_max )
                    550:            closeAnyConnection();
                    551:     }
                    552: 
                    553:     /**
                    554:      * The given connection has been deleted.
                    555:      * @param conn The deleted connection.
                    556:      */
                    557: 
1.60      ylafon    558:     protected void deleteConnection(HttpConnection conn) {
1.9       abaird    559:        HttpServerState ss = conn.getServer().getState();
                    560:        ss.deleteConnection(conn);
1.60      ylafon    561:        synchronized(this) {
                    562:            --conn_count;
                    563:            if (debug)
                    564:                System.out.println("+++ delete conn_count: " + conn_count);
1.63      ylafon    565:            notifyAll();
1.60      ylafon    566:        }
1.9       abaird    567:     }
                    568: 
                    569:     protected synchronized boolean tooManyConnections() {
1.51      ylafon    570:        return conn_count >= conn_max;
1.9       abaird    571:     }
                    572: 
                    573:     /**
                    574:      * Try reusing one of the idle connection of that server, if any.
                    575:      * @param server The target server.
                    576:      * @return An currently idle connection to the given server.
1.4       abaird    577:      */
                    578: 
1.60      ylafon    579:     protected HttpConnection getConnection(HttpServer server) {
1.9       abaird    580:        HttpServerState ss = server.getState();
1.60      ylafon    581:        return ss.getConnection();
1.9       abaird    582:     }
                    583: 
1.47      ylafon    584:     /**
                    585:      * Wait for a connection to come up.
                    586:      * @param server, the target server.
1.48      bmahe     587:      * @exception InterruptedException If interrupted..
1.47      ylafon    588:      */
                    589: 
1.9       abaird    590:     protected synchronized void waitForConnection(HttpServer server)
                    591:        throws InterruptedException
                    592:     {
1.60      ylafon    593:        wait();
1.4       abaird    594:     }
                    595: 
                    596:     /**
1.60      ylafon    597:      * Close some connections, but pickling the least recently used ones.
1.45      ylafon    598:      * One third of the max number of connection is cut. This is done to 
                    599:      * eliminate the old connections that should be broken already.
                    600:      * (no Socket.isAlive());
1.9       abaird    601:      * @return A boolean, <strong>true</strong> if a connection was closed
                    602:      * <strong>false</strong> otherwise.
1.4       abaird    603:      */
                    604: 
1.60      ylafon    605:     protected boolean closeAnyConnection() {
1.45      ylafon    606:        boolean saved = false;
1.47      ylafon    607:        int max = Math.max(conn_max/3, 1);
1.45      ylafon    608:        for (int i=0; i < max; i++) {
                    609:            HttpConnection conn = (HttpConnection) connectionsLru.removeTail();
                    610:            if ( conn != null ) {
                    611:                conn.close();
                    612:                deleteConnection(conn);
                    613:                if (debug)
                    614:                    System.out.println("+++ close request");
1.60      ylafon    615:                    saved = true;
1.47      ylafon    616:            } else
                    617:                break;
1.9       abaird    618:        }
1.45      ylafon    619:        return saved;
1.4       abaird    620:     }
                    621: 
                    622:     /**
1.1       abaird    623:      * One of our server handler wants to open a connection.
                    624:      * @param block A boolean indicating whether we should block the calling
                    625:      * thread until a token is available (otherwise, the method will just
                    626:      * peek at the connection count, and return the appropriate result).
                    627:      * @return A boolean, <strong>true</strong> if the connection can be
                    628:      * opened straight, <strong>false</strong> otherwise.
                    629:      */
                    630: 
1.9       abaird    631:     protected boolean negotiateConnection(HttpServer server) {
                    632:        HttpServerState ss = server.getState();
1.10      abaird    633:        if ( ! tooManyConnections() ) {
1.4       abaird    634:            return true;
1.10      abaird    635:        } else if ( ss.notEnoughConnections() ) {
                    636:            return closeAnyConnection();
1.9       abaird    637:        } else if ( servers.size() > conn_max ) {
                    638:            return closeAnyConnection();
1.4       abaird    639:        }
1.9       abaird    640:        return false;
1.60      ylafon    641:     }
                    642: 
                    643:     /**
                    644:      * A new client connection has been established.
                    645:      * This method will try to maintain a maximum number of established
                    646:      * connections, by closing idle connections when possible.
                    647:      * @param server The server that has established a new connection.
                    648:      */
                    649: 
                    650:     protected final synchronized void incrConnCount(HttpServer server) {
                    651:        if ( ++conn_count > conn_max )
                    652:            closeAnyConnection();
                    653:        if (debug)
                    654:            System.out.println("+++ incr conn_count: " + conn_count);
                    655:     }
                    656: 
                    657:     /**
                    658:      * Decrement the number of established connections.
                    659:      * @param server The server that has closed one connection to its target.
                    660:      */
                    661: 
                    662:     protected final synchronized void decrConnCount(HttpServer server) {
                    663:        --conn_count;
                    664:        if (debug)
                    665:            System.out.println("+++ decr conn_count: " + conn_count);
1.1       abaird    666:     }
                    667: 
                    668:     /**
                    669:      * Run the given request, in synchronous mode.
                    670:      * This method will launch the given request, and block the calling thread
                    671:      * until the response headers are available.
                    672:      * @param request The request to run.
                    673:      * @return An instance of Reply, containing all the reply 
                    674:      * informations.
1.42      bmahe     675:      * @exception HttpException If something failed during request processing.
1.1       abaird    676:      */
1.65      ylafon    677: 
1.1       abaird    678:     public Reply runRequest(Request request)
                    679:        throws HttpException
                    680:     {
1.19      abaird    681:        Reply reply  = null;
                    682:        int   fcalls = 0;
1.1       abaird    683:        // Now run through the ingoing filters:
                    684:        RequestFilter filters[] = filteng.run(request);
                    685:        if ( filters != null ) {
                    686:            for (int i = 0 ; i < filters.length ; i++) {
1.19      abaird    687:                if ((reply = filters[fcalls].ingoingFilter(request)) != null)
                    688:                    break;
                    689:                fcalls++;
1.1       abaird    690:            }
                    691:        }
1.16      abaird    692:        // Locate the appropriate target server:
1.31      abaird    693:        URL target = request.getURL();
1.19      abaird    694:        if ( reply == null ) {
1.32      abaird    695:            HttpServer srv = null;
1.22      ylafon    696:            boolean    rtry ;
1.21      abaird    697:            do {
1.22      ylafon    698:                rtry = false;
1.21      abaird    699:                try {
1.32      abaird    700:                    URL proxy  = request.getProxy();
                    701:                    if ( proxy != null ) 
                    702:                        srv = lookupServer(proxy.getHost(), proxy.getPort());
                    703:                    else
                    704:                        srv = lookupServer(target.getHost(), target.getPort());
1.30      abaird    705:                    request.setServer(srv);
1.21      abaird    706:                    reply = srv.runRequest(request);
                    707:                } catch (HttpException ex) {
                    708:                    for (int i = 0; i < fcalls; i++)
                    709:                        rtry = rtry || filters[i].exceptionFilter(request, ex);
1.23      abaird    710:                    if ( ! rtry )
1.22      ylafon    711:                        throw ex;
1.30      abaird    712:                } finally {
                    713:                    request.unsetServer();
1.21      abaird    714:                }
                    715:            } while (rtry);
1.16      abaird    716:        }
1.1       abaird    717:        // Apply the filters on the way back:
                    718:        if ( filters != null ) {
1.19      abaird    719:            while (--fcalls >= 0) {
                    720:                Reply frep = filters[fcalls].outgoingFilter(request, reply);
                    721:                if ( frep != null ) {
                    722:                    reply = frep;
                    723:                    break;
                    724:                }
1.3       abaird    725:            }
1.1       abaird    726:        }
                    727:        return reply;
                    728:     }
                    729: 
                    730:     /**
                    731:      * Get this manager's reply factory.
                    732:      * The Reply factory is used when prsing incomming reply from servers, it
                    733:      * decides what object will be created to hold the actual reply from the 
                    734:      * server.
                    735:      * @return An object compatible with the MimeParserFactory interface.
                    736:      */
                    737: 
                    738:     MimeParserFactory factory = null ;
                    739: 
1.9       abaird    740:     public MimeParserFactory getReplyFactory() {
1.66      bmahe     741:        if (factory == null) {
                    742:            factory = new ReplyFactory();
                    743:        }
1.1       abaird    744:        return factory;
                    745:     }
                    746: 
                    747:     /**
                    748:      * Add a new request filter.
                    749:      * Request filters are called <em>before</em> a request is launched, and
                    750:      * <em>after</em> the reply headers are available. They allow applications
                    751:      * to setup specific request headers (such as PICS, or PEP stuff) on the
                    752:      * way in, and check the reply on the way out.
                    753:      * <p>Request filters are application wide: if their scope matches
                    754:      * the current request, then they will always be aplied.
                    755:      * <p>Filter scopes are defined inclusively and exclusively
1.15      abaird    756:      * @param incs The URL domains for which the filter should be triggered.
                    757:      * @param exs The URL domains for which the filter should not be triggered.
1.1       abaird    758:      * @param filter The request filter to add.
                    759:      */
                    760: 
                    761:     public void setFilter(URL incs[], URL exs[], RequestFilter filter) {
                    762:        if ( incs != null ) {
                    763:            for (int i = 0 ; i < incs.length ; i++)
                    764:                filteng.setFilter(incs[i], true, filter);
                    765:        }
                    766:        if ( exs != null ) {
                    767:            for (int i = 0 ; i < exs.length ; i++)
                    768:                filteng.setFilter(exs[i], false, filter);
                    769:        }
                    770:        return;
                    771:     }
                    772: 
1.15      abaird    773:     /**
                    774:      * Add a global filter.
                    775:      * The given filter will <em>always</em> be invoked.
                    776:      * @param filter The filter to install.
                    777:      */
1.65      ylafon    778: 
1.1       abaird    779:     public void setFilter(RequestFilter filter) {
                    780:        filteng.setFilter(filter);
                    781:     }
                    782: 
                    783:     /**
1.15      abaird    784:      * Find back an instance of a global filter.
                    785:      * This methods allow external classes to get a pointer to installed
                    786:      * filters of a given class.
                    787:      * @param cls The class of the filter to look for.
                    788:      * @return A RequestFilter instance, or <strong>null</strong> if not
                    789:      * found.
1.1       abaird    790:      */
                    791: 
1.15      abaird    792:     public RequestFilter getGlobalFilter(Class cls) {
                    793:        return filteng.getGlobalFilter(cls);
1.1       abaird    794:     }
                    795: 
                    796:     /**
                    797:      * Create a new default outgoing request.
                    798:      * This method should <em>always</em> be used to create outgoing requests.
                    799:      * It will initialize the request with appropriate default values for 
                    800:      * the various headers, and make sure that the request is enhanced by
                    801:      * the registered request filters.
                    802:      * @return An instance of Request, suitable to be launched.
                    803:      */
                    804: 
                    805:     public Request createRequest() {
                    806:        return (Request) template.getClone() ;
                    807:     }
                    808: 
                    809:     /**
                    810:      * Global settings - Set the max number of allowed connections.
                    811:      * Set the maximum number of simultaneous connections that can remain
                    812:      * opened. The manager will take care of queuing requests if this number
                    813:      * is reached.
                    814:      * <p>This value defaults to the value of the 
1.38      bmahe     815:      * <code>org.w3c.www.http.maxConnections</code> property.
1.1       abaird    816:      * @param max_conn The allowed maximum simultaneous open connections.
                    817:      */
                    818: 
1.13      abaird    819:     public synchronized void setMaxConnections(int max_conn) {
                    820:        this.conn_max = max_conn;
1.35      ylafon    821:     }
                    822: 
                    823:     /**
                    824:      * Global settings - Set the timeout on the socket
                    825:      *
                    826:      * <p>This value defaults to the value of the 
1.38      bmahe     827:      * <code>org.w3c.www.http.Timeout</code> property.
1.35      ylafon    828:      * @param timeout The allowed maximum microsecond before a timeout.
                    829:      */
                    830: 
                    831:     public synchronized void setTimeout(int timeout) {
                    832:        this.timeout = timeout;
                    833:        Enumeration e = servers.elements();
                    834:        while (e.hasMoreElements()) {
                    835:            ((HttpServer) e.nextElement()).setTimeout(timeout);
                    836:        }
1.62      ylafon    837:     }
                    838: 
                    839:     /**
                    840:      * Global settings - set the HTTP parsing lenient or not.
                    841:      * @param lenient, true by default, false to detect wrong servers
                    842:      */
                    843:     public void setLenient(boolean lenient) {
                    844:        this.lenient = lenient;
                    845:     }
                    846: 
                    847:     /**
                    848:      * Is this manager parsing headers in a lenient way?
                    849:      * @return A boolean.
                    850:      */
                    851:     public boolean isLenient() {
                    852:        return lenient;
1.1       abaird    853:     }
                    854: 
                    855:     /**
                    856:      * Global settings - Set an optional proxy to use.
                    857:      * Set the proxy to which all requests should be targeted. If the
1.38      bmahe     858:      * <code>org.w3c.www.http.proxy</code> property is defined, it will be
1.1       abaird    859:      * used as the default value.
                    860:      * @param proxy The URL for the proxy to use.
                    861:      */
                    862: 
                    863:     public void setProxy(URL proxy) {
1.5       abaird    864:        template.setProxy(proxy);
1.30      abaird    865:     }
                    866: 
                    867:     /**
                    868:      * Does this manager uses a proxy to fulfill requests ?
                    869:      * @return A boolean.
                    870:      */
                    871: 
                    872:     public boolean usingProxy() {
                    873:        return template.hasProxy();
1.1       abaird    874:     }
                    875: 
                    876:     /**
                    877:      * Global settings - Set the request timeout.
                    878:      * Once a request has been emited, the HttpManager will sit for this 
                    879:      * given number of milliseconds before the request is declared to have
                    880:      * timed-out.
                    881:      * <p>This timeout value defaults to the value of the
1.38      bmahe     882:      * <code>org.w3c.www.http.requestTimeout</code> property value.
1.1       abaird    883:      * @param ms The timeout value in milliseconds.
                    884:      */
                    885: 
                    886:     public void setRequestTimeout(int ms) {
                    887:     }
                    888: 
                    889:     /**
                    890:      * Global settings - Define a global request header.
                    891:      * Set a default value for some request header. Once defined, the
                    892:      * header will automatically be defined on <em>all</em> outgoing requests
                    893:      * created through the <code>createRequest</code> request.
                    894:      * @param name The name of the header, case insensitive.
                    895:      * @param value It's default value.
                    896:      */
1.65      ylafon    897: 
1.1       abaird    898:     public void setGlobalHeader(String name, String value) {
                    899:        template.setValue(name, value);
                    900:     }
                    901: 
1.18      abaird    902:     /**
                    903:      * Global settings - Get a global request header default value.
                    904:      * @param name The name of the header to get.
                    905:      * @return The value for that header, as a String, or <strong>
                    906:      * null</strong> if undefined.
                    907:      */
                    908: 
1.1       abaird    909:     public String getGlobalHeader(String name) {
                    910:        return template.getValue(name);
1.18      abaird    911:     }
                    912: 
1.65      ylafon    913:    
1.18      abaird    914:     /**
                    915:      * Dump all in-memory cached state to persistent storage.
                    916:      */
                    917: 
                    918:     public void sync() {
                    919:        filteng.sync();
1.1       abaird    920:     }
                    921: 
                    922:     /**
                    923:      * Create a new HttpManager.
1.33      abaird    924:      * FIXME Making this method protected breaks the static method
                    925:      * to create HttpManager instances (should use a factory here)
1.1       abaird    926:      * @param props The properties from which the manager should initialize 
                    927:      * itself, or <strong>null</strong> if none are available.
                    928:      */
                    929: 
1.33      abaird    930:     protected HttpManager() {
1.9       abaird    931:        this.template       = new Request(this);
                    932:        this.servers        = new Hashtable();
                    933:        this.filteng        = new FilterEngine();
                    934:        this.connectionsLru = new SyncLRUList();
1.1       abaird    935:     }
                    936: 
                    937:     /**
                    938:      * DEBUGGING !
                    939:      */
                    940: 
                    941:     public static void main(String args[]) {
                    942:        try {
                    943:            // Get the manager, and define some global headers:
                    944:            HttpManager manager = HttpManager.getManager();
                    945:            manager.setGlobalHeader("User-Agent", "Jigsaw/1.0a");
                    946:            manager.setGlobalHeader("Accept", "*/*;q=1.0");
                    947:            manager.setGlobalHeader("Accept-Encoding", "gzip");
1.34      bmahe     948:            PropRequestFilter filter = 
1.38      bmahe     949:              new org.w3c.www.protocol.http.cookies.CookieFilter();
1.34      bmahe     950:            filter.initialize(manager);
1.45      ylafon    951:            PropRequestFilter pdebug = 
1.38      bmahe     952:              new org.w3c.www.protocol.http.DebugFilter();
1.45      ylafon    953:            pdebug.initialize(manager);
1.1       abaird    954:            Request request = manager.createRequest();
                    955:            request.setURL(new URL(args[0]));
                    956:            request.setMethod("GET");
                    957:            Reply       reply   = manager.runRequest(request);
1.34      bmahe     958:            //Display some infos:
1.1       abaird    959:            System.out.println("last-modified: "+reply.getLastModified());
                    960:            System.out.println("length       : "+reply.getContentLength());
                    961:            // Display the returned body:
                    962:            InputStream in = reply.getInputStream();
                    963:            byte buf[] = new byte[4096];
                    964:            int  cnt   = 0;
                    965:            while ((cnt = in.read(buf)) > 0) 
1.56      ylafon    966:              System.out.print(new String(buf, 0, cnt));
1.1       abaird    967:            System.out.println("-");
                    968:            in.close();
1.34      bmahe     969:            manager.sync();
1.1       abaird    970:        } catch (Exception ex) {
                    971:            ex.printStackTrace();
                    972:        }
                    973:        System.exit(1);
                    974:     }
                    975: }
1.34      bmahe     976: 
                    977: 

Webmaster