FileDocCategorySizeDatePackage
JkMain.javaAPI DocApache Tomcat 6.0.1422932Fri Jul 20 04:20:32 BST 2007org.apache.jk.server

JkMain

public class JkMain extends Object implements MBeanRegistration
Main class used to startup and configure jk. It manages the conf/jk2.properties file and is the target of JMX proxy. It implements a policy of save-on-change - whenever a property is changed at runtime the jk2.properties file will be overriden. You can edit the config file when tomcat is stoped ( or if you don't use JMX or other admin tools ). The format of jk2.properties:
TYPE[.LOCALNAME].PROPERTY_NAME=VALUE
Set a property on the associated component. TYPE will be used to find the class name and instantiate the component. LOCALNAME allows multiple instances. In JMX mode, TYPE and LOCALNAME will form the JMX name ( eventually combined with a 'jk2' component )
NAME=VALUE
Define global properties to be used in ${} substitutions
class.COMPONENT_TYPE=JAVA_CLASS_NAME
Adds a new 'type' of component. We predefine all known types.
Instances are created the first time a component name is found. In addition, 'handler.list' property will override the list of 'default' components that are loaded automatically. Note that the properties file is just one (simplistic) way to configure jk. We hope to see configs based on registry, LDAP, db, etc. ( XML is not necesarily better )
author
Costin Manolache

Fields Summary
org.apache.jk.core.WorkerEnv
wEnv
String
propFile
Properties
props
Properties
modules
boolean
modified
boolean
started
boolean
saveProperties
private static String
DEFAULT_HTTPS
String
out
String
err
File
propsF
static String[]
defaultHandlers
long
initTime
long
startTime
static JkMain
jkMain
static Hashtable
replacements
private static String
CNAME
static org.apache.juli.logging.Log
log
protected String
domain
protected ObjectName
oname
protected MBeanServer
mserver
Constructors Summary
public JkMain()


     
    
        JkMain.jkMain=this;
        modules.put("channelSocket", "org.apache.jk.common.ChannelSocket");
        modules.put("channelNioSocket", "org.apache.jk.common.ChannelNioSocket");
        modules.put("channelUnix", "org.apache.jk.common.ChannelUn");
        modules.put("channelJni", "org.apache.jk.common.ChannelJni");
        modules.put("apr", "org.apache.jk.apr.AprImpl");
        modules.put("mx", "org.apache.jk.common.JkMX");
        modules.put("modeler", "org.apache.jk.common.JkModeler");
        modules.put("shm", "org.apache.jk.common.Shm");
        modules.put("request","org.apache.jk.common.HandlerRequest");
        modules.put("container","org.apache.jk.common.HandlerRequest");
        modules.put("modjk","org.apache.jk.common.ModJkMX");

    
Methods Summary
private booleancheckPropertiesFile()

        if(propFile == null) {
            return false;
        }
        propsF = new File(propFile);
        if(!propsF.isAbsolute()) {
            String home = getWorkerEnv().getJkHome();
            if( home == null ) {
                return false;
            }
            propsF = new File(home, propFile);
        }
        return propsF.exists();
    
public java.lang.StringgetChannelClassName()

        return (String)props.get( "handler.channel.className");
    
public java.lang.StringgetDomain()

        return domain;
    
public java.lang.StringgetErr()

        return this.err;
    
public longgetInitTime()
The time it took to initialize jk ( ms)

        return initTime;
    
public java.lang.StringgetJkHome()

        return getWorkerEnv().getJkHome();
    
public static org.apache.jk.server.JkMaingetJkMain()

        return jkMain;
    
public javax.management.ObjectNamegetObjectName()


       
        return oname;
    
public java.lang.StringgetOut()

        return this.out;
    
public java.lang.StringgetPropertiesFile()

        return propFile;
    
public java.lang.ObjectgetProperty(java.lang.String name)
Retrieve a property.

        String alias = (String)replacements.get(name);
        Object result = null;
        if(alias != null) {
            result = props.get(alias);
        }
        if(result == null) {
            result = props.get(name);
        }
        return result;
    
public longgetStartTime()
The time it took to start jk ( ms )

        return startTime;
    
public java.lang.StringgetWorkerClassName()

        return (String)props.get( "handler.container.className");
    
public org.apache.jk.core.WorkerEnvgetWorkerEnv()

        if( wEnv==null ) { 
            wEnv=new WorkerEnv();
        }
        return wEnv;
    
private voidguessHome()


       
        String home= wEnv.getJkHome();
        if( home != null )
            return;
        home=IntrospectionUtils.guessInstall( "jk2.home","jk2.home",
                                              "tomcat-jk2.jar", CNAME );
        if( home != null ) {
            log.info("Guessed home " + home );
            wEnv.setJkHome( home );
        }
    
public voidinit()

        long t1=System.currentTimeMillis();
        if(null != out) {
            PrintStream outS=new PrintStream(new FileOutputStream(out));
            System.setOut(outS);
        }
        if(null != err) {
            PrintStream errS=new PrintStream(new FileOutputStream(err));
            System.setErr(errS);
        }

        String home=getWorkerEnv().getJkHome();
        if( home==null ) {
            // XXX use IntrospectionUtil to find myself
            this.guessHome();
        }
        home=getWorkerEnv().getJkHome();
        if( home==null ) {
            log.info( "Can't find home, jk2.properties not loaded");
        }
        if(log.isDebugEnabled())
            log.debug("Starting Jk2, base dir= " + home  );
        loadPropertiesFile();

        String initHTTPS = (String)props.get("class.initHTTPS");
        if("true".equalsIgnoreCase(initHTTPS)) {
            initHTTPSUrls();
        }

        long t2=System.currentTimeMillis();
        initTime=t2-t1;
    
private voidinitHTTPSUrls()

       
        try {
            // 11657: if only ajp is used, https: redirects need to work ( at least for 1.3+)
            String value = System.getProperty("java.protocol.handler.pkgs");
            if (value == null) {
                value = DEFAULT_HTTPS;
            } else if (value.indexOf(DEFAULT_HTTPS) >= 0  ) {
                return; // already set
            } else {
                value += "|" + DEFAULT_HTTPS;
            }
            System.setProperty("java.protocol.handler.pkgs", value);
        } catch(Exception ex ) {
            log.info("Error adding SSL Protocol Handler",ex);
        }
    
private voidloadPropertiesFile()

        if(!checkPropertiesFile()) {
            return;
        }

        try {
            props.load( new FileInputStream(propsF) );
        } catch(IOException ex ){
            log.warn("Unable to load properties from "+propsF,ex);
        }
    
public static voidmain(java.lang.String[] args)


         
        try {
            if( args.length == 1 &&
                ( "-?".equals(args[0]) || "-h".equals( args[0])) ) {
                System.out.println("Usage: ");
                System.out.println("  JkMain [args]");
                System.out.println();
                System.out.println("  Each bean setter corresponds to an arg ( like -debug 10 )");
                System.out.println("  System properties:");
                System.out.println("    jk2.home    Base dir of jk2");
                return;
            }

            jkMain=new JkMain();

            IntrospectionUtils.processArgs( jkMain, args, new String[] {},
                                            null, new Hashtable());

            jkMain.init();
            jkMain.start();
        } catch( Exception ex ) {
            log.warn("Error running",ex);
        }
    
private org.apache.jk.core.JkHandlernewHandler(java.lang.String type, java.lang.String localName, java.lang.String fullName)

        JkHandler handler;
        String classN=modules.getProperty(type);
        if( classN == null ) {
            log.error("No class name for " + fullName + " " + type );
            return null;
        }
        try {
            Class channelclass = Class.forName(classN);
            handler=(JkHandler)channelclass.newInstance();
        } catch (Throwable ex) {
            handler=null;
            log.error( "Can't create " + fullName, ex );
            return null;
        }
        if( this.domain != null ) {
            try {
                ObjectName handlerOname = new ObjectName
                    (this.domain + ":" + "type=JkHandler,name=" + fullName);
                Registry.getRegistry(null, null).registerComponent(handler, handlerOname, classN);
            } catch (Exception e) {
                log.error( "Error registering " + fullName, e );
            }

        }
        wEnv.addHandler( fullName, handler );
        return handler;
    
public voidpause()

        for( int i=0; i<wEnv.getHandlerCount(); i++ ) {
            if( wEnv.getHandler(i) != null ) {
                wEnv.getHandler(i).pause();
            }
        }
    
public voidpostDeregister()

    
public voidpostRegister(java.lang.Boolean registrationDone)

    
public voidpreDeregister()

    
private voidpreProcessProperties()

     
        replacements.put("port","channelSocket.port");
        replacements.put("maxThreads", "channelSocket.maxThreads");   
        replacements.put("minSpareThreads", "channelSocket.minSpareThreads");   
        replacements.put("maxSpareThreads", "channelSocket.maxSpareThreads");   
        replacements.put("backlog", "channelSocket.backlog");   
        replacements.put("tcpNoDelay", "channelSocket.tcpNoDelay");
        replacements.put("soTimeout", "channelSocket.soTimeout");
        replacements.put("timeout", "channelSocket.timeout");
        replacements.put("address", "channelSocket.address");            
        replacements.put("bufferSize", "channelSocket.bufferSize");
        replacements.put("tomcatAuthentication", "request.tomcatAuthentication");
        replacements.put("packetSize", "channelSocket.packetSize");
    
        Enumeration keys=props.keys();
        Vector v=new Vector();
        
        while( keys.hasMoreElements() ) {
            String key=(String)keys.nextElement();          
            Object newName=replacements.get(key);
            if( newName !=null ) {
                v.addElement(key);
            }
        }
        keys=v.elements();
        while( keys.hasMoreElements() ) {
            String key=(String)keys.nextElement();
            Object propValue=props.getProperty( key );
            String replacement=(String)replacements.get(key);
            props.put(replacement, propValue);
            if( log.isDebugEnabled()) 
                log.debug("Substituting " + key + " " + replacement + " " + 
                    propValue);
        }
    
public javax.management.ObjectNamepreRegister(javax.management.MBeanServer server, javax.management.ObjectName name)

        oname=name;
        mserver=server;
        domain=name.getDomain();
        return name;
    
private voidprocessModules()

        Enumeration keys=props.keys();
        int plen=6;
        
        while( keys.hasMoreElements() ) {
            String k=(String)keys.nextElement();
            if( ! k.startsWith( "class." ) )
                continue;

            String name= k.substring( plen );
            String propValue=props.getProperty( k );

            if( log.isDebugEnabled()) log.debug("Register " + name + " " + propValue );
            modules.put( name, propValue );
        }
    
private voidprocessProperties()

        preProcessProperties();
        Enumeration keys=props.keys();

        while( keys.hasMoreElements() ) {
            String name=(String)keys.nextElement();
            String propValue=props.getProperty( name );

            processProperty( name, propValue );
        }
    
private voidprocessProperty(java.lang.String name, java.lang.String propValue)

        String type=name;
        String fullName=name;
        String localName="";
        String propName="";
        // ignore
        if( name.startsWith("key.")) return;

        int dot=name.indexOf(".");
        int lastDot=name.lastIndexOf(".");
        if( dot > 0 ) {
            type=name.substring(0, dot );
            if( dot != lastDot ) {
                localName=name.substring( dot + 1, lastDot );
                fullName=type + "." + localName;
            } else {
                fullName=type;
            }
            propName=name.substring( lastDot+1);
        } else {
            return;
        }
        
        if( log.isDebugEnabled() )
            log.debug( "Processing " + type + ":" + localName + ":" + fullName + " " + propName );
        if( "class".equals( type ) || "handler".equals( type ) ) {
            return;
        }
        
        JkHandler comp=getWorkerEnv().getHandler( fullName );
        if( comp==null ) {
            comp=newHandler( type, localName, fullName );
        }
        if( comp==null )
            return;
        
        if( log.isDebugEnabled() ) 
            log.debug("Setting " + propName + " on " + fullName + " " + comp);
        this.setBeanProperty( comp, propName, propValue );
    
public voidresume()

        for( int i=0; i<wEnv.getHandlerCount(); i++ ) {
            if( wEnv.getHandler(i) != null ) {
                wEnv.getHandler(i).resume();
            }
        }
    
public voidsaveProperties()

        if( !saveProperties) return;
        
        if(propsF == null) {
            log.warn("No properties file specified. Unable to save");
            return;
        }
        // Temp - to check if it works
        File outFile= new File(propsF.getParentFile(), propsF.getName()+".save");
        log.debug("Saving properties " + outFile );
        try {
            props.store( new FileOutputStream(outFile), "AUTOMATICALLY GENERATED" );
        } catch(IOException ex ){
            log.warn("Unable to save to "+outFile,ex);
        }
    
public voidsetBeanProperty(java.lang.Object target, java.lang.String name, java.lang.String val)

        if( val!=null )
            val=IntrospectionUtils.replaceProperties( val, props, null );
        if( log.isDebugEnabled())
            log.debug( "setProperty " + target + " " + name + "=" + val );
        
        IntrospectionUtils.setProperty( target, name, val );
    
public voidsetChannelClassName(java.lang.String name)
Set the channelClassName that will used to connect to httpd.

        props.put( "handler.channel.className",name);
    
public voidsetErr(java.lang.String s)

        this.err=s;
    
public voidsetJkHome(java.lang.String s)
Set the base dir of jk2. ( including WEB-INF if in a webapp ). We'll try to guess it from classpath if none is set ( for example on command line ), but if in a servlet environment you need to use Context.getRealPath or a system property or set it expliciltey.

        getWorkerEnv().setJkHome(s);
    
public voidsetOut(java.lang.String s)

        this.out=s;
    
public voidsetPropertiesFile(java.lang.String p)
Load a .properties file into and set the values into jk2 configuration.

        propFile=p;
        if( started ) {
            loadPropertiesFile();
        }
    
public voidsetProperty(java.lang.String n, java.lang.String v)
Set a name/value as a jk2 property

        if( "jkHome".equals( n ) ) {
            setJkHome( v );
        } 
        if( "propertiesFile".equals( n ) ) {
            setPropertiesFile( v );
        }
        props.put( n, v );
        if( started ) {
            processProperty( n, v );
            saveProperties();
        }
    
public voidsetPropertyString(java.lang.String handlerN, java.lang.String name, java.lang.String val)

        if( log.isDebugEnabled() )
            log.debug( "setProperty " + handlerN + " " + name + "=" + val );
        Object target=getWorkerEnv().getHandler( handlerN );

        setBeanProperty( target, name, val );
        if( started ) {
            saveProperties();
        }

    
public voidsetSaveProperties(boolean b)

        saveProperties=b;
    
public voidsetWorkerClassName(java.lang.String name)
Set the workerClassName that will handle the request. ( sort of 'pivot' in axis :-)

        props.put( "handler.container.className",name);
    
public voidsetWorkerEnv(org.apache.jk.core.WorkerEnv wEnv)

        this.wEnv = wEnv;
    
private java.lang.String[]split(java.lang.String s, java.lang.String delim)

         Vector v=new Vector();
        StringTokenizer st=new StringTokenizer(s, delim );
        while( st.hasMoreTokens() ) {
            v.addElement( st.nextToken());
        }
        String res[]=new String[ v.size() ];
        for( int i=0; i<res.length; i++ ) {
            res[i]=(String)v.elementAt(i);
        }
        return res;
    
public voidstart()

        long t1=System.currentTimeMillis();
        // We must have at least 3 handlers:
        // channel is the 'transport'
        // request is the request processor or 'global' chain
        // container is the 'provider'
        // Additional handlers may exist and be used internally
        // or be chained to create one of the standard handlers 

        String handlers[]=defaultHandlers;
        // backward compat
        String workers=props.getProperty( "handler.list", null );
        if( workers!=null ) {
            handlers= split( workers, ",");
        }

        // Load additional component declarations
        processModules();
        
        for( int i=0; i<handlers.length; i++ ) {
            String name= handlers[i];
            JkHandler w=getWorkerEnv().getHandler( name );
            if( w==null ) {
                newHandler( name, "", name );
            }
        }

        // Process properties - and add aditional handlers.
        processProperties();

        for( int i=0; i<wEnv.getHandlerCount(); i++ ) {
            if( wEnv.getHandler(i) != null ) {
                try {
                    wEnv.getHandler(i).init();
                } catch( IOException ex) {
                    if( "apr".equals(wEnv.getHandler(i).getName() )) {
                        log.info( "APR not loaded, disabling jni components: " + ex.toString());
                    } else {
                        log.error( "error initializing " + wEnv.getHandler(i).getName(), ex );
                    }
                }
            }
        }

        started=true;
        long t2=System.currentTimeMillis();
        startTime=t2-t1;

        this.saveProperties();
        log.info("Jk running ID=" + wEnv.getLocalId() + " time=" + initTime + "/" + startTime +
                 "  config=" + propFile);
    
public voidstop()

    /*
     static String defaultHandlers[]= { "apr",
                                       "shm",
                                       "request",
                                       "container",
                                       "channelSocket",
                                       "channelJni",
                                       "channelUnix"};
    */
    
       
    
        for( int i=0; i<wEnv.getHandlerCount(); i++ ) {
            if( wEnv.getHandler(i) != null ) {
                try {
                    wEnv.getHandler(i).destroy();
                } catch( IOException ex) {
                    log.error("Error stopping " + wEnv.getHandler(i).getName(), ex);
                }
            }
        }

        started=false;