FileDocCategorySizeDatePackage
Connector.javaAPI DocApache Tomcat 6.0.1436061Fri Jul 20 04:20:36 BST 2007org.apache.catalina.connector

Connector

public class Connector extends Object implements org.apache.catalina.Lifecycle, MBeanRegistration
Implementation of a Coyote connector for Tomcat 5.x.
author
Craig R. McClanahan
author
Remy Maucherat
version
$Revision: 480000 $ $Date: 2006-11-28 12:31:04 +0100 (mar., 28 nov. 2006) $

Fields Summary
private static org.apache.juli.logging.Log
log
public static final boolean
RECYCLE_FACADES
Alternate flag to enable recycling of facades.
protected org.apache.catalina.Service
service
The Service we are associated with (if any).
protected boolean
allowTrace
Do we allow TRACE ?
protected org.apache.catalina.Container
container
The Container used for processing requests received by this Connector.
protected boolean
emptySessionPath
Use "/" as path for session cookies ?
protected boolean
enableLookups
The "enable DNS lookups" flag for this Connector.
protected boolean
xpoweredBy
protected static final String
info
Descriptive information about this Connector implementation.
protected org.apache.catalina.util.LifecycleSupport
lifecycle
The lifecycle event support for this component.
protected int
port
The port number on which we listen for requests.
protected String
proxyName
The server name to which we should pretend requests to this Connector were directed. This is useful when operating Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the server name included in the Host header is used.
protected int
proxyPort
The server port to which we should pretent requests to this Connector were directed. This is useful when operating Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the port number specified by the port property is used.
protected int
redirectPort
The redirect port for non-SSL to SSL redirects.
protected String
scheme
The request scheme that will be set on all requests received through this connector.
protected boolean
secure
The secure connection flag that will be set on all requests received through this connector.
protected org.apache.catalina.util.StringManager
sm
The string manager for this package.
protected int
maxPostSize
Maximum size of a POST which will be automatically parsed by the container. 2MB by default.
protected int
maxSavePostSize
Maximum size of a POST which will be saved by the container during authentication. 4kB by default
protected boolean
initialized
Has this component been initialized yet?
protected boolean
started
Has this component been started yet?
protected boolean
stopped
The shutdown signal to our background thread
protected boolean
useIPVHosts
Flag to use IP-based virtual hosting.
protected Thread
thread
The background thread.
protected String
protocolHandlerClassName
Coyote Protocol handler class name. Defaults to the Coyote HTTP/1.1 protocolHandler.
protected org.apache.coyote.ProtocolHandler
protocolHandler
Coyote protocol handler.
protected org.apache.coyote.Adapter
adapter
Coyote adapter.
protected org.apache.tomcat.util.http.mapper.Mapper
mapper
Mapper.
protected MapperListener
mapperListener
Mapper listener.
protected String
URIEncoding
URI encoding.
protected boolean
useBodyEncodingForURI
URI encoding as body.
protected static HashMap
replacements
private static final int
TCN_REQUIRED_MAJOR
private static final int
TCN_REQUIRED_MINOR
private static final int
TCN_REQUIRED_PATCH
private static boolean
aprInitialized
protected String
domain
protected ObjectName
oname
protected MBeanServer
mserver
ObjectName
controller
Constructors Summary
public Connector()



    // ------------------------------------------------------------ Constructor


     
          
        this(null);
    
public Connector(String protocol)

        setProtocol(protocol);
        // Instantiate protocol handler
        try {
            Class clazz = Class.forName(protocolHandlerClassName);
            this.protocolHandler = (ProtocolHandler) clazz.newInstance();
        } catch (Exception e) {
            log.error
                (sm.getString
                 ("coyoteConnector.protocolHandlerInstantiationFailed", e));
        }
    
Methods Summary
public voidaddLifecycleListener(org.apache.catalina.LifecycleListener listener)
Add a lifecycle event listener to this component.

param
listener The listener to add


        lifecycle.addLifecycleListener(listener);

    
