KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > server > PEMain


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.server;
25
26 import java.io.IOException JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.PrintStream JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.util.logging.Level JavaDoc;
31 import java.util.Locale JavaDoc;
32 import org.apache.catalina.LifecycleException;
33 import org.apache.catalina.core.StandardHost;
34 import com.sun.appserv.server.ServerLifecycle;
35 import com.sun.appserv.server.ServerLifecycleException;
36 import com.sun.enterprise.config.ConfigFactory;
37 import com.sun.enterprise.config.ConfigContext;
38 import com.sun.enterprise.config.ConfigException;
39 import com.sun.enterprise.web.WebContainer;
40 import java.util.logging.Logger JavaDoc;
41 import com.sun.logging.LogDomains;
42 import com.sun.enterprise.server.logging.*;
43 import com.sun.enterprise.server.logging.stats.ErrorStatistics;
44
45 import com.sun.enterprise.admin.server.core.channel.RMIClient;
46 import com.sun.enterprise.admin.event.ShutdownEvent;
47 import com.sun.enterprise.server.Shutdown;
48 import com.sun.enterprise.admin.event.AdminEventListenerRegistry;
49 import com.sun.enterprise.admin.event.AdminEventResult;
50
51 import com.sun.enterprise.server.pluggable.PluggableFeatureFactory;
52 import com.sun.enterprise.server.pluggable.PluggableFeatureFactoryImpl;
53
54 import com.sun.enterprise.util.i18n.StringManager;
55 import com.sun.appserv.server.util.Version;
56 import com.sun.enterprise.admin.common.Status;
57
58 import com.sun.enterprise.util.ASenvPropertyReader;
59 import com.sun.enterprise.util.SystemPropertyConstants;
60
61 import com.sun.enterprise.launcher.PELaunchFilter;
62
63 import com.sun.enterprise.jms.JmsProviderLifecycle;
64
65 import com.sun.enterprise.security.store.IdentityManager;
66 import com.sun.enterprise.server.ss.ASLazyKernel;
67 import com.sun.enterprise.admin.server.core.channel.RRStateFactory;
68
69 /**kebbs**/
70  import com.sun.enterprise.admin.server.core.jmx.SunoneInterceptor;
71
72  import com.sun.enterprise.server.ondemand.OnDemandServer;
73
74 import com.sun.enterprise.security.audit.AuditManager;
75 import com.sun.enterprise.security.audit.AuditManagerFactory;
76
77 /**
78   * Start up class for PE/RI
79   */

