FileDocCategorySizeDatePackage
PEMain.javaAPI DocGlassfish v2 API21953Mon May 14 20:16:48 BST 2007com.sun.enterprise.server

PEMain

public class PEMain extends Object
Start up class for PE/RI

Fields Summary
private static final long
START_TIME_MILLIS
public static volatile boolean
shutdownStarted
public static volatile boolean
shutdownThreadInvoked
private static volatile ApplicationServer
_server
private static final String
STOP
private static volatile PEMain
_instance
private static final String
SERVER_INSTANCE
private static com.sun.enterprise.util.i18n.StringManager
localStrings
local string manager
ServerContext
context
private static Logger
_logger
private ClassLoader
_loader
private boolean
isStarted
private static final String
instance_root
private static com.sun.enterprise.security.audit.AuditManager
auditManager
private static final boolean
USE_OLD_INSTANCE_STATUS_CHECK
Code surrounded by this causes hangs of up to 150 seconds at startup, though it usually takes only a few milliseconds to a few seconds. The code is obsolete and should not be needed.
Constructors Summary
public PEMain()
This object will be created during the Init phase of NSAPI

        // Set the context class loader
        _loader = getClass().getClassLoader();
        Thread.currentThread().setContextClassLoader(_loader);
	AdminEventListenerRegistry.addShutdownEventListener(new Shutdown());
        _instance = this;
    
Methods Summary
private ServerContextcreateServerContext(java.lang.String rootDir)
Create and initialize a server context object and also initialize its configuration context by reading the configuration file.


        // setup the config and the initial server context
        String[] args = new String[0];
        ServerContextImpl context = new ServerContextImpl();

        context.setCmdLineArgs(args);
	context.setInstallRoot(rootDir);
	context.setInstanceName(SERVER_INSTANCE);
        try{
            String serverXml = context.getServerConfigURL();
	    // Read server.xml and create a read-only configuration context
            ConfigContext cfgContext =
		ConfigFactory.createConfigContext(serverXml,
                                                  true,
                                                  false,
                                                  true);
	    context.setConfigContext(cfgContext);
	} catch (Exception ex){

	    if (!(ex instanceof ConfigException)){
                getLogger().log(Level.SEVERE,"j2eerunner.server_context_excp",ex);
        	if (_logger == null){
		    System.err.println("Exception in creating server context");
		    ex.printStackTrace();
		}
	    }
	    throw new ConfigException(ex.getMessage());
        }

        PluggableFeatureFactory ff = PluggableFeatureFactoryImpl.getFactory();

        context.setPluggableFeatureFactory(ff);
        return context;
    
public static ApplicationServergetApplicationServer()
return the ApplicationServer object

	return _server;
    
public static com.sun.enterprise.server.PEMaingetInstance()

        return _instance;
    
private static intgetInstanceStatus()
Get status of the instance.

        String stubFile = getStubFilePath();
        String seedFile = getSeedFilePath();
        RMIClient rmiClient = new RMIClient(true, stubFile, seedFile);
        return rmiClient.getInstanceStatusCode();
    
private static synchronized java.util.logging.LoggergetLogger()


         
        if (_logger == null) {
            _logger = LogDomains.getLogger(LogDomains.CORE_LOGGER);
        }
        return _logger;
    
public static java.lang.StringgetSeedFilePath()
method to obtain stub file


        return instance_root +
	  File.separatorChar +
	  "config" + File.separatorChar +
	  "admsn";
    
public static longgetStartTimeMillis()

         return START_TIME_MILLIS; 
public static java.lang.StringgetStubFilePath()
method to obtain stub file


        return instance_root +
	  File.separatorChar +
	  "config" +
	  File.separatorChar +
	  "admch";
    
public static booleanisInstanceAlreadyStarted()
method to check if server is already up or not

        return isInstanceStartingOrRunning();
    
private static booleanisInstanceRunning()
Is instance in running state.

        return (getInstanceStatus() == Status.kInstanceRunningCode);
    
private static booleanisInstanceStartingOrRunning()
Is instance in starting or running state.

        int statusCode = getInstanceStatus();
        return (statusCode == Status.kInstanceStartingCode
                || statusCode == Status.kInstanceRunningCode);
    
public booleanisStartingUp()

        return !isStarted;
    