protected javax.management.ObjectNamecreateObjectName(java.lang.String domain, java.lang.String type)

        String encodedAddr = null;
        if (getProperty("address") != null) {
            encodedAddr = URLEncoder.encode(getProperty("address").toString());
        }
        String addSuffix = (getProperty("address") == null) ? "" : ",address="
                + encodedAddr;
        ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port="
                + getPort() + addSuffix);
        return _oname;
    
public RequestcreateRequest()
Create (or allocate) and return a Request object suitable for specifying the contents of a Request to the responsible Container.


        Request request = new Request();
        request.setConnector(this);
        return (request);

    
public ResponsecreateResponse()
Create (or allocate) and return a Response object suitable for receiving the contents of a Response from the responsible Container.


        Response response = new Response();
        response.setConnector(this);
        return (response);

    
public voiddestroy()

        if( oname!=null && controller==oname ) {
            if(log.isDebugEnabled())
                 log.debug("Unregister itself " + oname );
            Registry.getRegistry(null, null).unregisterComponent(oname);
        }
        if( getService() == null)
            return;
        getService().removeConnector(this);
    
protected voidfindContainer()

        try {
            // Register to the service
            ObjectName parentName=new ObjectName( domain + ":" +
                    "type=Service");

            if(log.isDebugEnabled())
                log.debug("Adding to " + parentName );
            if( mserver.isRegistered(parentName )) {
                mserver.invoke(parentName, "addConnector", new Object[] { this },
                        new String[] {"org.apache.catalina.connector.Connector"});
                // As a side effect we'll get the container field set
                // Also initialize will be called
                //return;
            }
            // XXX Go directly to the Engine
            // initialize(); - is called by addConnector
            ObjectName engName=new ObjectName( domain + ":" + "type=Engine");
            if( mserver.isRegistered(engName )) {
                Object obj=mserver.getAttribute(engName, "managedResource");
                if(log.isDebugEnabled())
                      log.debug("Found engine " + obj + " " + obj.getClass());
                container=(Container)obj;

                // Internal initialize - we now have the Engine
                initialize();

                if(log.isDebugEnabled())
                    log.debug("Initialized");
                // As a side effect we'll get the container field set
                // Also initialize will be called
                return;
            }
        } catch( Exception ex ) {
            log.error( "Error finding container " + ex);
        }
    
public org.apache.catalina.LifecycleListener[]findLifecycleListeners()
Get the lifecycle listeners associated with this lifecycle. If this Lifecycle has no listeners registered, a zero-length array is returned.


        return lifecycle.findLifecycleListeners();

    
public booleangetAllowTrace()
True if the TRACE method is allowed. Default value is "false".


        return (this.allowTrace);

    
public java.lang.ObjectgetAttribute(java.lang.String name)
Return a configured property.

        return getProperty(name);
    
public intgetBufferSize()
Return the input buffer size for this Connector.

deprecated

        return 2048;
    
public org.apache.catalina.ContainergetContainer()
Return the Container used for processing requests received by this Connector.

        if( container==null ) {
            // Lazy - maybe it was added later
            findContainer();
        }
        return (container);

    
public javax.management.ObjectNamegetController()

        return controller;
    
public java.lang.StringgetDomain()

        return domain;
    
public booleangetEmptySessionPath()
Return the "empty session path" flag.


        return (this.emptySessionPath);

    
public booleangetEnableLookups()
Return the "enable DNS lookups" flag.


        return (this.enableLookups);

    
public java.lang.StringgetInfo()
Return descriptive information about this Connector implementation.


        return (info);

    
public org.apache.tomcat.util.http.mapper.MappergetMapper()
Return the mapper.


         return (mapper);

     
public intgetMaxPostSize()
Return the maximum size of a POST which will be automatically parsed by the container.


        return (maxPostSize);

    
public intgetMaxSavePostSize()
Return the maximum size of a POST which will be saved by the container during authentication.


        return (maxSavePostSize);

    
public javax.management.ObjectNamegetObjectName()

        return oname;
    
public intgetPort()
Return the port number on which we listen for requests.


        return (this.port);

    
