tomcat-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cos...@apache.org
Subject cvs commit: jakarta-tomcat/src/share/org/apache/tomcat/startup EmbededTomcat.java
Date Tue, 21 Aug 2001 05:29:27 GMT
costin      01/08/20 22:29:27

  Modified:    src/share/org/apache/tomcat/startup EmbededTomcat.java
  Log:
  Ok, this is the big one !
  
  I did a lot of work on this area, now things should be much cleaner and simpler
  ( by my taste ).
  
  First, most of the settings from Main.java are now part of EmbededTomcat. We
  expect people to use EmbededTomcat to include tomcat in other apps, not
  Main - since we need to provide a reach interface and more control.
  
  Main.java is now reduced to the same role as "java -jar" ( and is equivalent
  with it - or should be ). It just create a simple class loader including all
  the classes in common, and then pass control to EmbededTomcat, which does
  all the real work.
  
  In other words, to embed tomcat you need to include all the common in
  a classpath, then use EmbeddedTomcat as a regular bean - set properties and
  call the methods you need.
  
  EmbededTomcat will set the container environment ( which must be separated
  in another class loader - security and isolation ).
  
  I also added a bit more documentation.
  
  An important change - there is no dependency between ET and container classes
  ( see 2 lines above ).
  
  EmbededTomcat now  works in both modes - if setEstart is used ( equivalent
  with java -jar tomcat.jar estart ), it'll use the hardcoded modules
  ( or an alternate set, depending on your code ). The default, or if
  "start" command is used on the command line, is to load tomcat using
  server.xml, as before.
  
  Revision  Changes    Path
  1.47      +586 -225  jakarta-tomcat/src/share/org/apache/tomcat/startup/EmbededTomcat.java
  
  Index: EmbededTomcat.java
  ===================================================================
  RCS file: /home/cvs/jakarta-tomcat/src/share/org/apache/tomcat/startup/EmbededTomcat.java,v
  retrieving revision 1.46
  retrieving revision 1.47
  diff -u -r1.46 -r1.47
  --- EmbededTomcat.java	2001/08/17 04:23:00	1.46
  +++ EmbededTomcat.java	2001/08/21 05:29:27	1.47
  @@ -5,35 +5,83 @@
   
   import org.apache.tomcat.core.*;
   import org.apache.tomcat.util.log.*;
  -import org.apache.tomcat.modules.server.*;
  +import org.apache.tomcat.util.compat.*;
  +import org.apache.tomcat.util.IntrospectionUtils;
   import java.security.*;
   import java.util.*;
   
  +/* EmbededTomcat is the bean you use to embed tomcat in your application.
  +   Main is a wrapper that will guess TOMCAT_HOME and dispatch to 
  +   tasks performing different actions, including EmbededTomcat.
  +
  +*/
  +
  +/* Required setup:
  +   -  EmbededTomcat is assumed to be loaded in the same class loader with
  +   lib/common, and without lib/container. It'll deal with setting a separate
  +   class loader for container and applications.
  +
  +   - home property must be set, or TOMCAT_HOME env.
  +
  +*/
  +
   /**
  + *
  + *  Use this class to embed tomcat in your application. If all you want is to
  + *  start/stop tomcat, with minimal customization, you can use Main.main()
    *
  - *  Wrapper around ContextManager. Use this class to embed tomcat in your
  - *  application if you want to use "API"-based configuration ( instead
  - *  or in addition to server.xml ).
  + *  This class is designed as a java bean, where you set different properties,
  + *  then call methods to perform actions. The main method is "execute", that
  + *  will start tomcat. Few other methods allow to perform different other tasks.
  + *
  + *  EmbededTomcat is usable as an "ant" task as well, using the TaskAdapter.
  + *  ( see sample - TODO XXX ).
  + * 
  + *  Adding tomcat to your application:
  + * 
  + *  - Create a java class that will act as adapter and start tomcat ( and
  + *    hold your customization code ). The class and all the files in
  + *    TOMCAT_HOME/lib/common must be available in the class loader.
  + *    lib/container and lib/apps should  _not_ be visible, EmbededTomcat
  + *    will handle that. All the application files you want visible from 
  + *    tomcat must be included as well.
  + *    ADVANCED1. Completely separated classloader
    *
  - *  The order is important:
  + *  - In your adapter, create an instance of EmbededTomcat.
    * 
  - *  1. set properties like workDir and debug
  - *  2. add all interceptors including your application-specific
  - *  3. add the endpoints 
  - *  4. add at least the root context ( you can add more if you want )
  - *  5. call start(). The web service will be operational.
  - *  6. You can add/remove contexts
  - *  7. stop().
  + *  - set properties you want to customize. 
    *  
  - *  You can add more contexts after start, but interceptors and  
  - *  endpoints must be set before the first context and root must be
  - *  set before start().
  + *  - add all interceptors including your application-specific. That includes
  + *   the connector modules ( shortcuts are provided for common sets of
  + *   modules and for common connector configuration ).
  + *
  + *  - add the root context ( required ) and any other contexts you want.
  + *    More context can be added at runtime. You can also use existing
  + *    configuration modules that automatically add/deploy Contexts. 
  + *    
  + *  -  call start(). Tomcat will initialize and start. The method returns
  + *     when everything is ready.
  + * 
  + *  -  You can add/remove contexts at runtime.
  + *
  + *  -  call stop(). Tomcat will clean up all resources and shutdown ( clean 
  + *     shutdown ). All common modules have been tested and shouldn't leave
  + *     any garbage, however it is possible that user code will leave threads
  + *     or other garbage ( i.e. not clean on destroy ). If tomcat is run in
  + *     a sandbox, this shouldn't be a problem ( as untrusted servlets can't
  + *     create threads ). It is your responsiblity to make sure all apps you trust
  + *     or custom modules support clean shutdown.
    *
  - *  All file paths _must_ be absolute. ( right now if the path is relative it
  - *  will be made absolute using tomcat.home as base. This behavior is very
  - *  "expensive" as code complexity and will be deprecated ).
  + *  - ADVANCED2. You can throw away the classloader, and use another one
  + *    if you start again. That would take care of all garbage and classes
  + *    except threads and associated objects ( there is no way to handle
  + *    dangling threads except killing them, assuming you can distinguish
  + *    them from your own threads ).
  + *
  + *  All file paths _should_ be absolute. If not, you should set "home" and
  + *  make sure you include the "PathSetter" module before anything else.
    * 
  - * @author costin@eng.sun.com
  + * @author Costin Manolache
    */
   public class EmbededTomcat { 
       // the "real" server
  @@ -43,22 +91,23 @@
       protected Object application;
   
       // null == not set up
  -    protected Vector requestInt=null;
       protected Vector connectors=new Vector();
   
  -    ClassLoader parentClassLoader;
  -    ClassLoader appsClassLoader;
  -    ClassLoader commonClassLoader;
  -    ClassLoader containerClassLoader;
  -    String home=".";
  -    String install=null;
  +    String home=null;
  +    String installDir=null;
       
  -    boolean sandbox=false;
  +    Hashtable attributes=new Hashtable();
       
       // configurable properties
  -    protected int debug=0;
  +    protected int dL=0;
  +
  +    boolean defaultConnectors=true;
  +    boolean autoDeploy=true;
       
  +    boolean serverXml=true;
  +    
       public EmbededTomcat() {
  +	//	setDebug( 10 );
       }
   
       // -------------------- 
  @@ -69,68 +118,79 @@
       
       // -------------------- Properties - set before start
   
  -    /** Set debugging - must be called before anything else
  +    /** Debug for EmbededTomcat. 
        */
       public void setDebug( int debug ) {
  -	this.debug=debug;
  +	this.dL=debug;
   	contextM.setDebug( debug );
  +	debug( "Debugging enabled ");
       }
   
  -    public void setParentClassLoader( ClassLoader cl ) {
  -	this.parentClassLoader=cl;
  -    }
  -
  -    public void setCommonClassLoader( ClassLoader cl ) {
  -	this.commonClassLoader=cl;
  -    }
  -
  -    public void setAppsClassLoader( ClassLoader cl ) {
  -	this.appsClassLoader=cl;
  -    }
  -
  -    public void setContainerClassLoader( ClassLoader cl ) {
  -	this.containerClassLoader=cl;
  -    }
  -    
  -
  -
       public void setHome( String s ) {
   	home=s;
  -	//System.getProperties().put(ContextManager.TOMCAT_HOME, s);
  -	contextM.setHome( s );
       }
   
       public void setInstall(String install) {
  -	this.install=install;
  -	//System.getProperties().put( ContextManager.TOMCAT_INSTALL, install);
  +	this.installDir=install;
   	contextM.setInstallDir( install );
  +	if( dL > 0 ) debug( "setInstall " + install);
  +    }
  +
  +    public void setConfig( String s ) {
  +	attributes.put("config", s);
       }
   
       /** Tomcat will run in a sandboxed environment, under SecurityManager
        */
  -    public void setSandbox( boolean b ) {
  -	sandbox=b;
  +    public void setSandbox(boolean b) {
  +	debug("Sandbox enabled");
  +	attributes.put("sandbox", "true");
       }
   
  -    // -------------------- Access tomcat state --------------------
  +    // First param
  +    public void setStart(boolean b) {
  +	// nothing, default mode
  +    }
   
  -    public boolean isInitialized() {
  -	return initialized;
  +    public void setEstart(boolean b) {
  +	debug( "Using default embedded config ");
  +	serverXml=false;
       }
   
  +    public void setRun(boolean b) {
  +	setStart(true);
  +    }
       
  -    // -------------------- Application Modules --------------------
  +    // -------------------- Generic properties --------------------
   
  -    /** This is an adapter object that provides callbacks into the
  -     *  application.
  -     */
  -    public void addApplicationAdapter( BaseInterceptor adapter )
  -	throws TomcatException
  -    {
  -	if(requestInt==null)  initDefaultInterceptors();
  -	addInterceptor(adapter);
  +    public void setProperty( String name, String v ) {
  +	if( name.equals("home")  )
  +	    setHome((String) v );
  +	if( name.equals("install")  )
  +	    setInstall( (String) v);
  +	if( name.equals("sandbox"))
  +	    setSandbox(true);
  +	attributes.put( name, v );
       }
   
  +    public void setAttribute( String name, Object v ) {
  +	if( name.equals("parentClassLoader")  )
  +	    setParentClassLoader((ClassLoader)v);
  +	if( name.equals("commonClassLoader")  )
  +	    setCommonClassLoader((ClassLoader)v);
  +	if( name.equals("args")  )
  +	    setArgs((String [])v);
  +	if( name.equals("commonClassPath")  )
  +	    setCommonClassPath((URL [])v);
  +	attributes.put( name, v );
  +    }
  +    
  +    // Ant compatibility
  +    public void addProperty(Property prop) {
  +    }
  +    
  +    // -------------------- Application Modules --------------------
  +
       /** Keep a reference to the application in which we are embeded
        */
       public void setApplication( Object app ) {
  @@ -142,61 +202,94 @@
       public Object getApplication() {
   	return application;
       }
  +
  +    // -------------------- Module configuration --------------------
   
  -    // -------------------- Helpers for http connectors --------------------
  +    Vector modules=new Vector();
  +
  +    public int addModule( BaseInterceptor ri )
  +	throws TomcatException
  +    {
  +	if( ri==null ) return -1;
  +	if( dL > 20 ) debug( "addModule " + ri.getClass().getName());
  +	if(ri.getClass().getName().indexOf("Xml") <0 )
  +	    ri.setDebug( dL );
  +	modules.addElement( ri );
  +	return modules.size()-1;
  +    }
       
  -    /** Add a HTTP listener.
  -     */
  -    public void addEndpoint( int port, InetAddress addr , String hostname)
  +    /** Add a custom module. It'll return the module id, that can be
  +	used to set properties
  +    */
  +    public int addModule( String className )
   	throws TomcatException
       {
  -	if(debug>0) log( "addConnector " + port + " " + addr +
  -			 " " + hostname );
  +	BaseInterceptor bi=createModule( className );
  +	if( bi==null )
  +	    throw new TomcatException("module not found " + className);
  +	return addModule( bi );
  +    }
   
  -	Http10Interceptor sc=new Http10Interceptor();
  -	sc.setPort( port ) ;
  -	if( addr != null ) sc.setAddress( addr );
  -	if( hostname != null ) sc.setHostName( hostname );
  -	
  -	contextM.addInterceptor(  sc );
  +    public int findModule( String className, int startPos )
  +    {
  +	for( int i=startPos; i<modules.size(); i++ ) {
  +	    Object o=modules.elementAt(i);
  +	    if( className.equals( o.getClass().getName() )) 
  +		return i;
  +	}
  +	return -1;
       }
   
  -    /** Add AJP12 listener.
  -     */
  -    public void addAjpEndpoint( int port, InetAddress addr , String hostname)
  +    public void setModuleProperty( int id, String name, String value )
   	throws TomcatException
       {
  -	if(debug>0) log( "addAjp12Connector " + port + " " + addr +
  -			 " " + hostname );
  -
  -	Ajp12Interceptor sc=new Ajp12Interceptor();
  -	sc.setPort( port ) ;
  -	if( addr != null ) sc.setAddress( addr );
  -	if( hostname != null ) sc.setHostName( hostname );
  -	
  -	contextM.addInterceptor(  sc );
  +	Object o=modules.elementAt( id );
  +	if( dL>0 ) debug( "setModuleProperty " + o.getClass().getName() +
  +			  " " + name + " " + value );
  +	IntrospectionUtils.setProperty( o, name, value );
       }
   
  -    /** Add a secure HTTP listener.
  +    // -------------------- Module helpers --------------------
  +
  +    /** Init tomcat using server.xml-style configuration
        */
  -    public void addSecureEndpoint( int port, InetAddress addr, String hostname,
  -				    String keyFile, String keyPass )
  +    public void addServerXmlModules() throws TomcatException {
  +	debug( "Using server.xml " + attributes.get( "config" ));
  +	addModule( "org.apache.tomcat.modules.config.PathSetter");
  +	int mid=addModule( "org.apache.tomcat.modules.config.ServerXmlReader");
  +
  +	if( null!=attributes.get( "config" ) )
  +	    setModuleProperty( mid, "config",
  +			       (String)attributes.get("config") );
  +    }
  +
  +    public void addDefaultModules()
   	throws TomcatException
       {
  -	if(debug>0) log( "addSecureConnector " + port + " " + addr + " " +
  -			 hostname );
  -	
  -	Http10Interceptor sc=new Http10Interceptor();
  -	sc.setPort( port ) ;
  -	if( addr != null ) sc.setAddress(  addr );
  -	if( hostname != null ) sc.setHostName( hostname );
  -	
  -	sc.setSocketFactory("org.apache.tomcat.util.net.SSLSocketFactory");
  -	sc.setSecure(true);
  +	if( serverXml ) {
  +	    addServerXmlModules();
  +	    return;
  +	}
  +	if( dL > 0) {
  +	    int mid=addModule( LOG_EVENTS_MODULE );
  +	    setModuleProperty(mid, "enabled", "true");
  +	}
  +	    
  +	for( int i=0; i<moduleSet1.length; i++ ) {
  +	    addModule( moduleSet1[i] );
  +	}
  +    }
   
  -	contextM.addInterceptor(  sc );
  +    public void addAutoDeploy()
  +	throws TomcatException
  +    {
  +	if( serverXml ) return;
  +	for( int i=0; i<moduleSetAD.length; i++ ) {
  +	    addModule( moduleSetAD[i] );
  +	}
       }
   
  +    
       // -------------------- Context add/remove --------------------
   
       protected boolean initialized=false;
  @@ -206,21 +299,23 @@
       public Context addContext(  String ctxPath, URL docRoot, String hosts[] )
   	throws TomcatException
       {
  -	if(debug>0) log( "add context \"" + hosts[0] + ":" + ctxPath + "\" " +
  -			 docRoot );
  -	if( ! initialized ) {
  -	    initContextManager();
  -	}
  +	if(dL>0)
  +	    debug( "add context \"" + hosts[0] + ":" + ctxPath + "\" "+
  +		   docRoot );
  +	// User added a context explicitely, disable the default.
  +	autoDeploy=false;
   	
  +	if( ! initialized )  initContextManager();
  +
   	// tomcat supports only file-based contexts
   	if( ! "file".equals( docRoot.getProtocol()) ) {
  -	    log( "addContext() invalid docRoot: " + docRoot );
  +	    debug( "addContext() invalid docRoot: " + docRoot );
   	    throw new RuntimeException("Invalid docRoot " + docRoot );
   	}
   
   	try {
   	    Context ctx=contextM.createContext();
  -	    ctx.setDebug( debug );
  +	    ctx.setDebug( dL );
   	    ctx.setContextManager( contextM );
   	    ctx.setPath( ctxPath );
   	    ctx.setDocBase( docRoot.getFile());
  @@ -234,7 +329,7 @@
   	    contextM.addContext( ctx );
   	    return ctx;
   	} catch( Exception ex ) {
  -	    log("exception adding context " + ctxPath + "/" + docRoot, ex);
  +	    debug("exception adding context " + ctxPath + "/" + docRoot, ex);
   	}
   	return null;
       }
  @@ -267,8 +362,65 @@
   	return null;
       }
   
  +    // -------------------- Startup/shutdown methods --------------------
  +    
  +    public void initContextManager()
  +	throws TomcatException 
  +    {
  +	if( initialized ) return;
  +	if( home==null )
  +	    home = System.getProperty("tomcat.home");
  +	if( home==null ) {
  +	    IntrospectionUtils.guessInstall("tomcat.install",
  +					    "tomcat.home","tomcat.jar");
  +	    home = System.getProperty("tomcat.home");
  +	    if( dL > 0 ) debug( "Guessed home " + home );
  +	}
  +
  +	contextM.setHome( home );
  +	if( installDir==null ) installDir=home;
  +
  +	try {
  +	    setTomcatProperties();
  +
  +	    initClassLoaders();
  +
  +	    jdk11Compat.setContextClassLoader( containerCL );
  +
  +	    // 
  +	    if(modules.size()==0) 
  +		addDefaultModules();
  +
  +	    if( !serverXml ) {
  +		if( attributes.get("sandbox") != null )
  +		    addModule( POLICY_MODULE );
  +	    
  +		if( autoDeploy )
  +		    addAutoDeploy();
  +	    
  +		if( defaultConnectors )
  +		    addDefaultConnectors();
  +	    }
  +	    beforeAddInterceptors();
  +	    
  +	    for( int i=0; i< modules.size() ; i++ ) {
  +		contextM.addInterceptor( (BaseInterceptor)
  +					 modules.elementAt( i ) );
  +	    }
  +	    contextM.init();
  +	} catch( Exception ex ) {
  +	    debug("exception initializing ContextManager", ex);
  +	    throw new TomcatException( "EmbededTomcat.initContextManager", ex );
  +	}
  +	if(dL>0) debug( "ContextManager initialized" );
  +	initialized=true;
  +    }
  +
       public void start() throws TomcatException {
  +	long time3=System.currentTimeMillis();
   	contextM.start();
  +	long time4=System.currentTimeMillis();
  +	debug("Startup time " + ( time4-time3 ));
       }
   
       /** Stop contextM - will not exit the VM.
  @@ -276,50 +428,72 @@
       public void stop() throws TomcatException {
   	contextM.stop();
       }
  +
  +    // -------------------- Helpers and shortcuts --------------------
  +    
  +    /** Add a HTTP listener.
  +     */
  +    public int addEndpoint( int port, InetAddress addr , String hostname)
  +	throws TomcatException
  +    {
  +	if(modules.size()==0)  addDefaultModules();
  +	defaultConnectors=false;
  +	if(dL>0) debug( "addConnector " + port + " " + addr +
  +			 " " + hostname );
  +
  +	int mid=addModule("org.apache.tomcat.modules.server.Http10Interceptor");
   
  -    // -------------------- Private methods
  -    public void addInterceptor( BaseInterceptor ri ) {
  -	if( requestInt == null ) requestInt=new Vector();
  -	requestInt.addElement( ri );
  -	ri.setDebug( debug );
  +	setModuleProperty( mid, "port", Integer.toString(port) );
  +	if( addr != null )
  +	    setModuleProperty( mid, "address", addr.toString());
  +	if( hostname != null )
  +	    setModuleProperty( mid, "hostName",  hostname );
  +	return mid;
       }
   
  -    protected void initContextManager()
  -	throws TomcatException 
  +    /** Add AJP12 listener.
  +     */
  +    public int addAjpEndpoint( int port, InetAddress addr , String hostname)
  +	throws TomcatException
       {
  -	if( initialized ) return;
  -	if ( sandbox )
  -	    contextM.setProperty( "sandbox", "true");
  -	
  -	ClassLoader cl=parentClassLoader;
  -	
  -	if (cl==null) cl=this.getClass().getClassLoader();
  -	contextM.setParentLoader(cl);
  -	contextM.setCommonLoader(commonClassLoader);
  -	contextM.setContainerLoader(containerClassLoader);
  -	contextM.setAppsLoader(appsClassLoader);
  -	
  -	if(requestInt==null)  initDefaultInterceptors();
  -	
  -	for( int i=0; i< requestInt.size() ; i++ ) {
  -	    contextM.addInterceptor( (BaseInterceptor)
  -				     requestInt.elementAt( i ) );
  -	}
  +	if(modules.size()==0)  addDefaultModules();
  +	defaultConnectors=false;
  +	if(dL>0) debug( "addAjp12Connector " + port + " " + addr +
  +			 " " + hostname );
   
  -	try {
  -	    contextM.init();
  -	} catch( Exception ex ) {
  -	    log("exception initializing ContextManager", ex);
  -	}
  -	if(debug>0) log( "ContextManager initialized" );
  -	initialized=true;
  +	int mid=addModule("org.apache.tomcat.modules.server.Ajp12Interceptor");
  +
  +	setModuleProperty( mid, "port", Integer.toString( port )) ;
  +	if( addr != null )
  +	    setModuleProperty( mid, "address", addr.toString());
  +	if( hostname != null )
  +	    setModuleProperty( mid, "hostName",  hostname );
  +	return mid;
       }
   
  +    /** Add a secure HTTP listener.
  +     */
  +    public int addSecureEndpoint( int port, InetAddress addr, String hostname,
  +				    String keyFile, String keyPass )
  +	throws TomcatException
  +    {
  +	if(modules.size()==0)  addDefaultModules();
  +	int mid=addEndpoint( port, addr, hostname );
  +	
  +	setModuleProperty( mid, "socketFactory",
  +			   "org.apache.tomcat.util.net.SSLSocketFactory");
  +	setModuleProperty( mid, "secure", "true");
   
  -    protected void initDefaultInterceptors() {
  -	addModules( getDefaultModules() );
  +	return mid;
       }
   
  +    public void addDefaultConnectors()
  +	throws TomcatException
  +    {
  +	addEndpoint( 8080, null, null );
  +	addAjpEndpoint( 8007, null, null );
  +    }
  +    
       // -------------------- execute() --------------------
   
       /** Main and Ant action. It's expected to be overriden with completely
  @@ -327,20 +501,14 @@
   	directly the methods you need.
        */
       public void execute() throws Exception {
  -	processArgs(args);
  -	
  -	// Configure the server
  -	//	tryConfigSnapshot();
  -	// 	tryProperties();
  -	// 	tryServerXml();
  -	// 	tryDefault();
  -	
  -	// Set context manager properties
  -
  +	if( args!=null )
  +	    processArgs( args );
   	// Init 
   	if( ! initialized ) {
  +	    long time1=System.currentTimeMillis();
   	    initContextManager();
  -
  +	    long time2=System.currentTimeMillis();
  +	    debug("Init time "  + (time2-time1));
   	}
   	
   	// Start
  @@ -356,26 +524,16 @@
       }
   
       public boolean processArgs(String args[]) {
  -	for (int i = 0; i < args.length; i++) {
  -	    String arg = args[i];
  -
  -	    if (arg.equals("-sandbox")) {
  -		sandbox=true;
  -	    } else if (arg.equals("-h") || arg.equals("-home")) {
  -		i++;
  -		if (i < args.length)
  -		    setHome( args[i] );
  -		else
  -		    return false;
  -	    } else if (arg.equals("-i") || arg.equals("-install")) {
  -		i++;
  -		if (i < args.length)
  -		    setInstall( args[i] );
  -		else
  -		    return false;
  +	try {
  +	    if( dL> 0 ) {
  +		debug( "Processing args " );
  +		for( int i=0; i<args.length; i++ ) debug(args[i]);
   	    }
  +	    return IntrospectionUtils.processArgs( this, args );
  +	} catch( Exception ex ) {
  +	    ex.printStackTrace();
  +	    return false;
   	}
  -	return true;
       }
       
       public static void main(String args[] ) {
  @@ -384,78 +542,281 @@
   	    tomcat.setArgs( args );
               tomcat.execute();
   	} catch(Exception ex ) {
  -	    tomcat.log("main", ex);
  +	    tomcat.debug("main", ex);
   	    System.exit(1);
   	}
       }
   
  -    // -------------------- Default modules ( hardcoded )
  +    // -------------------- Utils --------------------
   
  -    /** Override this method to set a different set of modules
  +    /** Cleanup from a previous run
        */
  -    protected String[] getDefaultModules() {
  -	return moduleSet1;
  +    public void cleanupPrevious() {
  +	// remove ajp12.id
       }
   
  -    protected String moduleSet1[] = {
  -	"org.apache.tomcat.modules.config.PathSetter", 
  -	"org.apache.tomcat.facade.WebXmlReader",
  -	"org.apache.tomcat.modules.config.PolicyInterceptor",
  -	"org.apache.tomcat.modules.config.LoaderInterceptor11",
  -	"org.apache.tomcat.modules.generators.ErrorHandler",
  -	"org.apache.tomcat.modules.config.WorkDirSetup",
  -	"org.apache.tomcat.modules.session.SessionId",
  -	"org.apache.tomcat.modules.mappers.DecodeInterceptor",
  -	"org.apache.tomcat.modules.mappers.SimpleMapper1",
  -	"org.apache.tomcat.modules.generators.InvokerInterceptor",
  -	"org.apache.tomcat.facade.JspInterceptor",
  -	"org.apache.tomcat.modules.generators.StaticInterceptor",
  -	"org.apache.tomcat.modules.session.SimpleSessionStore",
  -	"org.apache.tomcat.facade.LoadOnStartupInterceptor",
  -	"org.apache.tomcat.facade.Servlet22Interceptor",
  -	"org.apache.tomcat.modules.aaa.AccessInterceptor",
  -	"org.apache.tomcat.modules.aaa.CredentialsInterceptor",
  -	"org.apache.tomcat.modules.generators.Jdk12Interceptor"
  -    };
  -    
  -    protected String moduleSet2[] = {
  -	"org.apache.tomcat.modules.config.PathSetter",
  -	"org.apache.tomcat.modules.config.ServerXmlReader",
  -    };
  +    private void setTomcatProperties() throws TomcatException {
  +	Enumeration attN=attributes.keys();
  +	while( attN.hasMoreElements() ) {
  +	    String k=(String)attN.nextElement();
  +	    Object o=attributes.get( k );
  +	    if( o instanceof String ) {
  +		IntrospectionUtils.setProperty( contextM, k, (String)o);
  +		if( dL> 0 ) debug("Set tomcat property " + k + " " + o );
  +	    } else
  +		contextM.setNote( k, o );
  +	}
  +    }
  +
  +    // -------------------- Class loader configuration --------------------
  +    // Set those if you embed tomcat in your app. If not, defaults
  +    // will be used as described in the comments.
  +    ClassLoader parentCL;
  +    ClassLoader appsCL;
  +    ClassLoader commonCL;
  +    ClassLoader containerCL;
  +    URL commonCP[];
  +    URL[] appsCP;
  +    URL[] containerCP;
  +	
  +
  +    /** Parent class loader is the parent of "common" loader. It
  +	can be used as a parent for the webapps, if you want them to
  +	have the minimal visibility of tomcat. If you do so,
  +	make sure you include at least servlet.jar.
  +    */
  +    public void setParentClassLoader( ClassLoader cl ) {
  +	this.parentCL=cl;
  +    }
  +
  +    /** Class loader containing lib/common ( or equivalent ). This will be the
  +     *  parent of both the server container and also parent of webapp loaders.
  +     *  Typically used to load EmbededTomcat ( defaults to
  +     *  this.getClassLoader()).
  +     *
  +     *   For backward compat, the caller can include  all elements of the 
  +     *   org.apache.tomcat.common.classpath property.
  +     */
  +    public void setCommonClassLoader( ClassLoader cl ) {
  +	this.commonCL=cl;
  +    }
  +
  +    /** Classpath used for common class loader ( probably not needed of
  +	URLClassLoader is used ). Used for javac.
  +    */
  +    public void setCommonClassPath( URL cp[] ) {
  +	commonCP=cp;
  +    }
  +
  +    /** Parent class loader for all web applications.
  +     *  Defaults to common + lib/apps + all elements of
  +     *  org.apache.tomcat.apps.classpath
  +     */
  +    public void setAppsClassLoader( ClassLoader cl ) {
  +	this.appsCL=cl;
  +    }
  +
  +    /** Class loader used to load tomcat internal classes, not
  +     *	visible to webapps.
  +     *  Defaults to common + ${TOMCAT_HOME}/lib/container/ + 
  +     *  ${TOMCAT_HOME}/classes + ${JAVA_HOME}/lib/tools.jar
  +     */
  +    public void setContainerClassLoader( ClassLoader cl ) {
  +	this.containerCL=cl;
  +    }
  +
  +    // -------------------- Class loader methods --------------------
  +
  +    static final Jdk11Compat jdk11Compat=Jdk11Compat.getJdkCompat();
  +    public static final String PROPERTY_APPS_LOADER =
  +	"org.apache.tomcat.apps.loader";
  +    public static final String PROPERTY_CONTAINER_LOADER =
  +	"org.apache.tomcat.container.loader";
  +	
  +
  +    /** Initialize class loaders with the defaults, if not set
  +     */
  +    public void initClassLoaders()
  +	throws IOException, MalformedURLException
  +    {
  +	if( dL > 0 ) debug( "Init class loaders ");
  +	if( parentCL==null ) {
  +	    if( dL > 0 ) debug( "Default parent loader: null");
  +	}
  +
  +	String prefix=installDir + File.separator + "lib" + File.separator;
  +	// At least this is assumed to be set.
  +	if( commonCL==null ) {
  +	    debug( "Default commonCL ");
  +	    commonCL=this.getClass().getClassLoader();
  +	}
  +
  +	if( containerCL == null ) {
  +	    if( dL > 0 )
  +		debug( "Dir : " + prefix+"container" + " " +
  +		       PROPERTY_CONTAINER_LOADER);
  +	    containerCP=
  +		IntrospectionUtils.getClassPath( prefix+"container",
  +						 null,
  +						 PROPERTY_CONTAINER_LOADER,
  +						 true );
  +	    containerCL=
  +		jdk11Compat.newClassLoaderInstance(containerCP , commonCL);
  +	    if( dL > 0 ) IntrospectionUtils.displayClassPath( "ContainerCP",
  +							      containerCP );
  +	}
  +	if( appsCL==null ) {
  +	    appsCP=
  +		IntrospectionUtils.getClassPath( prefix + "apps",
  +						 null,
  +						 PROPERTY_APPS_LOADER, false );
  +	    appsCL=jdk11Compat.newClassLoaderInstance(appsCP , commonCL);
  +	}
  +	// Tomcat initialization 
  +	// Set the env. variable with the classpath
  +	String cp=System.getProperty("tc_path_add");
  +	cp=IntrospectionUtils.classPathAdd(commonCP,cp);
  +	cp=IntrospectionUtils.classPathAdd(appsCP,cp);
  +	System.getProperties().put("tc_path_add",cp);
  +	
  +	contextM.setParentLoader(parentCL);
  +	contextM.setCommonLoader(commonCL);
  +	contextM.setContainerLoader(containerCL);
  +	contextM.setAppsLoader(appsCL);
  +    }
  +
       
       // -------------------- Utils --------------------
   
   
  -    public void log( String s ) {
  -	if( contextM==null )
  -	    System.out.println("EmbededTomcat: " + s );
  -	else
  -	    contextM.log( s );
  -    }
  -    public void log( String s, Throwable t ) {
  -	if( contextM==null ) {
  -	    System.out.println("EmbededTomcat: " + s );
  -	    t.printStackTrace();
  -	} else
  -	    contextM.log( s, t );
  +    public void debug( String s ) {
  +	debug( s, null );
       }
   
  -    protected void addModules(String set[] ) {
  -	for( int i=0; i<set.length; i++ ) {
  -	    addInterceptor( createModule( set[i] ));
  -	}
  +    public void debug( String s, Throwable t ) {
  +	System.out.println("EmbededTomcat: " + s );
  +	if( t!=null) t.printStackTrace();
       }
   
  -    private BaseInterceptor createModule( String classN ) {
  +    protected BaseInterceptor createModule( String classN ) {
   	try {
  -	    Class c=Class.forName( classN );
  +	    Class c=containerCL.loadClass( classN );
   	    return (BaseInterceptor)c.newInstance();
   	} catch( Exception ex ) {
  -	    ex.printStackTrace();
  +	    debug( "error creating module " + classN, ex);
   	    return null;
   	}
       }
   
  -    
  +    // -------------------- COMPAT --------------------
  +
  +    // Alternative property names, for backward compat.
  +    public void setSecurity(boolean b) {
  +	setSandbox(true);
  +    }
  +    public void setH(String s ) {
  +	setHome(s);
  +    }
  +    public void setI(String s ) {
  +	setInstall(s);
  +    }
  +    public void setF(String s ) {
  +	setConfig(s);
  +    }
  +    public void addInterceptor( BaseInterceptor ri )
  +	throws TomcatException
  +    {
  +	addModule( ri );
  +    }
  +
  +    // Other methods, no longer used 
  +    public boolean isInitialized() {
  +	return initialized;
  +    }
  +
  +    /** This is an adapter object that provides callbacks into the
  +     *  application.
  +     */
  +    public void addApplicationAdapter( BaseInterceptor adapter )
  +	throws TomcatException
  +    {
  +	if(modules.size()==0)
  +	    addDefaultModules();
  +	addModule(adapter);
  +    }
  +
  +    // -------------------- PROPERTIES --------------------
  +
  +    // Server.xml equivalent
  +    protected String moduleSet1[] = {
  +	"org.apache.tomcat.modules.config.HookSetter",
  +	"org.apache.tomcat.modules.config.PathSetter",
  +	"org.apache.tomcat.modules.config.LoaderInterceptor11",
  +	"org.apache.tomcat.modules.config.TrustedLoader",
  +	"org.apache.tomcat.modules.config.LogSetter", 
  +
  +	"org.apache.tomcat.modules.mappers.SimpleMapper1",
  +	"org.apache.tomcat.modules.session.SessionExpirer",
  +	"org.apache.tomcat.modules.session.SessionIdGenerator",
  +	"org.apache.tomcat.modules.session.SessionId",
  +
  +	"org.apache.tomcat.facade.WebXmlReader",
  +	"org.apache.tomcat.modules.generators.ErrorHandler",
  +	"org.apache.tomcat.modules.config.WorkDirSetup",
  +	"org.apache.tomcat.modules.generators.Jdk12Interceptor",
  +	"org.apache.tomcat.modules.generators.InvokerInterceptor",
  +	"org.apache.tomcat.facade.JspInterceptor",
  +	"org.apache.tomcat.modules.generators.StaticInterceptor",
  +
  +	"org.apache.tomcat.modules.mappers.ReloadInterceptor",
  +
  +	"org.apache.tomcat.modules.session.SimpleSessionStore",
  +	
  +	"org.apache.tomcat.modules.aaa.AccessInterceptor",
  +	"org.apache.tomcat.modules.aaa.CredentialsInterceptor",
  +	"org.apache.tomcat.modules.aaa.SimpleRealm",
  +	
  +	"org.apache.tomcat.facade.LoadOnStartupInterceptor",
  +	"org.apache.tomcat.facade.Servlet22Interceptor",
  +
  +	"org.apache.tomcat.modules.mappers.DecodeInterceptor"
  +    };
  +
  +    static String POLICY_MODULE=
  +	"org.apache.tomcat.modules.config.PolicyInterceptor";
  +    static String LOG_EVENTS_MODULE =
  +	"org.apache.tomcat.modules.loggers.LogEvents";
  +    // Autodeploy/autowebapp
  +    protected String moduleSetAD[] = { 
  +	"org.apache.tomcat.modules.config.ContextXmlReader",
  +	"org.apache.tomcat.modules.config.AutoDeploy",
  +	"org.apache.tomcat.modules.config.AutoWebApp"
  +   };
  +    
  +    // -------------------- Help --------------------
  +
  +    public static void printUsage() {
  +	PrintStream out=System.out;
  +	out.println("Usage: java org.apache.tomcat.startup.EmbeddedTomcat {options}");
  +	out.println("  Options are:");
  +        out.println("    -ajpid file                Use this file instead of conf/ajp12.id");
  +        out.println("                                 Use with -stop option");
  +	out.println("    -config file (or -f file)  Use this file instead of server.xml");
  +        out.println("    -enableAdmin               Updates admin webapp config to \"trusted\"");
  +	out.println("    -help (or help)            Show this usage report");
  +	out.println("    -home dir                  Use this directory as tomcat.home");
  +	out.println("    -install dir (or -i dir)   Use this directory as tomcat.install");
  +        out.println("    -sandbox                   Enable security manager (includes java.policy)");
  +	out.println("    -stop                      Shut down currently running Tomcat");
  +        out.println();
  +        out.println("In the absence of \"-enableAdmin\" and \"-stop\", Tomcat will be started");
  +    }
  +
  +    // -------------------- Override --------------------
  +
  +    protected void beforeAddInterceptors() throws TomcatException {
  +// 	int mid=findModule( "org.apache.tomcat.modules.config.LoaderInterceptor11" ,0);
  +// 	setModuleProperty( mid, "debug", "10" );
  +    }
   }
   
  
  
  

Mime
View raw message