public static voidmain(java.lang.String[] args)


         
        new AtStartup().submit( HowToRun.RUN_IN_SEPARATE_THREAD );
        new LoadMBeanServer().submit( HowToRun.RUN_IN_SEPARATE_THREAD );
        

	// parse args
	boolean verbose = false;
	boolean dbg = false;

        //set the system locale for this instance
        setSystemLocale();

        if(args[0].trim().equals(STOP)) {
            // check if instance is already running
            if (isInstanceRunning()) {
                    PEMain.shutdown();
                } else {
                    getLogger().log(Level.INFO, "instance.notRunning");
            }
            return;
        }

	try {

        // add temporary switch for new ProcessLauncher.
        // This will be removed once PE using the new invocation classes
        // Redirect stdout and stderr if location supplied in System.properties
        // NOTE: In verbose more the stderr only goes to the console, this is exactly the
        // way the apache commons-launcher functioned.
        String verboseMode=System.getProperty("com.sun.aas.verboseMode", "false");
        // Temporarily commented out. 
        // Hemanth: 
        // Will move the new SystemOutandErrorHandler() here after doing
        // some testing. The code is commented out mainly because the Log
        // Rotation will not work with the stream opened here.
        /*
        if(System.getProperty("com.sun.aas.processLauncher") != null
            && !verboseMode.equals("true")) {

            // If applicable, redirect output and error streams
            String defaultLogFile = System.getProperty("com.sun.aas.defaultLogFile");
            if (defaultLogFile != null) {
                PrintStream printStream = new PrintStream(new FileOutputStream(defaultLogFile, true), true);
                System.setOut(printStream);
                System.setErr(printStream);
            }
        }
        */


        // read in parameters off the stdin if they exist
        try {
            // check to see is Identity info is already set from native launcher
            if (IdentityManager.getUser() == null) {
                IdentityManager.populateFromInputStreamQuietly();
            }
        } catch (IOException e) {
            getLogger().log(Level.WARNING, "pemain.failureOnReadingSecurityIdentity", e);
        }
	if (getLogger().isLoggable(Level.FINE)) {
	    getLogger().log(Level.FINE, IdentityManager.getFormatedContents());
	}



       //Set system properties that correspond directly to asenv.conf/bat. This
       //keeps us from having to pass them all from -D on the command line.
       ASenvPropertyReader reader = new ASenvPropertyReader(
           System.getProperty(SystemPropertyConstants.CONFIG_ROOT_PROPERTY));
       reader.setSystemProperties();

        if ( USE_OLD_INSTANCE_STATUS_CHECK ) {
            // check if instance is already running
            if (isInstanceAlreadyStarted()) {
                getLogger().log(Level.SEVERE, "instance.alreadyRunning");
            System.exit(0);
            }
        }

	    getLogger().log(Level.FINE, "instance.start", SERVER_INSTANCE);

	    //_server = new ApplicationServer();
	    _server = new OnDemandServer();

            // print server starting message	 
	    String cstr = localStrings.getStringWithDefault( "pemain.start",
                                "Sun Java System Application Server",
                                new String[] {Version.getFullVersion()});
	    getLogger().log(Level.INFO, cstr);

	    // if running in debug mode, print JPDA address and transport
	    String debugOptions = System.getProperty(
						PELaunchFilter.DEBUG_OPTIONS);
	    if ( debugOptions != null && !debugOptions.equals("") ) {
                String transport = PELaunchFilter.getDebugProperty(
						    debugOptions, "transport");
                String addr = PELaunchFilter.getDebugProperty(
						    debugOptions, "address");
		String str = localStrings.getStringWithDefault(
				"pemain.debugger.message",
				"Application server is listening at address " + addr + " for debugger to attach using transport " + transport,
				new Object[] {addr, transport});

		System.err.println(str);
	    }

	    PEMain peMain = new PEMain();

	    //adding shutdown hook in case the small window on WIN OS is closed
	    ShutdownThread shutdownThread = new ShutdownThread();
	    Runtime runtime = Runtime.getRuntime();
	    runtime.addShutdownHook(shutdownThread);

	    peMain.run(System.getProperty(Constants.IAS_ROOT));

        // add startup time metrics
        final long now     = System.currentTimeMillis();
        final long pemainMillis    = now - getStartTimeMillis();
        final long pelaunchMillis  = now - PELaunch.getStartTimeMillis();
        SystemInfoData.getInstance().addPerformanceMillis( "PEMain.startup", pemainMillis );
        SystemInfoData.getInstance().addPerformanceMillis( "PELaunch.startup", pelaunchMillis );
        
        getLogger().log(Level.INFO, "pemain.startup.complete");

        if (auditManager.isAuditOn()){
            auditManager.serverStarted();
        }

	} catch(Exception e) {
	    getLogger().log(Level.SEVERE, "pemain.error", e.getMessage());
	    System.exit(1);
	}

    