public java.lang.ObjectgetProperty(java.lang.String name)
Return a configured property.

      
         replacements.put("acceptCount", "backlog");
         replacements.put("connectionLinger", "soLinger");
         replacements.put("connectionTimeout", "soTimeout");
         replacements.put("connectionUploadTimeout", "timeout");
         replacements.put("clientAuth", "clientauth");
         replacements.put("keystoreFile", "keystore");
         replacements.put("randomFile", "randomfile");
         replacements.put("rootFile", "rootfile");
         replacements.put("keystorePass", "keypass");
         replacements.put("keystoreType", "keytype");
         replacements.put("sslProtocol", "protocol");
         replacements.put("sslProtocols", "protocols");
     
        String repl = name;
        if (replacements.get(name) != null) {
            repl = (String) replacements.get(name);
        }
        return IntrospectionUtils.getProperty(protocolHandler, repl);
    
public java.lang.StringgetProtocol()
Return the Coyote protocol handler in use.


        if ("org.apache.coyote.http11.Http11Protocol".equals
            (getProtocolHandlerClassName())
            || "org.apache.coyote.http11.Http11AprProtocol".equals
            (getProtocolHandlerClassName())) {
            return "HTTP/1.1";
        } else if ("org.apache.jk.server.JkCoyoteHandler".equals
                   (getProtocolHandlerClassName())
                   || "org.apache.coyote.ajp.AjpAprProtocol".equals
                   (getProtocolHandlerClassName())) {
            return "AJP/1.3";
        }
        return getProtocolHandlerClassName();

    
public org.apache.coyote.ProtocolHandlergetProtocolHandler()
Return the protocol handler associated with the connector.


        return (this.protocolHandler);

    
public java.lang.StringgetProtocolHandlerClassName()
Return the class name of the Coyote protocol handler in use.


        return (this.protocolHandlerClassName);

    
public java.lang.StringgetProxyName()
Return the proxy server name for this Connector.


        return (this.proxyName);

    
public intgetProxyPort()
Return the proxy server port for this Connector.


        return (this.proxyPort);

    
public intgetRedirectPort()
Return the port number to which a request should be redirected if it comes in on a non-SSL port and is subject to a security constraint with a transport guarantee that requires SSL.


        return (this.redirectPort);

    
public java.lang.StringgetScheme()
Return the scheme that will be assigned to requests received through this connector. Default value is "http".


        return (this.scheme);

    
public booleangetSecure()
Return the secure connection flag that will be assigned to requests received through this connector. Default value is "false".


        return (this.secure);

    
public org.apache.catalina.ServicegetService()
Return the Service with which we are associated (if any).


        return (this.service);

    
public java.lang.StringgetURIEncoding()
Return the character encoding to be used for the URI.


         return (this.URIEncoding);

     
public booleangetUseBodyEncodingForURI()
Return the true if the entity body encoding should be used for the URI.


         return (this.useBodyEncodingForURI);

     
public booleangetUseIPVHosts()
Test if IP-based virtual hosting is enabled.

        return useIPVHosts;
    
public booleangetXpoweredBy()
Indicates whether the generation of an X-Powered-By response header for servlet-generated responses is enabled or disabled for this Connector.

return
true if generation of X-Powered-By response header is enabled, false otherwise

        return xpoweredBy;
    
public voidinit()


        if( this.getService() != null ) {
            if(log.isDebugEnabled())
                 log.debug( "Already configured" );
            return;
        }
        if( container==null ) {
            findContainer();
        }
    
public voidinitialize()
Initialize this connector (create ServerSocket here!)

        if (initialized) {
            if(log.isInfoEnabled())
                log.info(sm.getString("coyoteConnector.alreadyInitialized"));
           return;
        }

        this.initialized = true;

        if( oname == null && (container instanceof StandardEngine)) {
            try {
                // we are loaded directly, via API - and no name was given to us
                StandardEngine cb=(StandardEngine)container;
                oname = createObjectName(cb.getName(), "Connector");
                Registry.getRegistry(null, null)
                    .registerComponent(this, oname, null);
                controller=oname;
            } catch (Exception e) {
                log.error( "Error registering connector ", e);
            }
            if(log.isDebugEnabled())
                log.debug("Creating name for connector " + oname);
        }

        // Initializa adapter
        adapter = new CoyoteAdapter(this);
        protocolHandler.setAdapter(adapter);

        IntrospectionUtils.setProperty(protocolHandler, "jkHome",
                                       System.getProperty("catalina.base"));

        try {
            protocolHandler.init();
        } catch (Exception e) {
            throw new LifecycleException
                (sm.getString
                 ("coyoteConnector.protocolHandlerInitializationFailed", e));
        }
    