80
81 public class PEMain {
82     
83     static {
84         // Note: This call must happen before any calls on the logger.
85
ErrorStatistics.registerStartupTime();
86     }
87
88     //------------------------------------------------------------ Constructor
89

90     /**
91      * This object will be created during the Init phase of NSAPI
92      */

93     public PEMain() {
94         // Set the context class loader
95
_loader = getClass().getClassLoader();
96         Thread.currentThread().setContextClassLoader(_loader);
97     AdminEventListenerRegistry.addShutdownEventListener(new Shutdown JavaDoc());
98         _instance = this;
99     }
100
101     // ----------------------------------------------------- Instance Variables
102

103     public static boolean shutdownStarted = false;
104
105     public static boolean shutdownThreadInvoked = false;
106
107     private static ApplicationServer _server = null;
108
109     private final static String JavaDoc STOP = "stop";
110
111     private static PEMain _instance = null;
112
113     private final static String JavaDoc SERVER_INSTANCE =
114                         System.getProperty("com.sun.aas.instanceName");
115
116     /** local string manager */
117     private static StringManager localStrings =
118                         StringManager.getManager(PEMain.class);
119
120     ServerContext context = null;
121
122     //WARNING: _logger must be initialized upon demand in this case. The
123
//reason is that this static init happens before the ServerContext
124
//is initialized
125
private static Logger JavaDoc _logger = null;
126
127     private ClassLoader JavaDoc _loader = null;
128
129     private boolean isStarted = false;
130
131     private final static String JavaDoc instance_root =
132     System.getProperty("com.sun.aas.instanceRoot");
133
134     private static AuditManager auditManager =
135             AuditManagerFactory.getAuditManagerInstance();
136
137     //No need to worry about synchronization here as getLogger call is
138
//synchronized, worse case logger will get initialized to the same
139
//value 2x.
140
private static Logger JavaDoc getLogger() {
141         if (_logger == null) {
142             _logger = LogDomains.getLogger(LogDomains.CORE_LOGGER);
143         }
144         return _logger;
145     }
146
147     // --------------------------------------------------------- Public Methods
148

149     public static void main(String JavaDoc[] args) {
150
151
152     // parse args
153
boolean verbose = false;
154     boolean dbg = false;
155
156         //set the system locale for this instance
157
setSystemLocale();
158
159     if(args[0].trim().equals(STOP)) {
160         // check if instance is already running
161
if (isInstanceRunning()) {
162             PEMain.shutdown();
163         return;
164
165         } else {
166             getLogger().log(Level.INFO, "instance.notRunning");
167         return;
168         }
169         }
170
171     try {
172
173         // add temporary switch for new ProcessLauncher.
174
// This will be removed once PE using the new invocation classes
175
// Redirect stdout and stderr if location supplied in System.properties
176
// NOTE: In verbose more the stderr only goes to the console, this is exactly the
177
// way the apache commons-launcher functioned.
178
String JavaDoc verboseMode=System.getProperty("com.sun.aas.verboseMode", "false");
179         // Temporarily commented out.
180
// Hemanth:
181
// Will move the new SystemOutandErrorHandler() here after doing
182
// some testing. The code is commented out mainly because the Log
183
// Rotation will not work with the stream opened here.
184
/*
185         if(System.getProperty("com.sun.aas.processLauncher") != null
186             && !verboseMode.equals("true")) {
187
188             // If applicable, redirect output and error streams
189             String defaultLogFile = System.getProperty("com.sun.aas.defaultLogFile");
190             if (defaultLogFile != null) {
191                 PrintStream printStream = new PrintStream(new FileOutputStream(defaultLogFile, true), true);
192                 System.setOut(printStream);
193                 System.setErr(printStream);
194             }
195         }
196         */

197
198
199         // read in parameters off the stdin if they exist
200
try {
201             // check to see is Identity info is already set from native launcher
202
if (IdentityManager.getUser() == null) {
203                 IdentityManager.populateFromInputStream();
204             }
205         } catch (IOException JavaDoc e) {
206             getLogger().log(Level.WARNING, "pemain.failureOnReadingSecurityIdentity", e);
207         }
208     if (getLogger().isLoggable(Level.FINE)) {
209         getLogger().log(Level.FINE, IdentityManager.getFormatedContents());
210     }
211
212
213
214        //Set system properties that correspond directly to asenv.conf/bat. This
215
//keeps us from having to pass them all from -D on the command line.
216
ASenvPropertyReader reader = new ASenvPropertyReader(
217            System.getProperty(SystemPropertyConstants.CONFIG_ROOT_PROPERTY));
218        reader.setSystemProperties();
219
220         // check if instance is already running
221
if (isInstanceAlreadyStarted()) {
222             getLogger().log(Level.SEVERE, "instance.alreadyRunning");
223         System.exit(0);
224         }
225
226         getLogger().log(Level.FINE, "instance.start", SERVER_INSTANCE);
227
228         //_server = new ApplicationServer();
229
_server = new OnDemandServer();
230
231             // print server starting message
232
String JavaDoc cstr = localStrings.getStringWithDefault( "pemain.start",
233                                 "Sun Java System Application Server",
234                                 new String JavaDoc[] {Version.getFullVersion()});
235         getLogger().log(Level.INFO, cstr);
236
237         // if running in debug mode, print JPDA address and transport
238
String JavaDoc debugOptions = System.getProperty(
239                         PELaunchFilter.DEBUG_OPTIONS);
240         if ( debugOptions != null && !debugOptions.equals("") ) {
241                 String JavaDoc transport = PELaunchFilter.getDebugProperty(
242                             debugOptions, "transport");
243                 String JavaDoc addr = PELaunchFilter.getDebugProperty(
244                             debugOptions, "address");
245         String JavaDoc str = localStrings.getStringWithDefault(
246                 "pemain.debugger.message",
247                 "Application server is listening at address " + addr + " for debugger to attach using transport " + transport,
248                 new Object JavaDoc[] {addr, transport});
249
250         System.err.println(str);
251         }
252
253         PEMain peMain = new PEMain();
254
255         //adding shutdown hook in case the small window on WIN OS is closed
256
ShutdownThread shutdownThread = new ShutdownThread();
257         Runtime JavaDoc runtime = Runtime.getRuntime();
258         runtime.addShutdownHook(shutdownThread);
259
260         peMain.run(System.getProperty(Constants.IAS_ROOT));
261
262             getLogger().log(Level.INFO, "pemain.startup.complete");
263
264         if (auditManager.isAuditOn()){
265             auditManager.serverStarted();
266         }
267
268     } catch(Exception JavaDoc e) {
269         getLogger().log(Level.SEVERE, "pemain.error", e.getMessage());
270         System.exit(1);
271     }
272
273     }
274
275
276     /**
277     * return the ApplicationServer object
278     */

279
280     public static ApplicationServer getApplicationServer() {
281     return _server;
282     }
283
284     public synchronized static PEMain getInstance() {
285         return _instance;
286     }
287
288     /**
289     * method to start the PE server
290     */

291     public void run(String JavaDoc rootDir) {
292
293         try {
294             RRStateFactory.removeStateFile();
295         } catch (Exception JavaDoc e) {
296             getLogger().log(Level.FINE, "Could not remove restart required state file", e);
297         }
298
299     try {
300         context = createServerContext(rootDir);
301
302     } catch (ConfigException ce) {
303             getLogger().log(Level.SEVERE, "j2eerunner.cannotCreateServerContext",ce);
304         }
305
306
307     // Set up to route System.Out & err thru log formatter
308
new SystemOutandErrHandler();
309
310         _server.setServerContext(context);
311
312         // Execute this only once (i.e. during server startup)
313
try {
314             // initialized the application server.
315

316             _server.onInitialization(context);
317
318         if (getLogger().isLoggable(Level.FINE)) {
319                 getLogger().log(Level.FINE,
320                                 "application.config_file" +
321                                 context.getServerConfigURL());
322                 getLogger().log(Level.FINE,
323                     "application.default_locale" +
324                     java.util.Locale.getDefault());
325             }
326         _server.onStartup();
327
328             _server.onReady();
329
330             //When uncommented, this code can be called to load all config MBeans so that
331
//lazy loading is effectively disabled.
332
try {
333                 SunoneInterceptor.getMBeanServerInstance().queryNames(null, null);
334             } catch (Exception JavaDoc ex) {
335
336             }
337
338         } catch (Exception JavaDoc ee) {
339             getLogger().log(Level.SEVERE, "j2eerunner.initError", ee);
340         getLogger().log(Level.SEVERE, "pemain.startup.failed");
341         getLogger().log(Level.INFO, "shutdown.started");
342         try {
343             _server.onShutdown();
344         } catch (ServerLifecycleException e) {
345             getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
346         }
347         try {
348         _server.onTermination();
349         } catch (ServerLifecycleException e) {
350             getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
351         }
352         getLogger().log(Level.SEVERE,"pemain.server.startup.failed.exit");
353         System.exit(1);
354         }
355         synchronized ( this ) {
356             isStarted = true;
357             this.notifyAll();
358         }
359     }
360
361     public boolean isStartingUp() {
362         return !isStarted;
363     }
364
365
366     // -------------------------------------------------------- Private Methods
367

368
369     /**
370      * Shutdown the J2EE PE/RI server. Called when "PEMain stop" is invoked,
371      * in a "client" VM. Does a remote invocation on the server.
372      */

373     public static void shutdown() {
374     try {
375         RMIClient rmiClient = new RMIClient(
376                         true,
377                         getStubFilePath(),
378                         getSeedFilePath());
379
380         ShutdownEvent shutdownEvent = new ShutdownEvent(SERVER_INSTANCE);
381         getLogger().log(Level.INFO,
382                 "sending notification to server..." +
383                 SERVER_INSTANCE);
384         AdminEventResult result = rmiClient.sendNotification(shutdownEvent);
385         getLogger().log(Level.INFO,
386                 "server.shutdown_complete");
387
388     } catch(Exception JavaDoc e) {
389         getLogger().log(Level.SEVERE, "j2eerunner.initError", e);
390     }
391     }
392
393
394     /**
395      * method to obtain stub file
396      */

397     public static String JavaDoc getStubFilePath() {
398
399         return instance_root +
400       File.separatorChar +
401       "config" +
402       File.separatorChar +
403       "admch";
404     }
405
406    /**
407      * method to obtain stub file
408      */

409     public static String JavaDoc getSeedFilePath() {
410
411         return instance_root +
412       File.separatorChar +
413       "config" + File.separatorChar +
414       "admsn";
415     }
416
417     /**
418      * Get status of the instance.
419      */

420     private static int getInstanceStatus() {
421         String JavaDoc stubFile = getStubFilePath();
422         String JavaDoc seedFile = getSeedFilePath();
423         RMIClient rmiClient = new RMIClient(true, stubFile, seedFile);
424         return rmiClient.getInstanceStatusCode();
425     }
426
427     /**
428      * Is instance in running state.
429      */

430     private static boolean isInstanceRunning() {
431         return (getInstanceStatus() == Status.kInstanceRunningCode);
432     }
433
434     /**
435      * Is instance in starting or running state.
436      */

437     private static boolean isInstanceStartingOrRunning() {
438         int statusCode = getInstanceStatus();
439         return (statusCode == Status.kInstanceStartingCode
440                 || statusCode == Status.kInstanceRunningCode);
441     }
442
443     /**
444      * method to check if server is already up or not
445      */

446     public static boolean isInstanceAlreadyStarted() {
447         return isInstanceStartingOrRunning();
448     }
449
450
451     /**
452      * Create and initialize a server context object and also initialize
453      * its configuration context by reading the configuration file.
454      */

455     private ServerContext createServerContext(String JavaDoc rootDir) throws ConfigException {
456
457         // setup the config and the initial server context
458
String JavaDoc[] args = new String JavaDoc[0];
459         ServerContextImpl context = new ServerContextImpl();
460
461         context.setCmdLineArgs(args);
462     context.setInstallRoot(rootDir);
463     context.setInstanceName(SERVER_INSTANCE);
464         try{
465             String JavaDoc serverXml = context.getServerConfigURL();
466         // Read server.xml and create a read-only configuration context
467
ConfigContext cfgContext =
468         ConfigFactory.createConfigContext(serverXml,
469                                                   true,
470                                                   false,
471                                                   true);
472         context.setConfigContext(cfgContext);
473     } catch (Exception JavaDoc ex){
474
475         if (!(ex instanceof ConfigException)){
476                 getLogger().log(Level.SEVERE,"j2eerunner.server_context_excp",ex);
477             if (_logger == null){
478             System.err.println("Exception in creating server context");
479             ex.printStackTrace();
480         }
481         }
482         throw new ConfigException(ex.getMessage());
483         }
484
485         PluggableFeatureFactory ff = PluggableFeatureFactoryImpl.getFactory();
486
487         context.setPluggableFeatureFactory(ff);
488         return context;
489     }
490
491
492    /**
493     * Sets the default locale for this instance using the system property
494     * com.sun.aas.defaultLocale set only in the PELauncheFilter. This is an
495     * implementation specific property and not a standard Java system property.
496     *
497     * The locale must be specified in the following format: <br>
498     * <br><i><language>_<country_<variant></i> <br>
499     * For example: <i>en_US_UNIX </i><br>
500     * Of course, not all of these options need to be specified.
501     *
502     */

503     static void setSystemLocale() {
504         String JavaDoc locale =
505               System.getProperty(SystemPropertyConstants.DEFAULT_LOCALE_PROPERTY);
506         if(locale != null && !"".equals(locale) ) {
507             try {
508                 String JavaDoc[] tokens = locale.split("_",3);
509                 switch(tokens.length) {
510                     case 0:
511                         break;
512                     case 1:
513                         Locale.setDefault(new Locale JavaDoc(tokens[0]));
514                         break;
515                     case 2:
516                         Locale.setDefault(new Locale JavaDoc(tokens[0],tokens[1]));
517                         break;
518                     default:
519                         Locale.setDefault(new Locale JavaDoc(tokens[0],tokens[1],tokens[2]));
520                         break;
521                 }
522             } catch(Exception JavaDoc e) {
523                 getLogger().log(Level.WARNING, "locale.setdefault.error",locale);
524             }
525         }
526     }
527
528     private static class ShutdownThread extends Thread JavaDoc {
529
530         public ShutdownThread() {
531         }
532
533         public void run() {
534         shutdownThreadInvoked = true;
535         if (PEMain.shutdownStarted == false) {
536         PEMain.shutdown();
537         }
538     }
539
540     }
541
542 }
543
Popular Tags