public voidrun(java.lang.String rootDir)
method to start the PE server


        try {
            RRStateFactory.removeStateFile();
        } catch (Exception e) {
            getLogger().log(Level.FINE, "Could not remove restart required state file", e);
        }

	try {
	    context = createServerContext(rootDir);

	} catch (ConfigException ce) {
            getLogger().log(Level.SEVERE, "j2eerunner.cannotCreateServerContext",ce);
        }


	// Set up to route System.Out & err thru log formatter
	new SystemOutandErrHandler();

        _server.setServerContext(context);

        // Execute this only once (i.e. during server startup)
        try {
    	    // initialized the application server.

            _server.onInitialization(context);

	    if (getLogger().isLoggable(Level.FINE)) {
                getLogger().log(Level.FINE,
                                "application.config_file" +
                                context.getServerConfigURL());
                getLogger().log(Level.FINE,
                    "application.default_locale" +
                    java.util.Locale.getDefault());
            }
	    _server.onStartup();

            _server.onReady();
            
            //When uncommented, this code can be called to load all config MBeans so that
            //lazy loading is effectively disabled.
            try {
                FeatureAvailability.getInstance().getMBeanServer().queryNames(null, null);
            } catch (Exception ex) {
                // ignore
            }
            FeatureAvailability.getInstance().registerFeature( SERVER_STARTED_FEATURE, "" );
        }
        catch (Exception ee) {
            getLogger().log(Level.SEVERE, "j2eerunner.initError", ee);
            getLogger().log(Level.SEVERE, "pemain.startup.failed");
            getLogger().log(Level.INFO, "shutdown.started");
            try {
                _server.onShutdown();
            } catch (ServerLifecycleException e) {
                getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
            }
            try {
            _server.onTermination();
            } catch (ServerLifecycleException e) {
                getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
            }
            getLogger().log(Level.SEVERE,"pemain.server.startup.failed.exit");
            System.exit(1);
        }
        synchronized ( this ) {
            isStarted = true;
            this.notifyAll();
        }
    
static voidsetSystemLocale()
Sets the default locale for this instance using the system property com.sun.aas.defaultLocale set only in the PELauncheFilter. This is an implementation specific property and not a standard Java system property. The locale must be specified in the following format:

_
For example: en_US_UNIX
Of course, not all of these options need to be specified.

        String locale =
              System.getProperty(SystemPropertyConstants.DEFAULT_LOCALE_PROPERTY);
        if(locale != null && !"".equals(locale) ) {
            try {
                String[] tokens = locale.split("_",3);
                switch(tokens.length) {
                    case 0:
                        break;
                    case 1:
                        Locale.setDefault(new Locale(tokens[0]));
                        break;
                    case 2:
                        Locale.setDefault(new Locale(tokens[0],tokens[1]));
                        break;
                    default:
                        Locale.setDefault(new Locale(tokens[0],tokens[1],tokens[2]));
                        break;
                }
            } catch(Exception e) {
                getLogger().log(Level.WARNING, "locale.setdefault.error",locale);
            }
        }
    
public static voidshutdown()
Shutdown the J2EE PE/RI server. Called when "PEMain stop" is invoked, in a "client" VM. Does a remote invocation on the server.

	try {
	    RMIClient rmiClient = new RMIClient(
						true,
						getStubFilePath(),
						getSeedFilePath());

	    ShutdownEvent shutdownEvent = new ShutdownEvent(SERVER_INSTANCE);
	    getLogger().log(Level.INFO,
			    "sending notification to server..." +
			    SERVER_INSTANCE);
	    AdminEventResult result = rmiClient.sendNotification(shutdownEvent);
	    getLogger().log(Level.INFO,
			    "server.shutdown_complete");

	} catch(Exception e) {
	    getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
	}