private static synchronized voidinitializeAPR()


    // APR init support
        
    
        if (aprInitialized) {
            return;
        }
        int major = 0;
        int minor = 0;
        int patch = 0;
        try {
            String methodName = "initialize";
            Class paramTypes[] = new Class[1];
            paramTypes[0] = String.class;
            Object paramValues[] = new Object[1];
            paramValues[0] = null;
            Class clazz = Class.forName("org.apache.tomcat.jni.Library");
            Method method = clazz.getMethod(methodName, paramTypes);
            method.invoke(null, paramValues);
            major = clazz.getField("TCN_MAJOR_VERSION").getInt(null);
            minor = clazz.getField("TCN_MINOR_VERSION").getInt(null);
            patch = clazz.getField("TCN_PATCH_VERSION").getInt(null);
        } catch (Throwable t) {
            return;
        }
        if ((major != TCN_REQUIRED_MAJOR) ||
            (minor != TCN_REQUIRED_MINOR) ||
            (patch <  TCN_REQUIRED_PATCH)) {
            try {
                // Terminate the APR in case the version
                // is below required.
                String methodName = "terminate";
                Method method = Class.forName("org.apache.tomcat.jni.Library")
                                    .getMethod(methodName, (Class [])null);
                method.invoke(null, (Object []) null);
            } catch (Throwable t) {
                // Ignore
            }
            return;
        }
        aprInitialized = true;
    
public booleanisAvailable()
Is this connector available for processing requests?


        return (started);

    
public voidpause()
Pause the connector.

        try {
            protocolHandler.pause();
        } catch (Exception e) {
            log.error(sm.getString
                      ("coyoteConnector.protocolHandlerPauseFailed"), e);
        }
    
public voidpostDeregister()

        try {
            if( started ) {
                stop();
            }
        } catch( Throwable t ) {
            log.error( "Unregistering - can't stop", t);
        }
    
public voidpostRegister(java.lang.Boolean registrationDone)

    
public voidpreDeregister()

    
public javax.management.ObjectNamepreRegister(javax.management.MBeanServer server, javax.management.ObjectName name)

        oname=name;
        mserver=server;
        domain=name.getDomain();
        return name;
    
public voidremoveLifecycleListener(org.apache.catalina.LifecycleListener listener)
Remove a lifecycle event listener from this component.

param
listener The listener to add


        lifecycle.removeLifecycleListener(listener);

    
public voidremoveProperty(java.lang.String name)
remove a configured property.

        // FIXME !
        //protocolHandler.removeAttribute(name);
    
public voidresume()
Pause the connector.

        try {
            protocolHandler.resume();
        } catch (Exception e) {
            log.error(sm.getString
                      ("coyoteConnector.protocolHandlerResumeFailed"), e);
        }
    
public voidsetAllowTrace(boolean allowTrace)
Set the allowTrace flag, to disable or enable the TRACE HTTP method.

param
allowTrace The new allowTrace flag


        this.allowTrace = allowTrace;
        setProperty("allowTrace", String.valueOf(allowTrace));

    
public voidsetAttribute(java.lang.String name, java.lang.Object value)
Set a configured property.

        setProperty(name, String.valueOf(value));
    
public voidsetBufferSize(int bufferSize)
Set the input buffer size for this Connector.

param
bufferSize The new input buffer size.
deprecated

    
public voidsetContainer(org.apache.catalina.Container container)
Set the Container used for processing requests received by this Connector.

param
container The new Container to use


        this.container = container;

    
public voidsetController(javax.management.ObjectName controller)

        this.controller = controller;
    
public voidsetEmptySessionPath(boolean emptySessionPath)
Set the "empty session path" flag.

param
emptySessionPath The new "empty session path" flag value


        this.emptySessionPath = emptySessionPath;
        setProperty("emptySessionPath", String.valueOf(emptySessionPath));

    
public voidsetEnableLookups(boolean enableLookups)
Set the "enable DNS lookups" flag.

param
enableLookups The new "enable DNS lookups" flag value


        this.enableLookups = enableLookups;
        setProperty("enableLookups", String.valueOf(enableLookups));

    
public voidsetMaxPostSize(int maxPostSize)
Set the maximum size of a POST which will be automatically parsed by the container.

param
maxPostSize The new maximum size in bytes of a POST which will be automatically parsed by the container


        this.maxPostSize = maxPostSize;
    
public voidsetMaxSavePostSize(int maxSavePostSize)
Set the maximum size of a POST which will be saved by the container during authentication.

param
maxSavePostSize The new maximum size in bytes of a POST which will be saved by the container during authentication.


        this.maxSavePostSize = maxSavePostSize;
        setProperty("maxSavePostSize", String.valueOf(maxSavePostSize));
    
public voidsetPort(int port)
Set the port number on which we listen for requests.

param
port The new port number


        this.port = port;
        setProperty("port", String.valueOf(port));

    
public voidsetProperty(java.lang.String name, java.lang.String value)
Set a configured property.

        String repl = name;
        if (replacements.get(name) != null) {
            repl = (String) replacements.get(name);
        }
        IntrospectionUtils.setProperty(protocolHandler, repl, value);
    
public voidsetProtocol(java.lang.String protocol)
Set the Coyote protocol which will be used by the connector.

param
protocol The Coyote protocol name


        // Test APR support
        initializeAPR();

        if (aprInitialized) {
            if ("HTTP/1.1".equals(protocol)) {
                setProtocolHandlerClassName
                    ("org.apache.coyote.http11.Http11AprProtocol");
            } else if ("AJP/1.3".equals(protocol)) {
                setProtocolHandlerClassName
                    ("org.apache.coyote.ajp.AjpAprProtocol");
            } else if (protocol != null) {
                setProtocolHandlerClassName(protocol);
            } else {
                setProtocolHandlerClassName
                    ("org.apache.coyote.http11.Http11AprProtocol");
            }
        } else {
            if ("HTTP/1.1".equals(protocol)) {
                setProtocolHandlerClassName
                    ("org.apache.coyote.http11.Http11Protocol");
            } else if ("AJP/1.3".equals(protocol)) {
                setProtocolHandlerClassName
                    ("org.apache.jk.server.JkCoyoteHandler");
            } else if (protocol != null) {
                setProtocolHandlerClassName(protocol);
            }
        }

    
public voidsetProtocolHandlerClassName(java.lang.String protocolHandlerClassName)
Set the class name of the Coyote protocol handler which will be used by the connector.

param
protocolHandlerClassName The new class name


        this.protocolHandlerClassName = protocolHandlerClassName;

    
public voidsetProxyName(java.lang.String proxyName)
Set the proxy server name for this Connector.

param
proxyName The new proxy server name


        if(proxyName != null && proxyName.length() > 0) {
            this.proxyName = proxyName;
            setProperty("proxyName", proxyName);
        } else {
            this.proxyName = null;
            removeProperty("proxyName");
        }

    
public voidsetProxyPort(int proxyPort)
Set the proxy server port for this Connector.

param
proxyPort The new proxy server port


        this.proxyPort = proxyPort;
        setProperty("proxyPort", String.valueOf(proxyPort));

    
public voidsetRedirectPort(int redirectPort)
Set the redirect port number.

param
redirectPort The redirect port number (non-SSL to SSL)


        this.redirectPort = redirectPort;
        setProperty("redirectPort", String.valueOf(redirectPort));

    
public voidsetScheme(java.lang.String scheme)
Set the scheme that will be assigned to requests received through this connector.

param
scheme The new scheme


        this.scheme = scheme;

    
public voidsetSecure(boolean secure)
Set the secure connection flag that will be assigned to requests received through this connector.

param
secure The new secure connection flag


        this.secure = secure;
        setProperty("secure", Boolean.toString(secure));
    
public voidsetService(org.apache.catalina.Service service)
Set the Service with which we are associated (if any).

param
service The service that owns this Engine


        this.service = service;
        // FIXME: setProperty("service", service);

    
public voidsetURIEncoding(java.lang.String URIEncoding)
Set the URI encoding to be used for the URI.

param
URIEncoding The new URI character encoding.


         this.URIEncoding = URIEncoding;
         setProperty("uRIEncoding", URIEncoding);

     
public voidsetUseBodyEncodingForURI(boolean useBodyEncodingForURI)
Set if the entity body encoding should be used for the URI.

param
useBodyEncodingForURI The new value for the flag.


         this.useBodyEncodingForURI = useBodyEncodingForURI;
         setProperty
             ("useBodyEncodingForURI", String.valueOf(useBodyEncodingForURI));

     
public voidsetUseIPVHosts(boolean useIPVHosts)
Enable the use of IP-based virtual hosting.

param
useIPVHosts true if Hosts are identified by IP, false/code> if Hosts are identified by name.

        this.useIPVHosts = useIPVHosts;
        setProperty("useIPVHosts", String.valueOf(useIPVHosts));
    
public voidsetXpoweredBy(boolean xpoweredBy)
Enables or disables the generation of an X-Powered-By header (with value Servlet/2.4) for all servlet-generated responses returned by this Connector.

param
xpoweredBy true if generation of X-Powered-By response header is to be enabled, false otherwise

        this.xpoweredBy = xpoweredBy;
        setProperty("xpoweredBy", String.valueOf(xpoweredBy));
    
public voidstart()
Begin processing requests via this Connector.

exception
LifecycleException if a fatal startup error occurs

        if( !initialized )
            initialize();

        // Validate and update our current state
        if (started ) {
            if(log.isInfoEnabled())
                log.info(sm.getString("coyoteConnector.alreadyStarted"));
            return;
        }
        lifecycle.fireLifecycleEvent(START_EVENT, null);
        started = true;

        // We can't register earlier - the JMX registration of this happens
        // in Server.start callback
        if ( this.oname != null ) {
            // We are registred - register the adapter as well.
            try {
                Registry.getRegistry(null, null).registerComponent
                    (protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
            } catch (Exception ex) {
                log.error(sm.getString
                          ("coyoteConnector.protocolRegistrationFailed"), ex);
            }
        } else {
            if(log.isInfoEnabled())
                log.info(sm.getString
                     ("coyoteConnector.cannotRegisterProtocol"));
        }

        try {
            protocolHandler.start();
        } catch (Exception e) {
            String errPrefix = "";
            if(this.service != null) {
                errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
            }

            throw new LifecycleException
                (errPrefix + " " + sm.getString
                 ("coyoteConnector.protocolHandlerStartFailed", e));
        }

        if( this.domain != null ) {
            mapperListener.setDomain( domain );
            //mapperListener.setEngine( service.getContainer().getName() );
            mapperListener.init();
            try {
                ObjectName mapperOname = createObjectName(this.domain,"Mapper");
                if (log.isDebugEnabled())
                    log.debug(sm.getString(
                            "coyoteConnector.MapperRegistration", mapperOname));
                Registry.getRegistry(null, null).registerComponent
                    (mapper, mapperOname, "Mapper");
            } catch (Exception ex) {
                log.error(sm.getString
                        ("coyoteConnector.protocolRegistrationFailed"), ex);
            }
        }
    
public voidstop()
Terminate processing requests via this Connector.

exception
LifecycleException if a fatal shutdown error occurs


        // Validate and update our current state
        if (!started) {
            log.error(sm.getString("coyoteConnector.notStarted"));
            return;

        }
        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        started = false;

        try {
            mapperListener.destroy();
            Registry.getRegistry(null, null).unregisterComponent
                (createObjectName(this.domain,"Mapper"));
            Registry.getRegistry(null, null).unregisterComponent
                (createObjectName(this.domain,"ProtocolHandler"));
        } catch (MalformedObjectNameException e) {
            log.error( sm.getString
                    ("coyoteConnector.protocolUnregistrationFailed"), e);
        }
        try {
            protocolHandler.destroy();
        } catch (Exception e) {
            throw new LifecycleException
                (sm.getString
                 ("coyoteConnector.protocolHandlerDestroyFailed", e));
        }