KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > web > WebContainer


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.web;
25
26 import com.sun.enterprise.util.OS;
27 import java.io.File JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.net.URLClassLoader JavaDoc;
31 import java.text.MessageFormat JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.HashMap JavaDoc;
34 //HERCULES:add
35
import java.util.Hashtable JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 //end HERCULES:add
38
import java.util.List JavaDoc;
39 import java.util.ListIterator JavaDoc;
40 import java.util.logging.Logger JavaDoc;
41 import java.util.logging.Level JavaDoc;
42 import java.util.ResourceBundle JavaDoc;
43 import java.util.Set JavaDoc;
44 import java.util.Vector JavaDoc;
45 import javax.naming.NamingException JavaDoc;
46
47 import org.apache.catalina.startup.Embedded;
48 import org.apache.catalina.Container;
49 import org.apache.catalina.Context;
50 import org.apache.catalina.Deployer;
51 import org.apache.catalina.Engine;
52 import org.apache.catalina.Loader;
53 import org.apache.catalina.Lifecycle;
54 import org.apache.catalina.LifecycleException;
55 import org.apache.catalina.LifecycleListener;
56 import org.apache.catalina.Manager;
57 import org.apache.catalina.Valve;
58 import org.apache.catalina.core.StandardContext;
59 import org.apache.catalina.core.StandardEngine;
60 import org.apache.catalina.core.StandardHost;
61 import org.apache.catalina.deploy.ErrorPage;
62 import org.apache.catalina.loader.WebappLoader;
63 import org.apache.catalina.session.FileStore;
64 import org.apache.catalina.session.PersistentManager;
65 import org.apache.catalina.session.StandardManager;
66 import org.apache.catalina.util.LifecycleSupport;
67 import org.apache.catalina.util.ServerInfo;
68 import org.apache.catalina.startup.TldConfig;
69 import org.apache.catalina.startup.DigesterFactory;
70 import org.apache.catalina.valves.RemoteAddrValve;
71 import org.apache.catalina.valves.RemoteHostValve;
72 import org.apache.jasper.compiler.TldLocationsCache;
73 import org.apache.jasper.xmlparser.ParserUtils;
74 import org.apache.coyote.tomcat5.CoyoteRequest;
75 import com.sun.enterprise.config.ConfigBean;
76 import com.sun.enterprise.config.ConfigContext;
77 import com.sun.enterprise.config.ConfigBeansFactory;
78 import com.sun.enterprise.config.ConfigException;
79 import com.sun.enterprise.config.serverbeans.ApplicationHelper;
80 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
81 import com.sun.enterprise.config.serverbeans.Applications;
82 import com.sun.enterprise.config.serverbeans.J2eeApplication;
83 import com.sun.enterprise.config.serverbeans.LogService;
84 import com.sun.enterprise.config.serverbeans.Config;
85 import com.sun.enterprise.config.serverbeans.DasConfig;
86 import com.sun.enterprise.config.serverbeans.Server;
87 import com.sun.enterprise.config.serverbeans.HttpService;
88 import com.sun.enterprise.config.serverbeans.HttpProtocol;
89 import com.sun.enterprise.config.serverbeans.ElementProperty;
90 import com.sun.enterprise.instance.InstanceEnvironment;
91 import com.sun.enterprise.server.ApplicationRegistry;
92 import com.sun.enterprise.server.StandaloneWebModulesManager;
93 import com.sun.enterprise.server.ServerContext;
94 import com.sun.enterprise.server.pluggable.WebContainerFeatureFactory;
95 import com.sun.enterprise.deployment.runtime.web.SunWebApp;
96 import com.sun.enterprise.deployment.runtime.web.CookieProperties;
97 import com.sun.enterprise.deployment.runtime.web.ManagerProperties;
98 import com.sun.enterprise.deployment.runtime.web.SessionConfig;
99 import com.sun.enterprise.deployment.runtime.web.SessionManager;
100 import com.sun.enterprise.deployment.runtime.web.SessionProperties;
101 import com.sun.enterprise.deployment.runtime.web.StoreProperties;
102 import com.sun.enterprise.deployment.runtime.web.WebProperty;
103 import com.sun.enterprise.deployment.Application;
104 import com.sun.enterprise.deployment.util.WebValidatorWithoutCL;
105 import com.sun.enterprise.deployment.util.WebBundleVisitor;
106 import com.sun.enterprise.management.util.J2EEModuleUtil;
107 import com.sun.enterprise.util.io.FileUtils;
108 import com.sun.enterprise.util.logging.IASLevel;
109 import com.sun.enterprise.util.StringUtils;
110 import com.sun.enterprise.web.logger.IASLogger;
111 import com.sun.enterprise.web.session.PersistenceType;
112 import com.sun.enterprise.web.session.SessionCookieConfig;
113 import com.sun.enterprise.security.web.SingleSignOn;
114
115 import com.sun.enterprise.security.SecurityUtil;
116 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapper;
117 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapperFactory;
118
119 import com.sun.enterprise.deployment.Application;
120 import com.sun.enterprise.deployment.WebBundleDescriptor;
121 import com.sun.enterprise.deployment.WebServicesDescriptor;
122 import com.sun.enterprise.deployment.WebServiceEndpoint;
123 import com.sun.enterprise.instance.WebModulesManager;
124 import com.sun.enterprise.instance.AppsManager;
125 import com.sun.enterprise.Switch;
126 import com.sun.appserv.server.ServerLifecycleException;
127 import com.sun.appserv.server.util.ASClassLoaderUtil;
128 import com.sun.appserv.server.util.Version;
129 import com.sun.logging.LogDomains;
130
131 import com.sun.web.security.WebSecurityManager;
132 import com.sun.web.security.WebSecurityManagerFactory;
133 import com.sun.web.security.RealmAdapter;
134
135 // monitoring imports
136
import java.util.HashSet JavaDoc;
137 import javax.management.j2ee.statistics.Stats JavaDoc;
138 import com.sun.enterprise.deployment.WebComponentDescriptor;
139 import com.sun.enterprise.admin.monitor.stats.ServletStats;
140 import com.sun.enterprise.web.stats.ServletStatsImpl;
141 import com.sun.enterprise.web.monitor.PwcServletStats;
142 import com.sun.enterprise.web.monitor.impl.PwcServletStatsImpl;
143 import com.sun.enterprise.admin.monitor.stats.WebModuleStats;
144 import com.sun.enterprise.web.stats.WebModuleStatsImpl;
145 import com.sun.enterprise.web.monitor.PwcWebModuleStats;
146 import com.sun.enterprise.web.monitor.impl.PwcWebModuleStatsImpl;
147 import com.sun.enterprise.admin.monitor.registry.MonitoringRegistry;
148 import com.sun.enterprise.admin.monitor.registry.MonitoringRegistrationException;
149 import com.sun.enterprise.admin.monitor.registry.MonitoringLevel;
150 import com.sun.enterprise.admin.monitor.registry.MonitoringLevelListener;
151 import com.sun.enterprise.admin.monitor.registry.MonitoredObjectType;
152 import com.sun.enterprise.config.serverbeans.MonitoringService;
153 import com.sun.enterprise.config.serverbeans.ModuleMonitoringLevels;
154
155 //HERCULES:add
156
//admin event imports
157
import com.sun.enterprise.admin.event.ApplicationDeployEvent;
158 import com.sun.enterprise.admin.event.ApplicationDeployEventListener;
159 import com.sun.enterprise.admin.event.ModuleDeployEvent;
160 import com.sun.enterprise.admin.event.ModuleDeployEventListener;
161 import com.sun.enterprise.admin.event.AdminEventListenerRegistry;
162 //end HERCULES:add
163

164 // Begin EE: 4927099 load only associated applications
165
import com.sun.enterprise.config.serverbeans.Domain;
166 import com.sun.enterprise.config.serverbeans.Servers;
167 import com.sun.enterprise.config.serverbeans.ApplicationRef;
168 // End EE: 4927099 load only associated applications
169

170 /**
171  * Web container implementation for the Sun ONE Application Server.
172  *
173  * This class is intended for use in versions of the application server
174  * that *do not* have web-core as well as in versions that do. NSAPI
175  * specific functionality is implemented the NSAPIWebContainer subclass
176  * in the <code>j2ee-plugin</code> component.
177  */

178 public class WebContainer
179     implements Lifecycle,
180                ApplicationDeployEventListener,
181                ModuleDeployEventListener,
182                MonitoringLevelListener {
183
184     // ------------------------------------------------------------ Constants
185

186     public static final String JavaDoc DISABLED = "disabled";
187     public static final String JavaDoc OFF = "off";
188     public static final String JavaDoc ON = "on";
189     public static final String JavaDoc STATE = "state";
190     public static final String JavaDoc SSO_ENABLED="sso-enabled";
191     public static final String JavaDoc SSO_MAX_IDLE="sso-max-inactive-seconds";
192     public static final String JavaDoc SSO_REAP_INTERVAL="sso-reap-interval-seconds";
193     public static final String JavaDoc ADMIN_VS = "__asadmin";
194     public static final String JavaDoc DISPATCHER_MAX_DEPTH="dispatcher-max-depth";
195
196     static final int DEFAULT_REAP_INTERVAL = 60; // 1 minute
197

198     public static final String JavaDoc JWS_APPCLIENT_EAR_NAME = "__JWSappclients";
199     public static final String JavaDoc JWS_APPCLIENT_WAR_NAME = "sys";
200     private static final String JavaDoc JWS_APPCLIENT_MODULE_NAME = JWS_APPCLIENT_EAR_NAME + ":" + JWS_APPCLIENT_WAR_NAME + ".war";
201
202     private static final String JavaDoc DOC_BUILDER_FACTORY_PROPERTY =
203         "javax.xml.parsers.DocumentBuilderFactory";
204     private static final String JavaDoc DOC_BUILDER_FACTORY_IMPL =
205         "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
206
207     // ----------------------------------------------------- Instance Variables
208

209     /**
210      * The embedded Catalina object.
211      */

212     protected EmbeddedWebContainer _embedded = null;
213
214     /**
215      * The parent/top-level container in <code>_embedded</code> for virtual
216      * servers.
217      */

218
219     /**
220      * The server context under which this container was created.
221      */

222     protected ServerContext _serverContext = null;
223
224     /**
225      * The config context under which this container was created.
226      */

227     protected ConfigContext _configContext = null;
228
229     protected Domain domain = null;
230     protected InstanceEnvironment instance = null;
231     protected WebModulesManager webModulesManager = null;
232     protected AppsManager appsManager = null;
233
234     /**
235      * The schema2beans object that represents the root node of server.xml.
236      */

237     private Server _serverBean = null;
238
239     /**
240      * The id of this web container object.
241      */

242     private String JavaDoc _id = null;
243
244     /**
245      * The logger to use for logging ALL web container related messages.
246      */

247     protected static Logger JavaDoc _logger = null;
248
249     /**
250      * The resource bundle containing the message strings for _logger.
251      */

252     protected static ResourceBundle JavaDoc _rb = null;
253
254     /*
255      * The current web container monitoring level
256      */

257     protected static MonitoringLevel monitoringLevel;
258
259     /**
260      * The current level of logging verbosity for this object.
261      */

262     protected Level JavaDoc _logLevel = null;
263
264     /**
265      * Controls the verbosity of the web container subsystem's debug messages.
266      *
267      * This value is non-zero only when the iAS level is one of FINE, FINER
268      * or FINEST.
269      */

270     protected int _debug = 0;
271
272     /**
273      * Top-level directory for files generated (compiled JSPs) by
274      * standalone web modules.
275      */

276     private String JavaDoc _modulesWorkRoot = null;
277
278     // START S1AS 6178005
279
/**
280      * Top-level directory where ejb stubs of standalone web modules are stored
281      */

282     private String JavaDoc modulesStubRoot = null;
283     // END S1AS 6178005
284

285     /**
286      * Absolute path for location where all the deployed
287      * standalone modules are stored for this Server Instance.
288      */

289     protected String JavaDoc _modulesRoot = null;
290
291     /**
292      * Top-level directory for files generated by application web modules.
293      */

294     private String JavaDoc _appsWorkRoot = null;
295
296     // START S1AS 6178005
297
/**
298      * Top-level directory where ejb stubs for applications are stored.
299      */

300     private String JavaDoc appsStubRoot = null;
301     // END S1AS 6178005
302

303     /**
304      * Indicates whether dynamic reloading is enabled (as specified by
305      * the dynamic-reload-enabled attribute of <applications> in server.xml)
306      */

307     private boolean _reloadingEnabled = false;
308     
309     /**
310      * The number of seconds between checks for modified classes (if
311      * dynamic reloading is enabled).
312      *
313      * This value is specified by the reload-poll-interval attribute of
314      * <applications> in server.xml.
315      */

316     private int _pollInterval = 2;
317
318     /**
319      * Adds/removes standalone web modules to the reload monitor thread
320      * (when dynamic reloading is enabled in server.xml).
321      */

322     private StandaloneWebModulesManager _reloadManager = null;
323
324     /**
325      * The lifecycle event support for this component.
326      */

327     private LifecycleSupport _lifecycle = new LifecycleSupport(this);
328
329     /**
330      * Has this component been started yet?
331      */

332     protected boolean _started = false;
333         
334     /**
335      * The WebSecurityManagerFactory used for generating web permission
336      */

337     private WebSecurityManagerFactory webSecurityManagerFactory
338            = WebSecurityManagerFactory.getInstance();
339
340     private EjbWebServiceRegistryListener ejbWebServiceRegistryListener;
341
342     
343     private static final String JavaDoc DOL_DEPLOYMENT =
344                                    "com.sun.enterprise.web.deployment.backend";
345     
346     /**
347      * Are we using Tomcat deployment backend or DOL?
348      */

349     protected static boolean useDOLforDeployment = true;
350
351     /**
352      * The instance classpath, which is composed of the pathnames of
353      * domain_root/lib/classes and domain_root/lib/[*.jar|*.zip] (in this
354      * order), separated by the path-separator character.
355      */

356     private String JavaDoc instanceClassPath;
357
358     
359     static{
360         if (System.getProperty(DOL_DEPLOYMENT) != null){
361             useDOLforDeployment = Boolean.valueOf(
362                             System.getProperty(DOL_DEPLOYMENT)).booleanValue();
363         }
364     }
365     
366     /**
367      * The current <code>WebContainer</code> instance used (single).
368      */

369     protected static WebContainer webContainer;
370     // ------------------------------------------------------------ Constructor
371

372     /**
373      * This creates the embedded Catalina/Jasper container and sets the config
374      * properties on the container.
375      */

376     protected WebContainer(String JavaDoc id, ServerContext context) {
377
378         _id = id;
379         _serverContext = context;
380
381         _configContext = _serverContext.getConfigContext();
382
383         String JavaDoc rootDir = _serverContext.getInstallRoot();
384         String JavaDoc name = _serverContext.getInstanceName();
385         instance = new InstanceEnvironment(rootDir, name);
386         _modulesWorkRoot = instance.getWebModuleCompileJspPath();
387         _appsWorkRoot = instance.getApplicationCompileJspPath();
388         _modulesRoot = instance.getModuleRepositoryPath();
389
390         instanceClassPath = getInstanceClassPath(instance);
391
392         ejbWebServiceRegistryListener = new EjbWebServiceRegistryListener(this);
393
394         // START S1AS 6178005
395
modulesStubRoot = instance.getModuleStubPath();
396         appsStubRoot = instance.getApplicationStubPath();
397         // END S1AS 6178005
398

399         // XXX logger initialization should probably be done in
400
// in LogServiceLifecycle.onInitialization()
401
if (_logger == null) {
402             _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER);
403             _rb = _logger.getResourceBundle();
404         }
405
406         try {
407             webModulesManager = new WebModulesManager(instance);
408             appsManager = new AppsManager(instance);
409         } catch (ConfigException cx) {
410             _logger.log(Level.WARNING,
411                 "Error in creating web modules manager: ", cx);
412         }
413
414         setNoTldScan();
415
416         LogService logService = null;
417
418         try {
419             domain = (Domain) _configContext.getRootConfigBean();
420
421             _serverBean = ServerBeansFactory.getServerBean(_configContext);
422
423             getDynamicReloadingSettings(ServerBeansFactory.getDasConfigBean(_configContext));
424
425             Config cfg = ServerBeansFactory.getConfigBean(_configContext);
426             logService = cfg.getLogService();
427             initLogLevel(logService);
428             initMonitoringLevel(cfg.getMonitoringService());
429
430             ElementProperty maxDepth
431                 = ServerBeansFactory.getWebContainerBean(_configContext).getElementPropertyByName(DISPATCHER_MAX_DEPTH);
432             if (maxDepth != null && maxDepth.getValue() != null) {
433
434                 int depth = -1;
435                 try {
436                     depth = Integer.parseInt(maxDepth.getValue());
437                 } catch (Exception JavaDoc e) {}
438
439                 if (depth > 0) {
440                     CoyoteRequest.setMaxDispatchDepth(depth);
441                     if (_logger.isLoggable(Level.FINE)) {
442                         _logger.fine("Maximum depth for nested request "
443                                      + "dispatches set to "
444                                      + maxDepth.getValue());
445                     }
446                 }
447             }
448
449         } catch (ConfigException e) {
450             _logger.log(Level.SEVERE, "webcontainer.configError", e);
451         }
452
453         String JavaDoc logServiceFile = null;
454         if (logService != null) {
455             logServiceFile = logService.getFile();
456         }
457         _embedded = new EmbeddedWebContainer(_logger, _serverContext, this,
458                                              logServiceFile);
459         _embedded.setUseNaming(false);
460         if (_debug > 1)
461             _embedded.setDebug(_debug);
462         _embedded.setLogger(new IASLogger(_logger));
463
464         DigesterFactory.setSchemaResourcePrefix("/schemas/");
465         DigesterFactory.setDtdResourcePrefix("/dtds/");
466         ParserUtils.setSchemaResourcePrefix("/schemas/");
467         ParserUtils.setDtdResourcePrefix("/dtds/");
468
469         /*
470          * Set the server name and version.
471          * Allow customers to override this information by specifying
472          * product.name system property. For example, some customers prefer
473          * not to disclose the product name and version for security
474          * reasons, in which case they would set the value of the
475          * product.name system property to the empty string.
476          */

477         String JavaDoc serverInfo = System.getProperty("product.name");
478         if (serverInfo != null) {
479             ServerInfo.setServerInfo(serverInfo);
480         } else {
481             ServerInfo.setServerInfo(Version.getVersion());
482         }
483   
484         //HERCULES:add
485
//added for internal monitoring
486
WebDebugMonitor debugMonitor = new WebDebugMonitor();
487         HashMap JavaDoc monitorMap = debugMonitor.getDebugMonitoringDetails();
488         debugMonitoring = ((Boolean JavaDoc) monitorMap.get("debugMonitoring")).booleanValue();
489         debugMonitoringPeriodMS = ((Long JavaDoc) monitorMap.get(
490                                     "debugMonitoringPeriodMS")).longValue();
491
492         if (debugMonitoring) {
493             _timer.schedule(new DebugMonitor(_embedded), 0L,
494                                              debugMonitoringPeriodMS);
495         }
496         //added for internal monitoring
497
//END HERCULES:add
498
}
499     
500     //HERCULES:add
501
//added for monitoring
502
private static boolean debugMonitoring=false;
503     private static long debugMonitoringPeriodMS = 30000L;
504     private static WebContainerTimer _timer = new WebContainerTimer();
505     //added for monitoring
506
//END HERCULES:add
507

508
509     // ------------------------------------------------------------ Properties
510

511     /**
512      * Return the web container identifier.
513      */

514     public String JavaDoc getID() {
515         return _id;
516     }
517     
518      // --------------------------------------------------------- HADB Health Status
519

520     private HealthChecker _healthChecker = null;
521     public HealthChecker getHealthChecker() {
522         return _healthChecker;
523     }
524  
525     private void initHealthChecker() {
526         //added the pluggable interface way of getting the health checker
527
WebContainerFeatureFactory webContainerFeatureFactory =
528             _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
529         HealthChecker healthChecker =
530             webContainerFeatureFactory.getHADBHealthChecker(this);
531         if(_logger.isLoggable(Level.FINEST)) {
532             _logger.finest("WebContainer>>initHealthChecker - healthChecker = " + healthChecker);
533         }
534         if(healthChecker != null) {
535             _healthChecker = healthChecker;
536             try {
537                 _healthChecker.start();
538             } catch (LifecycleException ex) {}
539         }
540      }
541      
542      private void stopHealthChecker() {
543          if(_healthChecker != null) {
544              try {
545                  _healthChecker.stop();
546              } catch (LifecycleException ex) {}
547              _healthChecker = null;
548          }
549      }
550      
551      // --------------------------------------------------------- end HADB Health Status
552

553     
554     // ------------------------------------------------ Admin Event Processing
555

556     private WebContainerAdminEventProcessor _adminEventProcessor = null;
557     
558     //HERCULES:add
559
public void registerAdminEvents() {
560
561         AdminEventListenerRegistry.addApplicationDeployEventListener(this);
562         AdminEventListenerRegistry.addModuleDeployEventListener(this);
563         WebContainerFeatureFactory webContainerFeatureFactory =
564             _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
565     _adminEventProcessor =
566             webContainerFeatureFactory.getWebContainerAdminEventProcessor();
567         _adminEventProcessor.init(_embedded);
568     }
569     
570     public void unregisterAdminEvents() {
571         AdminEventListenerRegistry.removeEventListener(this);
572         _adminEventProcessor = null;
573     }
574
575     public void applicationDeployed(ApplicationDeployEvent deployEvent) {
576         _adminEventProcessor.applicationDeployed(deployEvent);
577     }
578     
579     public void applicationUndeployed(ApplicationDeployEvent deployEvent) {
580         _adminEventProcessor.applicationUndeployed(deployEvent);
581     }
582     
583     public void applicationRedeployed(ApplicationDeployEvent deployEvent) {
584         _adminEventProcessor.applicationRedeployed(deployEvent);
585     }
586     
587     public void applicationEnabled(ApplicationDeployEvent deployEvent) {
588     }
589     
590     public void applicationDisabled(ApplicationDeployEvent deployEvent) {
591     }
592     
593     public void moduleDeployed(ModuleDeployEvent deployEvent) {
594         _adminEventProcessor.moduleDeployed(deployEvent);
595     }
596     
597     public void moduleUndeployed(ModuleDeployEvent deployEvent) {
598         _adminEventProcessor.moduleUndeployed(deployEvent);
599     }
600     
601     public void moduleRedeployed(ModuleDeployEvent deployEvent) {
602         _adminEventProcessor.moduleRedeployed(deployEvent);
603     }
604     
605     public void moduleEnabled(ModuleDeployEvent deployEvent) {
606     }
607     
608     public void moduleDisabled(ModuleDeployEvent deployEvent) {
609     }
610     //end HERCULES:add
611

612
613     // -------------------------------------- Monitoring Level Event Processing
614

615     public void registerMonitoringLevelEvents() {
616         MonitoringRegistry monitoringRegistry =
617                 _serverContext.getMonitoringRegistry();
618         monitoringRegistry.registerMonitoringLevelListener(
619                                         this, MonitoredObjectType.SERVLET);
620     }
621
622     public void unregisterMonitoringLevelEvents() {
623         MonitoringRegistry monitoringRegistry =
624                 _serverContext.getMonitoringRegistry();
625         monitoringRegistry.unregisterMonitoringLevelListener(this);
626     }
627
628     public void setLevel(MonitoringLevel level) {
629         // deprecated, ignore
630
}
631
632     public void changeLevel(MonitoringLevel from, MonitoringLevel to,
633                 Stats JavaDoc handback) {
634         // deprecated, ignore
635
}
636
637     public void changeLevel(MonitoringLevel from, MonitoringLevel to,
638                             MonitoredObjectType type) {
639         if (MonitoredObjectType.SERVLET.equals(type)) {
640             monitoringLevel = to;
641             if(MonitoringLevel.OFF.equals(to)) {
642                 this.resetMonitorStatistics();
643             }
644         }
645     }
646
647     /**
648      * Returns the current monitoring level.
649      *
650      * @return The current monitoring level
651      */

652     public static MonitoringLevel getMonitoringLevel() {
653         return monitoringLevel;
654     }
655     
656     /**
657      * Returns true if monitoring is enabled, false otherwise.
658      *
659      * @return true if monitoring is enabled, false otherwise
660      */

661     public static boolean isMonitoringEnabled() {
662         return (!MonitoringLevel.OFF.equals(monitoringLevel));
663     }
664     
665     private void resetMonitorStatistics() {
666         MonitorUtil.resetMonitorStats(_embedded, _serverContext);
667     }
668
669
670     // -------------------------------------------------------- Public Methods
671

672     /**
673      * Create a virtual server/host.
674      */

675     public VirtualServer createVS(String JavaDoc vsID,
676                                   com.sun.enterprise.config.serverbeans.VirtualServer vsBean,
677                                   String JavaDoc docroot,
678                                   String JavaDoc logFile,
679                                   MimeMap mimeMap,
680                                   HttpProtocol httpProtocol) {
681
682         // Initialize the docroot
683
VirtualServer vs = (VirtualServer) _embedded.createHost(vsID,
684                                                                 vsBean,
685                                 docroot,
686                                 logFile,
687                                                                 mimeMap);
688                     
689         configureVirtualServerState(vs, vsBean);
690         configureRemoteAddressFilterValve(vs, vsBean);
691         configureRemoteHostFilterValve(vs, vsBean, httpProtocol);
692         configureSSOValve(vs, vsBean);
693         configureRedirect(vs, vsBean);
694         configureErrorPage(vs, vsBean);
695
696         return vs;
697     }
698
699     // ------------------------------------------------------ Lifecycle Methods
700

701
702     /**
703      * Add a lifecycle event listener to this component.
704      *
705      * @param listener The listener to add
706      */

707     public void addLifecycleListener(LifecycleListener listener) {
708         _lifecycle.addLifecycleListener(listener);
709     }
710
711
712     /**
713      * Remove a lifecycle event listener from this component.
714      *
715      * @param listener The listener to remove
716      */

717     public void removeLifecycleListener(LifecycleListener listener) {
718         _lifecycle.removeLifecycleListener(listener);
719     }
720     
721     private void doSchemaCheck() {
722         SchemaUpdater schemaUpdater =
723             _serverContext.getPluggableFeatureFactory().getSchemaUpdater();
724         try {
725             schemaUpdater.doSchemaCheck();
726         } catch (Exception JavaDoc ex) {
727             _logger.log(Level.SEVERE, "schemaupdater.error", ex);
728         }
729     }
730
731     /**
732      * Prepare for the beginning of active use of the public methods of this
733      * component. This method should be called before any of the public
734      * methods of the component are utilized.
735      *
736      * @exception IllegalStateException if this component has already been
737      * started
738      * @exception LifecycleException if this component detects a fatal error
739      * that prevents this component from being used
740      */

741     public void start() throws LifecycleException {
742         if (_started) {
743             String JavaDoc msg = _rb.getString("webcontainer.alreadyStarted");
744             throw new LifecycleException(msg);
745         }
746
747         if (System.getProperty(DOC_BUILDER_FACTORY_PROPERTY) == null) {
748             System.setProperty(DOC_BUILDER_FACTORY_PROPERTY,
749                                DOC_BUILDER_FACTORY_IMPL);
750         }
751
752         //HERCULES:mod
753
registerAdminEvents();
754         registerMonitoringLevelEvents();
755         initHealthChecker();
756         long btime = 0L;
757         if (_logger.isLoggable(Level.FINE)) {
758             _logger.fine("before schema check");
759             btime = System.currentTimeMillis();
760         }
761         doSchemaCheck();
762         if (_logger.isLoggable(Level.FINE)) {
763             _logger.fine("after schema check time: " + (System.currentTimeMillis() - btime));
764         }
765         //end HERCULES:mod
766

767         ejbWebServiceRegistryListener.register();
768
769         Engine[] engines = _embedded.getEngines();
770
771         for (int j=0; j<engines.length; j++) {
772             Container[] vsList = engines[j].findChildren();
773             for (int i = 0; i < vsList.length; i++) {
774                 // Load all the standalone web modules for each VS
775
loadWebModules((VirtualServer)vsList[i]);
776             }
777         }
778
779         // Load the web modules specified in each j2ee-application
780
loadAllJ2EEApplicationWebModules(true);
781
782         //
783
// Create and load a default context for those virtual servers
784
// who do not have one configured already (i.e. when the configuration
785
// for the virtual-server element does not specify a default-web-module
786
// and none of the web modules (on a virtual server) are loaded at
787
// a context-root=""
788
//
789
loadSystemDefaultWebModules();
790
791         _lifecycle.fireLifecycleEvent(START_EVENT, null);
792         _started = true;
793          // start the embedded container
794
_embedded.start();
795
796         if (_reloadingEnabled) {
797             // Enable dynamic reloading (via the .reload file) for all
798
// standalone web-modules that are marked as enabled
799

800             Applications appsBean = null;
801             try {
802                 appsBean = ServerBeansFactory.getApplicationsBean(_configContext);
803             } catch (ConfigException e) {
804                String JavaDoc msg = _rb.getString("webcontainer.appsConfigError");
805                _logger.log(Level.SEVERE, msg, e);
806             }
807
808             _reloadManager = new StandaloneWebModulesManager(_id,
809                                                              _modulesRoot,
810                                                              _pollInterval);
811             if (appsBean != null) {
812                 com.sun.enterprise.config.serverbeans.WebModule[] wmBeans = appsBean.getWebModule();
813                 if (wmBeans != null && wmBeans.length > 0) {
814                     _reloadManager.addWebModules(wmBeans);
815                 }
816             }
817         }
818         enableAllWSEndpoints();
819     }
820
821     /**
822      * Gracefully terminate the active use of the public methods of this
823      * component. This method should be the last one called on a given
824      * instance of this component.
825      *
826      * @exception IllegalStateException if this component has not been started
827      * @exception LifecycleException if this component detects a fatal error
828      * that needs to be reported
829      */

830     public void stop() throws LifecycleException {
831         // Validate and update our current component state
832
if (!_started) {
833             String JavaDoc msg = _rb.getString("webcontainer.notStarted");
834             throw new LifecycleException(msg);
835         }
836           
837         ejbWebServiceRegistryListener.unregister();
838
839         //HERCULES:mod
840
unregisterAdminEvents();
841     unregisterMonitoringLevelEvents();
842         stopHealthChecker();
843         
844         WebContainerStartStopOperation startStopOperation =
845             this.getWebContainerStartStopOperation();
846         /* TODO: remove after testing
847         //added the pluggable interface way of getting the start/stop operation
848         WebContainerFeatureFactory webContainerFeatureFactory =
849             _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
850         WebContainerStartStopOperation startStopOperation =
851             webContainerFeatureFactory.getWebContainerStartStopOperation();
852         startStopOperation.init(_embedded);
853          */

854         ArrayList JavaDoc shutdownCleanupCapablesList = startStopOperation.doPreStop();
855         //end HERCULES:mod
856

857         _started = false;
858
859         // stop the embedded container
860
try{
861             _embedded.stop();
862         } catch (LifecycleException ex){
863             if (ex.getMessage().indexOf("has not been started") == -1){
864                 throw ex;
865             }
866         }
867
868         if (_reloadManager != null) {
869             // Remove the entries from the reload monitor thread corresponding
870
// to this web container object that is being stopped
871
_reloadManager.stop();
872             _reloadManager = null;
873         }
874          
875         //HERCULES:mod
876
startStopOperation.doPostStop(shutdownCleanupCapablesList);
877         //end HERCULES:mod
878
}
879     
880     /**
881      * Get the webContainerStartStopOperation
882      * used for doing shutdown cleanup work
883      */

884     public WebContainerStartStopOperation getWebContainerStartStopOperation() {
885         
886         //added the pluggable interface way of getting the start/stop operation
887
WebContainerFeatureFactory webContainerFeatureFactory =
888             _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
889         WebContainerStartStopOperation startStopOperation =
890             webContainerFeatureFactory.getWebContainerStartStopOperation();
891         
892         startStopOperation.init(_embedded);
893         return startStopOperation;
894     }
895
896     // -------------------------------------------------------- Private Methods
897

898     /**
899      * Loads all the standalone web-modules that are hosted (as specified by
900      * the server configuration) under the specified virtual server.
901      */

902     protected void loadWebModules(VirtualServer vs) {
903         WebModuleConfig wmInfo = null;
904         
905         loadDefaultWebModule(vs,_serverBean);
906         
907         // Get a list of the web modules to be loaded on this virtual server
908
List JavaDoc modules = vs.getWebModules(_serverBean, _modulesRoot);
909         if ((modules != null) && (modules.size() > 0)) {
910             ListIterator JavaDoc iterator = modules.listIterator();
911             while (iterator.hasNext()) {
912                 wmInfo = (WebModuleConfig) iterator.next();
913                 com.sun.enterprise.config.serverbeans.WebModule webBean =
914                      wmInfo.getBean();
915                  // load the stand alone web module if it is enabled
916
if (webBean != null &&
917                      isEnabled(webBean.getConfigContext(), webBean.getName())) {
918                      loadStandaloneWebModule(vs, wmInfo);
919                  }
920             }
921         }
922     }
923     
924     
925     /**
926      * Add the default web-module to a virtual-server.
927      * @param vs the virtual-server which doesn't have a default web-module.
928      * @param serverBean the server config bean used to configure the
929      * default web module.
930      */

931     public void loadDefaultWebModule(VirtualServer vs,
932                                                 Server serverBean){
933         WebModuleConfig wmInfo = vs.getUserDefaultWebModuleConfig(serverBean);
934         if (wmInfo != null) {
935             // If there is a 'default-web-module' for the virtual server,
936
// load it first, thus preventing other web modules that may
937
// have a context-root = "" from getting loaded as the default
938
// web module for this virtual server
939
loadStandaloneWebModule(vs, wmInfo);
940         }
941     }
942     
943     
944     /**
945      * Creates and configures a default context for each virtual server
946      * that doesn't have one configured already.
947      */

948     protected void loadSystemDefaultWebModules() {
949
950         Engine[] engines = _embedded.getEngines();
951
952         for (int j=0; j<engines.length; j++) {
953             Container[] vsArray = engines[j].findChildren();
954             for (int i = 0; i < vsArray.length; i++) {
955                 if (vsArray[i] instanceof VirtualServer) {
956                     VirtualServer vs = (VirtualServer) vsArray[i];
957                     WebModuleConfig wmInfo =
958                         vs.createSystemDefaultWebModuleIfNecessary();
959                     if (wmInfo != null) {
960                         loadStandaloneWebModule(vs, wmInfo);
961                     }
962                 }
963             }
964         }
965     }
966
967     /**
968      * Load the specified web module as a standalone module on the specified
969      * virtual server.
970      */

971     protected void loadStandaloneWebModule(VirtualServer vs,
972                                          WebModuleConfig wmInfo) {
973         loadWebModule(vs, wmInfo, "null");
974     }
975
976     /**
977      * Loads all the web modules that are configured for every
978      * j2ee-application specified in server.xml.
979      */

980     protected void loadAllJ2EEApplicationWebModules() {
981         loadAllJ2EEApplicationWebModules(false);
982     }
983
984     /**
985      * Loads all the web modules that are configured for every
986      * j2ee-application specified in server.xml.
987      *
988      * @param isStartUp true, if this is called during server startup
989      */

990     private void loadAllJ2EEApplicationWebModules(boolean isStartUp) {
991
992         Applications appsBean = null;
993         try {
994             appsBean = ServerBeansFactory.getApplicationsBean(_configContext);
995         } catch (ConfigException e) {
996             String JavaDoc msg = _rb.getString("webcontainer.appsConfigError");
997             _logger.log(Level.SEVERE, msg, e);
998         }
999
1000        if (appsBean != null) {
1001            J2eeApplication[] j2eeAppBeans = appsBean.getJ2eeApplication();
1002            if (j2eeAppBeans != null) {
1003                for (int i = 0; i < j2eeAppBeans.length; i++) {
1004                    //Begin EE: 4927099 - load only associated applications
1005
if ( isReferenced(j2eeAppBeans[i].getName()) ) {
1006                        loadJ2EEApplicationWebModules(j2eeAppBeans[i]);
1007                    }
1008                    //End EE: 4927099 - load only associated applications
1009
}
1010            }
1011        }
1012    }
1013
1014    /**
1015     * Loads all the web modules that are configured for the specified
1016     * j2ee-application.
1017     */

1018    public void loadJ2EEApplicationWebModules(J2eeApplication j2eeAppBean) {
1019        if ((j2eeAppBean != null) &&
1020            isEnabled(j2eeAppBean.getConfigContext(), j2eeAppBean.getName())) {
1021            String JavaDoc id = j2eeAppBean.getName();
1022            String JavaDoc location = j2eeAppBean.getLocation();
1023            String JavaDoc resourceType = j2eeAppBean.getObjectType();
1024
1025            ApplicationRegistry registry = ApplicationRegistry.getInstance();
1026            ClassLoader JavaDoc appLoader = registry.getClassLoaderForApplication(id);
1027            if (appLoader != null) {
1028                Application appDesc = registry.getApplication(appLoader);
1029             
1030                // Check to see if this app had deployed successfully (4663247)
1031
if(appDesc == null){
1032                    Object JavaDoc[] params = { id };
1033                    _logger.log(Level.SEVERE, "webcontainer.notLoaded",
1034                                params);
1035                } else {
1036                    //Hercules: add
1037
ConfigContext eventConfigContext = j2eeAppBean.getConfigContext();
1038                    //end Hercules: add
1039
String JavaDoc j2eeApplication = appDesc.getRegistrationName();
1040                    Set JavaDoc wbds = appDesc.getWebBundleDescriptors();
1041                    WebBundleDescriptor wbd = null;
1042                    com.sun.enterprise.config.serverbeans.WebModule wm = null;
1043                    WebModuleConfig wmInfo = null;
1044                    for (Iterator JavaDoc itr = wbds.iterator(); itr.hasNext(); ) {
1045                        StringBuffer JavaDoc dir = new StringBuffer JavaDoc(location);
1046                        wbd = (WebBundleDescriptor) itr.next();
1047                        String JavaDoc moduleName = wbd.getModuleDescriptor().getArchiveUri();
1048                        dir.append(File.separator);
1049                        dir.append(FileUtils.makeFriendlyFilename(moduleName));
1050
1051                        wm = new com.sun.enterprise.config.serverbeans.WebModule();
1052                        //Hercules add
1053
wm.setConfigContext(eventConfigContext);
1054                        //end Hercules add
1055
wm.setName(moduleName);
1056                        wm.setContextRoot(wbd.getContextRoot());
1057                        wm.setLocation(dir.toString());
1058                        wm.setEnabled(true);
1059                        wm.setObjectType(resourceType);
1060
1061                        wmInfo = new WebModuleConfig();
1062                        wmInfo.setBean(wm);
1063                        wmInfo.setDescriptor(wbd);
1064                        wmInfo.setParentLoader(appLoader);
1065                        wmInfo.setVirtualServers(
1066                                getVirtualServers(id,
1067                                        j2eeAppBean.getConfigContext()));
1068                        loadWebModule(wmInfo, j2eeApplication);
1069                    }
1070                }//end if(appDesc != null)
1071
}
1072        }
1073    }
1074
1075   /**
1076     * Whether or not a component (either an application or a module) should be
1077     * enabled is defined by the "enable" attribute on both the
1078     * application/module element and the application-ref element.
1079     *
1080     * @param config The dynamic ConfigContext
1081     * @param moduleName The name of the component (application or module)
1082     * @return boolean
1083     */

1084    protected boolean isEnabled (ConfigContext config, String JavaDoc moduleName) {
1085        try {
1086            if (config == null) {
1087                config = _configContext;
1088            }
1089 
1090            ConfigBean app = ApplicationHelper.findApplication(config,
1091                moduleName);
1092            Server server = ServerBeansFactory.getServerBean(config);
1093            ApplicationRef appRef = server.getApplicationRefByRef(moduleName);
1094
1095            return ((app != null && app.isEnabled()) &&
1096                        (appRef != null && appRef.isEnabled()));
1097        } catch (ConfigException e) {
1098            _logger.log(Level.WARNING, "Error finding " + moduleName, e);
1099
1100            //If there is anything wrong, do not enable the module
1101
return false;
1102        }
1103    }
1104
1105    /**
1106     * Creates and configures a web module for each virtual server
1107     * that the web module is hosted under.
1108     *
1109     * If no virtual servers are specified, then the web module is
1110     * loaded on EVERY virtual server.
1111     */

1112    public List JavaDoc<Throwable JavaDoc> loadWebModule(
1113        WebModuleConfig wmInfo, String JavaDoc j2eeApplication) {
1114
1115        String JavaDoc vsIDs = wmInfo.getVirtualServers();
1116        List JavaDoc vsList = StringUtils.parseStringList(vsIDs, " ,");
1117        boolean loadToAll = (vsList == null) || (vsList.size() == 0);
1118        boolean loadAtLeastToOne = false;
1119
1120        Engine[] engines = _embedded.getEngines();
1121
1122        List JavaDoc<Throwable JavaDoc> throwables = new ArrayList JavaDoc();
1123        for (int j=0; j<engines.length; j++) {
1124            Container[] vsArray = engines[j].findChildren();
1125            for (int i = 0; i < vsArray.length; i++) {
1126                if (vsArray[i] instanceof VirtualServer) {
1127                    VirtualServer vs = (VirtualServer) vsArray[i];
1128
1129                    /*
1130                     * Fix for bug# 4913636:
1131                     * If the vsList is null and the virtual server is
1132                     * __asadmin, continue with next iteration
1133                     * because we don't want to load user apps on __asadmin
1134                     */

1135                    if (vs.getID().equals(ADMIN_VS) && loadToAll) {
1136                        continue;
1137                    }
1138
1139                    if ( loadToAll
1140                            || vsList.contains(vs.getID())
1141                            || verifyAlias(vsList,vs)){
1142
1143                        Throwable JavaDoc t = loadWebModule(vs, wmInfo, j2eeApplication);
1144                        if (t != null) {
1145                            throwables.add(t);
1146                        }
1147                        loadAtLeastToOne = true;
1148                    }
1149                }
1150            }
1151        }
1152        if (!loadAtLeastToOne) {
1153            Object JavaDoc[] params = {wmInfo.getName(), vsIDs};
1154            _logger.log(Level.SEVERE, "webcontainer.moduleNotLoadedToVS",
1155                            params);
1156        }
1157        return throwables;
1158    }
1159
1160
1161    /**
1162     * Deploy on aliases as well as host.
1163     */

1164    private boolean verifyAlias(List JavaDoc vsList,VirtualServer vs){
1165        for(int i=0; i < vs.getAliases().length; i++){
1166            if (vsList.contains(vs.getAliases()[i]) ){
1167                return true;
1168            }
1169        }
1170        return false;
1171    }
1172    
1173    /**
1174     * Creates and configures a web module and adds it to the specified
1175     * virtual server.
1176     */

1177    protected Throwable JavaDoc loadWebModule(VirtualServer vs, WebModuleConfig wmInfo,
1178                                 String JavaDoc j2eeApplication) {
1179        String JavaDoc wmName = wmInfo.getName();
1180        if (wmName.indexOf(Constants.NAME_SEPARATOR) != -1) {
1181            wmInfo.setWorkDirBase(_appsWorkRoot);
1182            // START S1AS 6178005
1183
wmInfo.setStubBaseDir(appsStubRoot);
1184            // END S1AS 6178005
1185
} else {
1186            wmInfo.setWorkDirBase(_modulesWorkRoot);
1187            // START S1AS 6178005
1188
wmInfo.setStubBaseDir(modulesStubRoot);
1189            // END S1AS 6178005
1190
}
1191
1192        String JavaDoc wmContextPath = wmInfo.getContextPath();
1193        String JavaDoc displayContextPath = null;
1194        if (wmContextPath.equals(""))
1195            displayContextPath = "/";
1196        else
1197            displayContextPath = wmContextPath;
1198
1199        HashMap JavaDoc adHocPaths = null;
1200        HashMap JavaDoc adHocSubtrees = null;
1201        WebModule ctx = (WebModule)vs.findChild(wmContextPath);
1202        if (ctx != null) {
1203            if (ctx instanceof AdHocWebModule) {
1204                /*
1205                 * Found ad-hoc web module which has been created by web
1206                 * container in order to store mappings for ad-hoc paths
1207                 * and subtrees.
1208                 * All these mappings must be propagated to the context
1209                 * that is being deployed.
1210                 */

1211                if (ctx.hasAdHocPaths()) {
1212                    adHocPaths = ctx.getAdHocPaths();
1213                }
1214                if (ctx.hasAdHocSubtrees()) {
1215                    adHocSubtrees = ctx.getAdHocSubtrees();
1216                }
1217                vs.removeChild(ctx);
1218            } else if (Constants.DEFAULT_WEB_MODULE_NAME
1219                    .equals(ctx.getModuleName())) {
1220                /*
1221                 * Dummy context that was created just off of a docroot,
1222                 * (see
1223                 * VirtualServer.createSystemDefaultWebModuleIfNecessary()).
1224                 * Unload it so it can be replaced with the web module to be
1225                 * loaded
1226                 */

1227                unloadWebModule(wmContextPath,
1228                                ctx.getJ2EEApplication(),
1229                                vs.getName(),
1230                                null,
1231                                true);
1232            } else if (!ctx.getAvailable()){
1233                /*
1234                 * Context has been marked unavailable by a previous
1235                 * call to disableWebModule. Mark the context as available and
1236                 * return
1237                 */

1238                ctx.setAvailable(true);
1239                return null;
1240            } else {
1241                Object JavaDoc[] params = { vs.getID(), displayContextPath, wmName };
1242                _logger.log(Level.WARNING, "webcontainer.duplicateContextRoot",
1243                            params);
1244                return null;
1245            }
1246        }
1247
1248        Object JavaDoc[] params = { wmName, vs.getID(), displayContextPath };
1249        if (wmName.equals(Constants.DEFAULT_WEB_MODULE_NAME))
1250            _logger.log(Level.FINE, "webcontainer.loadModule", params);
1251        else
1252            _logger.log(Level.INFO, "webcontainer.loadModule", params);
1253
1254        String JavaDoc docBase = null;
1255        if (JWS_APPCLIENT_MODULE_NAME.equals(wmName)) {
1256            File JavaDoc installRootFile = new File JavaDoc(System.getProperty("com.sun.aas.installRoot"));
1257            String JavaDoc path = installRootFile.toURI().getPath();
1258            if (OS.isWindows()) {
1259                path = path.substring(1); // On Windows, skip the slash before the device
1260
}
1261            docBase = path;
1262        } else {
1263            docBase = wmInfo.getLocation();
1264        }
1265        ctx = (WebModule) _embedded.createContext(wmContextPath,
1266                                                  docBase,
1267                                                  vs.getDefaultWebXmlLocation(),
1268                                                  useDOLforDeployment,
1269                                                  wmInfo.getDescriptor());
1270
1271        // Set JSR 77 object name and attributes
1272
String JavaDoc engineName = vs.getParent().getName();
1273        String JavaDoc j2eeServer = _serverContext.getInstanceName();
1274        String JavaDoc domain = _serverContext.getDefaultDomainName();
1275        String JavaDoc server = domain + ":j2eeType=J2EEServer,name=" + j2eeServer;
1276        String JavaDoc[] javaVMs = J2EEModuleUtil.getjavaVMs();
1277        ctx.setDomain(domain);
1278
1279        ctx.setJ2EEServer(j2eeServer);
1280        ctx.setJ2EEApplication(j2eeApplication);
1281        ctx.setEngineName(engineName);
1282        ctx.setServer(server);
1283        ctx.setJavaVMs(javaVMs);
1284        ctx.setCachingAllowed(true);
1285        ctx.setCacheControls(vs.getCacheControls());
1286 
1287        if (adHocPaths != null) {
1288            ctx.addAdHocPaths(adHocPaths);
1289        }
1290        if (adHocSubtrees != null) {
1291            ctx.addAdHocSubtrees(adHocSubtrees);
1292        }
1293
1294        // Object containing web.xml information
1295
WebBundleDescriptor wbd = wmInfo.getDescriptor();
1296
1297        //Set the context root
1298
if (wmInfo.getBean() != null) {
1299            String JavaDoc contextRoot = wmInfo.getBean().getContextRoot();
1300            ctx.setContextRoot(contextRoot);
1301            if (wbd != null) {
1302                wbd.setContextRoot(contextRoot);
1303            }
1304        } else {
1305            // Should never happen.
1306
_logger.log(Level.WARNING, "Unable to set context root", wmInfo);
1307        }
1308
1309        //
1310
// Ensure that the generated directory for JSPs in the document root
1311
// (i.e. those that are serviced by a system default-web-module)
1312
// is different for each virtual server.
1313
//
1314
String JavaDoc wmInfoWorkDir = wmInfo.getWorkDir();
1315        if (wmInfoWorkDir != null) {
1316            StringBuffer JavaDoc workDir = new StringBuffer JavaDoc(wmInfo.getWorkDir());
1317            if (wmName.equals(Constants.DEFAULT_WEB_MODULE_NAME)) {
1318                workDir.append("-");
1319                workDir.append(FileUtils.makeFriendlyFilename(vs.getID()));
1320            }
1321            ctx.setWorkDir(workDir.toString());
1322        }
1323
1324        ClassLoader JavaDoc parentLoader = wmInfo.getParentLoader();
1325        if (parentLoader == null) {
1326            // Use the shared classloader as the parent for all
1327
// standalone web-modules
1328
parentLoader = _serverContext.getSharedClassLoader();
1329        }
1330        ctx.setParentClassLoader(parentLoader);
1331
1332        Throwable JavaDoc exception = null;
1333        Switch sw = Switch.getSwitch();
1334        try{
1335            // Determine if an alternate DD is set for this web-module in
1336
// the application
1337
if (wbd != null) {
1338                String JavaDoc altDDName = wbd.getModuleDescriptor().
1339                                        getAlternateDescriptor();
1340                if (altDDName != null) {
1341                    // we should load the alt dd from generated/xml directory
1342
// first, then fall back to original app location.
1343

1344                    // if we have alt dd, it must be an embedded web module
1345
String JavaDoc appName = wmName.substring(0,
1346                        wmName.indexOf(Constants.NAME_SEPARATOR));
1347                    String JavaDoc appLoc =
1348                        appsManager.getGeneratedXMLLocation(appName);
1349                    if (! FileUtils.safeIsDirectory(appLoc)) {
1350                        appLoc = wmInfo.getLocation()+"/..";
1351                    }
1352
1353                    if (altDDName.startsWith("/")) {
1354                        altDDName = appLoc+altDDName.trim();
1355                    }
1356                    else {
1357                        altDDName = appLoc+"/"+altDDName.trim();
1358                    }
1359                    Object JavaDoc[] objs = {altDDName, wmName};
1360                    _logger.log(Level.INFO, "webcontainer.altDDName", objs);
1361                    ctx.setAltDDName(altDDName);
1362
1363                }
1364                // time to update the Web Services related information in
1365
// our runtime jsr77 mbeans. We publish two extra properties
1366
// hasWebServices and endpointAddresses for webservices
1367
// enable web applications.
1368
if (wbd.hasWebServices()) {
1369                    ctx.setHasWebServices(true);
1370                    
1371                    // creates the list of endpoint addresses
1372
String JavaDoc[] endpointAddresses;
1373                    WebServicesDescriptor webService = wbd.getWebServices();
1374                    Vector JavaDoc endpointList = new Vector JavaDoc();
1375                    for (Iterator JavaDoc endpoints = webService.getEndpoints().iterator();
1376                    endpoints.hasNext();) {
1377                        WebServiceEndpoint wse = (WebServiceEndpoint) endpoints.next();
1378                        if (wbd.getContextRoot()!=null) {
1379                            endpointList.add(wbd.getContextRoot() + "/"
1380                                             + wse.getEndpointAddressUri());
1381                        } else {
1382                            endpointList.add(wse.getEndpointAddressUri());
1383                        }
1384                    }
1385                    endpointAddresses = new String JavaDoc[endpointList.size()];
1386                    endpointList.copyInto(endpointAddresses);
1387                    
1388                    ctx.setEndpointAddresses(endpointAddresses);
1389                    
1390                } else {
1391                    ctx.setHasWebServices(false);
1392                }
1393            }
1394
1395            // Object containing sun-web.xml information
1396
SunWebApp iasBean = null;
1397
1398            // The default context is the only case when wbd == null
1399
if (wbd != null)
1400                iasBean = wbd.getSunDescriptor();
1401
1402            // set the sun-web config bean
1403
ctx.setIasWebAppConfigBean(iasBean);
1404            ctx.setID(wmName);
1405
1406            // Configure the class loader delegation model, classpath etc
1407
Loader JavaDoc loader = configureLoader(ctx, iasBean, wmInfo);
1408            
1409            // Set the class loader on the DOL object
1410
if (wbd != null && wbd.hasWebServices())
1411                wbd.addExtraAttribute("WEBLOADER", loader);
1412
1413            // Enable dynamic reloading
1414
if (_reloadingEnabled) {
1415                if (_reloadManager == null) {
1416                    _reloadManager = new StandaloneWebModulesManager(
1417                                                            _id,
1418                                                            _modulesRoot,
1419                                                            _pollInterval);
1420                }
1421                _reloadManager.addWebModule(wmInfo.getBean());
1422            }
1423
1424            // Configure SingleThreadedServletPools, work/tmp directory etc
1425
configureMiscSettings(ctx, iasBean, vs, displayContextPath);
1426
1427            // Configure the session manager and other related settings
1428
// HERCULES:mod - take into account if app is distributable
1429
// passing in WebBundleDescriptor which has info about whether
1430
// app is distributable
1431
configureSessionSettings(ctx, iasBean, wbd, wmInfo);
1432            // END HERCULES:mod
1433

1434            // set i18n info from locale-charset-info tag in sun-web.xml
1435
ctx.setI18nInfo();
1436
1437            if (wbd != null) {
1438                String JavaDoc resourceType = wmInfo.getBean().getObjectType();
1439                boolean isSystem = (resourceType != null &&
1440                    resourceType.startsWith("system-"));
1441                ctx.setRealm(new RealmAdapter(wbd, isSystem));
1442                configureSecurity(wbd, isSystem);
1443                sw.setDescriptorFor(ctx, wbd);
1444
1445                // post processing DOL object for standalone web module
1446
if (wbd.getApplication() != null &&
1447                    wbd.getApplication().isVirtual()) {
1448                    wbd.visit((WebBundleVisitor) new WebValidatorWithoutCL());
1449                }
1450
1451                sw.getNamingManager().bindObjects(wbd);
1452            }
1453
1454            // Add virtual server mime mappings, if present
1455
addMimeMappings(ctx, vs.getMimeMap());
1456
1457        } catch (Throwable JavaDoc ex){
1458            exception = ex;
1459        }
1460
1461        if (wbd != null && wbd.getApplication() != null) {
1462            // no dummy web module
1463
sw.setDescriptorFor(ctx, wbd);
1464            String JavaDoc moduleName;
1465            // S1AS BEGIN WORKAROUND FOR 6174360
1466
if (wbd.getApplication().isVirtual()) {
1467                // this is a standalone module
1468
moduleName = wbd.getApplication().getRegistrationName();
1469            } else {
1470                moduleName = wbd.getModuleDescriptor().getArchiveUri();
1471            }
1472            // S1AS END WORKAROUND FOR 6174360
1473
ctx.setModuleName(moduleName);
1474        } else {
1475            ctx.setModuleName(Constants.DEFAULT_WEB_MODULE_NAME);
1476        }
1477
1478        try {
1479            vs.addChild(ctx);
1480        } catch (Throwable JavaDoc ex){
1481            exception = ex;
1482        }
1483        
1484        if (exception != null){
1485            ctx.setAvailable(false);
1486
1487            Object JavaDoc[] objs = {wmName, exception};
1488            _logger.log(Level.SEVERE, "webcontainer.webModuleDisabled", objs);
1489            
1490        }
1491        enableWSMonitoring(wbd, j2eeServer);
1492        return exception;
1493    }
1494
1495
1496    /**
1497    * Generate the JSR 115 policy file for a web application, bundled
1498    * within a ear or deployed as a standalone war file.
1499    *
1500    * Implementation note: If the generated file doesn't contains
1501    * all the permission, the role mapper is probably broken.
1502    */

1503    protected void configureSecurity(WebBundleDescriptor wbd,
1504                                     boolean isSystem) {
1505        try{
1506            webSecurityManagerFactory.newWebSecurityManager(wbd);
1507        String JavaDoc context = WebSecurityManager.getContextID(wbd);
1508        SecurityUtil.generatePolicyFile(context);
1509        }catch(Exception JavaDoc ce){
1510            _logger.log(Level.SEVERE, "webcontainer.configureSecurity", ce);
1511            throw new RuntimeException JavaDoc(ce);
1512        }
1513    }
1514    
1515    /**
1516     * Utility Method to access the ServerContext
1517     */

1518     public ServerContext getServerContext() {
1519        return _serverContext;
1520    }
1521    
1522    /**
1523     * Configure the class loader for the web module based on the
1524     * settings in sun-web.xml's class-loader element (if any).
1525     */

1526    private Loader JavaDoc configureLoader(WebModule ctx, SunWebApp bean,
1527                                   WebModuleConfig wmInfo) {
1528
1529        com.sun.enterprise.deployment.runtime.web.ClassLoader clBean = null;
1530
1531        Loader JavaDoc loader = _embedded.createLoader(ctx.getParentClassLoader());
1532
1533        if (bean != null) {
1534            clBean = bean.getClassLoader();
1535        }
1536        if (clBean != null) {
1537            configureLoaderAttributes(loader, clBean, ctx);
1538            configureLoaderProperties(loader, clBean);
1539        } else {
1540            loader.setDelegate(true);
1541        }
1542
1543        // START S1AS 6178005
1544
String JavaDoc stubPath = wmInfo.getStubPath();
1545        if (stubPath != null) {
1546            loader.addRepository("file:" + stubPath + File.separator);
1547        }
1548        // END S1AS 6178005
1549

1550        addLibs(loader, ctx);
1551
1552        // START PE 4985680
1553
/**
1554         * Adds the given package name to the list of packages that may
1555         * always be overriden, regardless of whether they belong to a
1556         * protected namespace
1557         */

1558        String JavaDoc packagesName =
1559            System.getProperty("com.sun.enterprise.overrideablejavaxpackages");
1560
1561        if (packagesName != null) {
1562            List JavaDoc overridablePackages =
1563                    StringUtils.parseStringList(packagesName, " ,");
1564            for( int i=0; i < overridablePackages.size(); i++){
1565                loader.addOverridablePackage((String JavaDoc)overridablePackages.get(i));
1566            }
1567        }
1568        // END PE 4985680
1569

1570        ctx.setLoader(loader);
1571        return loader;
1572    }
1573
1574    /**
1575     * Configure miscellaneous settings such as the pool size for
1576     * single threaded servlets, specifying a temporary directory other
1577     * than the default etc.
1578     *
1579     * Since the work directory is used when configuring the session manager
1580     * persistence settings, this method must be invoked prior to
1581     * <code>configureSessionSettings</code>.
1582     */

1583    private void configureMiscSettings(WebModule ctx, SunWebApp bean,
1584                                       VirtualServer vs, String JavaDoc contextPath) {
1585
1586        /*
1587         * Web app inherits setting of allowLinking property from vs on which
1588         * it is being deployed, but may override it using allowLinking
1589         * property in its sun-web.xml
1590         */

1591        boolean allowLinking = vs.getAllowLinking();
1592
1593        if ((bean != null) && (bean.sizeWebProperty() > 0)) {
1594            WebProperty[] props = bean.getWebProperty();
1595            for (int i = 0; i < props.length; i++) {
1596
1597                String JavaDoc name = props[i].getAttributeValue("name");
1598                String JavaDoc value = props[i].getAttributeValue("value");
1599                if (name == null || value == null) {
1600                    throw new IllegalArgumentException JavaDoc(
1601                        _rb.getString("webcontainer.nullWebProperty"));
1602                }
1603
1604                if (name.equalsIgnoreCase("singleThreadedServletPoolSize")) {
1605                    int poolSize = ctx.getSTMPoolSize();
1606                    try {
1607                        poolSize = Integer.parseInt(value);
1608                    } catch (NumberFormatException JavaDoc e) {
1609                        Object JavaDoc[] params =
1610                            { value, contextPath, Integer.toString(poolSize) };
1611                        _logger.log(Level.WARNING,
1612                                    "webcontainer.invalidServletPoolSize",
1613                                    params);
1614                    }
1615                    if (poolSize > 0) {
1616                        ctx.setSTMPoolSize(poolSize);
1617                    }
1618
1619                } else if (name.equalsIgnoreCase("tempdir")) {
1620                    ctx.setWorkDir(value);
1621                } else if (name.equalsIgnoreCase("crossContextAllowed")) {
1622                    boolean crossContext = ConfigBean.toBoolean(value);
1623                    ctx.setCrossContext(crossContext);
1624        } else if (name.equalsIgnoreCase("allowLinking")) {
1625                    allowLinking = ConfigBean.toBoolean(value);
1626                // START S1AS8PE 4817642
1627
} else if (name.equalsIgnoreCase("reuseSessionID")) {
1628                    boolean reuse = ConfigBean.toBoolean(value);
1629                    ctx.setReuseSessionID(reuse);
1630                    if (reuse) {
1631                        Object JavaDoc[] params = { contextPath,
1632                                            vs.getID() };
1633                        _logger.log(Level.WARNING,
1634                                    "webcontainer.sessionIDsReused",
1635                                    params);
1636                    }
1637                // END S1AS8PE 4817642
1638
} else if(name.equalsIgnoreCase("useResponseCTForHeaders")) {
1639                    if(value.equalsIgnoreCase("true")) {
1640                        ctx.setResponseCTForHeaders();
1641                    }
1642                } else if(name.equalsIgnoreCase("encodeCookies")) {
1643                    boolean flag = ConfigBean.toBoolean(value);
1644                    ctx.setEncodeCookies(flag);
1645                // START RIMOD 4642650
1646
} else if (name.equalsIgnoreCase("relativeRedirectAllowed")) {
1647                    boolean relativeRedirect = ConfigBean.toBoolean(value);
1648                    ctx.setAllowRelativeRedirect(relativeRedirect);
1649                // END RIMOD 4642650
1650
} else if (name.equalsIgnoreCase("fileEncoding")) {
1651                    ctx.setFileEncoding(value);
1652                } else if (name.equalsIgnoreCase("enableTldValidation")
1653                        && ConfigBean.toBoolean(value)) {
1654                    ctx.setTldValidation(true);
1655                } else if (name.equalsIgnoreCase("enableTldNamespaceAware")
1656                        && ConfigBean.toBoolean(value)) {
1657                    ctx.setTldNamespaceAware(true);
1658                } else {
1659                    Object JavaDoc[] params = { name, value };
1660                    _logger.log(Level.WARNING, "webcontainer.invalidProperty",
1661                                params);
1662                }
1663            }
1664        }
1665
1666        ctx.setAllowLinking(allowLinking);
1667    }
1668    
1669    /**
1670     * Create and configure the session manager for this web application
1671     * according to the persistence type specified.
1672     *
1673     * Also configure the other aspects of session management for this
1674     * web application according to the values specified in the session-config
1675     * element of sun-web.xml (and whether app is distributable)
1676     * HERCULES:mod method signature added wbd
1677     */

1678    private void configureSessionSettings(WebModule ctx,
1679                                          SunWebApp bean,
1680                                          WebBundleDescriptor wbd,
1681                                          WebModuleConfig wmInfo) {
1682
1683        SessionConfig cfg = null;
1684        SessionManager smBean = null;
1685        SessionProperties sessionBean = null;
1686        CookieProperties cookieBean = null;
1687
1688        if (bean != null)
1689            cfg = bean.getSessionConfig();
1690
1691        if (cfg != null)
1692            smBean = cfg.getSessionManager();
1693
1694        if (cfg != null)
1695            sessionBean = cfg.getSessionProperties();
1696
1697        if (cfg != null)
1698            cookieBean = cfg.getCookieProperties();
1699        
1700        //Hercules: mod - passing wbd and wmInfo into these methods
1701
configureSessionManager(ctx, smBean, wbd, wmInfo);
1702        //configureSessionManager(ctx, smBean, wbd);
1703
configureSession(ctx, sessionBean, wbd);
1704        //end HERCULES:mod
1705
configureCookieProperties(ctx, cookieBean);
1706    }
1707    
1708    /**
1709     * The application id for this web module
1710     * HERCULES:add
1711     */

1712    public String JavaDoc getApplicationId(WebModule wm) {
1713        return wm.getID();
1714    }
1715
1716
1717    /**
1718     * Return the Absolute path for location where all the deployed
1719     * standalone modules are stored for this Server Instance.
1720     */

1721    public String JavaDoc getModulesRoot() {
1722        return _modulesRoot;
1723    }
1724
1725    
1726    /**
1727     * Configure the session manager according to the persistence-type
1728     * specified in the <session-manager> element and the related
1729     * settings in the <manager-properties> and <store-properties> elements
1730     * in sun-web.xml.
1731     * HERCULES:modified
1732     */

1733    private void configureSessionManager(WebModule ctx,
1734                                         SessionManager smBean,
1735                                         WebBundleDescriptor wbd,
1736                                         WebModuleConfig wmInfo) {
1737        
1738        PersistenceType persistence = PersistenceType.MEMORY;
1739        String JavaDoc frequency = null;
1740        String JavaDoc scope = null;
1741        
1742        SessionManagerConfigurationHelper configHelper =
1743            new SessionManagerConfigurationHelper(ctx, smBean, wbd, wmInfo);
1744        
1745        persistence = configHelper.getPersistenceType();
1746        frequency = configHelper.getPersistenceFrequency();
1747        scope = configHelper.getPersistenceScope();
1748
1749        if (_logger.isLoggable(Level.FINEST)) {
1750            _logger.finest("IN WebContainer>>ConfigureSessionManager before builder factory");
1751            _logger.finest("FINAL_PERSISTENCE-TYPE IS = "
1752                           + persistence.getType());
1753            _logger.finest("FINAL_PERSISTENCE_FREQUENCY IS = " + frequency);
1754            _logger.finest("FINAL_PERSISTENCE_SCOPE IS = " + scope);
1755        }
1756
1757    PersistenceStrategyBuilderFactory factory =
1758            new PersistenceStrategyBuilderFactory();
1759        PersistenceStrategyBuilder builder =
1760            factory.createPersistenceStrategyBuilder(persistence.getType(),
1761                                                     frequency, scope, ctx);
1762        if (_logger.isLoggable(Level.FINEST)) {
1763            _logger.finest("PersistenceStrategyBuilder class = "
1764                           + builder.getClass().getName());
1765        }
1766
1767        builder.setLogger(_logger);
1768        builder.initializePersistenceStrategy(ctx, smBean);
1769    }
1770    
1771
1772    /**
1773     * Get the persistence frequency for this web module
1774     * (this is the value from sun-web.xml if defined
1775     * @param the session manager config bean
1776     * HERCULES:add
1777     */

1778    private String JavaDoc getPersistenceFrequency(SessionManager smBean) {
1779        String JavaDoc persistenceFrequency = null;
1780        ManagerProperties mgrBean = smBean.getManagerProperties();
1781        if ((mgrBean != null) && (mgrBean.sizeWebProperty() > 0)) {
1782            WebProperty[] props = mgrBean.getWebProperty();
1783            for (int i = 0; i < props.length; i++) {
1784
1785                String JavaDoc name = props[i].getAttributeValue(WebProperty.NAME);
1786                String JavaDoc value = props[i].getAttributeValue(WebProperty.VALUE);
1787                if (name == null || value == null) {
1788                    throw new IllegalArgumentException JavaDoc(
1789                        _rb.getString("webcontainer.nullWebProperty"));
1790                }
1791
1792                if (name.equalsIgnoreCase("persistenceFrequency")) {
1793                    persistenceFrequency = value;
1794                    break;
1795                }
1796            }
1797        }
1798        return persistenceFrequency;
1799    }
1800    
1801    /**
1802     * Get the persistence scope for this web module
1803     * (this is the value from sun-web.xml if defined
1804     * @param the session manager config bean
1805     * HERCULES:add
1806     */

1807    private String JavaDoc getPersistenceScope(SessionManager smBean) {
1808        String JavaDoc persistenceScope = null;
1809        StoreProperties storeBean = smBean.getStoreProperties();
1810        if ((storeBean != null) && (storeBean.sizeWebProperty() > 0)) {
1811            WebProperty[] props = storeBean.getWebProperty();
1812            for (int i = 0; i < props.length; i++) {
1813
1814                String JavaDoc name = props[i].getAttributeValue(WebProperty.NAME);
1815                String JavaDoc value = props[i].getAttributeValue(WebProperty.VALUE);
1816                if (name == null || value == null) {
1817                    throw new IllegalArgumentException JavaDoc(
1818                        _rb.getString("webcontainer.nullWebProperty"));
1819                }
1820
1821                if (name.equalsIgnoreCase("persistenceScope")) {
1822                    persistenceScope = value;
1823                    break;
1824                }
1825            }
1826        }
1827        return persistenceScope;
1828    }
1829        
1830    
1831    /**
1832     * Configure the attributes of the session, such as the timeout,
1833     * whether to force URL rewriting etc.
1834     * HERCULES:mod passing in new param wbd
1835     */

1836    private void configureSession(WebModule ctx, SessionProperties spBean,
1837                                  WebBundleDescriptor wbd) {
1838
1839        boolean timeoutConfigured = false;
1840        int timeoutSeconds = 1800; // tomcat default (see StandardContext)
1841
boolean enableCookies = true;
1842
1843        if ((spBean != null) && (spBean.sizeWebProperty() > 0)) {
1844            WebProperty[] props = spBean.getWebProperty();
1845            for (int i = 0; i < props.length; i++) {
1846
1847                String JavaDoc name = props[i].getAttributeValue(WebProperty.NAME);
1848                String JavaDoc value = props[i].getAttributeValue(WebProperty.VALUE);
1849                if (name == null || value == null) {
1850                    throw new IllegalArgumentException JavaDoc(
1851                        _rb.getString("webcontainer.nullWebProperty"));
1852                }
1853
1854                if (name.equalsIgnoreCase("timeoutSeconds")) {
1855                    try {
1856                        timeoutSeconds = Integer.parseInt(value);
1857                        timeoutConfigured = true;
1858                    } catch (NumberFormatException JavaDoc e) {
1859                        // XXX need error message
1860
}
1861                } else if (name.equalsIgnoreCase("enableCookies")) {
1862                    enableCookies = ConfigBean.toBoolean(value);
1863                } else {
1864                    Object JavaDoc[] params = { name };
1865                    _logger.log(Level.INFO, "webcontainer.notYet", params);
1866                }
1867            }
1868        }
1869        
1870        //HERCULES:added/modified
1871
int webXmlTimeoutSeconds = -1;
1872        if(wbd != null) {
1873            webXmlTimeoutSeconds = wbd.getSessionTimeout() * 60;
1874        }
1875
1876        //web.xml setting has precedence if it exists
1877
//ignore if the value is the 30 min default
1878
if (webXmlTimeoutSeconds != -1 && webXmlTimeoutSeconds != 1800) {
1879            ctx.getManager().setMaxInactiveIntervalSeconds(webXmlTimeoutSeconds);
1880        } else {
1881            /*
1882             * Do not override Tomcat default, unless 'timeoutSeconds' was
1883             * specified in sun-web.xml
1884             */

1885            if (timeoutConfigured) {
1886                ctx.getManager().setMaxInactiveIntervalSeconds(timeoutSeconds);
1887            }
1888            
1889        }
1890        //end HERCULES:added/modified
1891

1892        ctx.setCookies(enableCookies);
1893    }
1894
1895    /**
1896     * Configure the settings for the session cookie using the values
1897     * in sun-web.xml's cookie-property
1898     */

1899    private void configureCookieProperties(WebModule ctx,
1900                                           CookieProperties bean) {
1901        if (bean != null) {
1902            WebProperty[] props = bean.getWebProperty();
1903            if (props != null) {
1904                SessionCookieConfig cookieConfig = new SessionCookieConfig();
1905                for (int i = 0; i < props.length; i++) {
1906
1907                    String JavaDoc name = props[i].getAttributeValue(WebProperty.NAME);
1908                    String JavaDoc value = props[i].getAttributeValue(WebProperty.VALUE);
1909                    if (name == null || value == null) {
1910                        throw new IllegalArgumentException JavaDoc(
1911                            _rb.getString("webcontainer.nullWebProperty"));
1912                    }
1913
1914                    if (name.equalsIgnoreCase("cookieName")) {
1915                        cookieConfig.setName(value);
1916                    } else if (name.equalsIgnoreCase("cookiePath")) {
1917                        cookieConfig.setPath(value);
1918                    } else if (name.equalsIgnoreCase("cookieMaxAgeSeconds")) {
1919                        try {
1920                            cookieConfig.setMaxAge(Integer.parseInt(value));
1921                        } catch (NumberFormatException JavaDoc e) {
1922                            // XXX need error message
1923
}
1924                    } else if (name.equalsIgnoreCase("cookieDomain")) {
1925                        cookieConfig.setDomain(value);
1926                    } else if (name.equalsIgnoreCase("cookieComment")) {
1927                        cookieConfig.setComment(value);
1928                    } else {
1929                        Object JavaDoc[] params = { name, value };
1930                        _logger.log(Level.WARNING,
1931                                    "webcontainer.invalidProperty",
1932                                    params);
1933                    }
1934                }
1935                if (props.length > 0) {
1936                    if (_logger.isLoggable(Level.FINE)) {
1937                        _logger.fine("WebModule[" + ctx.getPath() + "]: "
1938                                     + cookieConfig);
1939                    }
1940                    ctx.setSessionCookieConfig(cookieConfig);
1941                }
1942            }
1943        }
1944    }
1945
1946
1947    /**
1948     * Configures the given <code>VirtualServer</code> with its state
1949     * (on | off | disabled).
1950     */

1951    protected void configureVirtualServerState(
1952            VirtualServer host,
1953            com.sun.enterprise.config.serverbeans.VirtualServer vsBean){
1954
1955        String JavaDoc stateValue = ON;
1956        if (vsBean != null){
1957            stateValue = vsBean.getState();
1958        }
1959
1960        if ( ( !stateValue.equalsIgnoreCase(ON) )
1961            && ( host.getName().equalsIgnoreCase(ADMIN_VS) ) ){
1962            throw new java.lang.IllegalArgumentException JavaDoc(
1963                "virtual-server "
1964                + ADMIN_VS + " state property cannot be modified");
1965        }
1966        
1967        if ( stateValue.equalsIgnoreCase(DISABLED) ) {
1968            // state="disabled"
1969
host.setIsDisabled(true);
1970        } else if ( !ConfigBean.toBoolean( stateValue ) ) {
1971            // state="off"
1972
host.setIsOff(true);
1973        }
1974    }
1975
1976
1977    /**
1978     * Configures the SSO valve for the given virtual server from the
1979     * SSO configuration specified in the given virtual server bean.
1980     */

1981    private void configureSSOValve(
1982            VirtualServer vs,
1983            com.sun.enterprise.config.serverbeans.VirtualServer vsBean) {
1984
1985        if (vsBean == null) {
1986            return;
1987        }
1988
1989        // is SSO enabled?
1990
if (!isSSOEnabled(vsBean)) {
1991            Object JavaDoc[] params = { vs.getID() };
1992            _logger.log(Level.INFO, "webcontainer.ssodisabled", params);
1993
1994        } else {
1995            // yes, configure and add SSO valve
1996
try {
1997                WebContainerFeatureFactory webContainerFeatureFactory =
1998                    _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
1999                SSOFactory ssoFactory = webContainerFeatureFactory.getSSOFactory();
2000                SingleSignOn sso = ssoFactory.createSingleSignOnValve();
2001                if (_debug > 1)
2002                    sso.setDebug(_debug);
2003            
2004                // set max idle time if given
2005
ElementProperty idle =
2006                    vsBean.getElementPropertyByName(SSO_MAX_IDLE);
2007                if (idle !=null && idle.getValue() != null) {
2008                    _logger.fine("SSO entry max idle time set to: " +
2009                                 idle.getValue());
2010                    int i = Integer.parseInt(idle.getValue());
2011                    sso.setMaxInactive(i);
2012                }
2013
2014                // set expirer thread sleep time if given
2015
ElementProperty expireTime =
2016                    vsBean.getElementPropertyByName(SSO_REAP_INTERVAL);
2017                if (expireTime !=null && expireTime.getValue() != null) {
2018                    _logger.fine("SSO expire thread interval set to : " +
2019                                 expireTime.getValue());
2020                    int i = Integer.parseInt(expireTime.getValue());
2021                    sso.setReapInterval(i);
2022                }
2023
2024                vs.addValve(sso);
2025
2026            } catch (Exception JavaDoc e) {
2027                _logger.log(Level.WARNING, "webcontainer.ssobadconfig", e);
2028                _logger.log(Level.WARNING, "webcontainer.ssodisabled",
2029                            vs.getID());
2030            }
2031        }
2032    }
2033
2034
2035    /**
2036     * Configures the Remote Address Filter valve for the given virtual
2037     * server.
2038     *
2039     * This valve enforces request accpetance/denial based on the string
2040     * representation of the remote client's IP address.
2041     */

2042    public void configureRemoteAddressFilterValve(
2043            VirtualServer vs,
2044            com.sun.enterprise.config.serverbeans.VirtualServer vsBean) {
2045
2046        RemoteAddrValve remoteAddrValve = null;
2047
2048        if (vsBean == null) {
2049            return;
2050        }
2051
2052        ElementProperty allow = vsBean.getElementPropertyByName(
2053            "allowRemoteAddress");
2054        ElementProperty deny = vsBean.getElementPropertyByName(
2055            "denyRemoteAddress");
2056        if ((allow != null && allow.getValue() != null)
2057                || (deny != null && deny.getValue() != null)) {
2058            remoteAddrValve = new RemoteAddrValve();
2059        }
2060
2061        if (allow != null && allow.getValue() != null) {
2062            _logger.fine("Allowing access to " + vs.getID()+ " from " +
2063                         allow.getValue());
2064            remoteAddrValve.setAllow(allow.getValue());
2065        }
2066
2067        if (deny != null && deny.getValue() != null) {
2068            _logger.fine("Denying access to " + vs.getID()+ " from " +
2069                         deny.getValue());
2070            remoteAddrValve.setDeny(deny.getValue());
2071        }
2072
2073        if (remoteAddrValve != null) {
2074            // Remove existing RemoteAddrValve (if any), in case of a reconfig
2075
Valve[] valves = vs.getValves();
2076            for (int i=0; valves!=null && i<valves.length; i++) {
2077                if (valves[i] instanceof RemoteAddrValve) {
2078                    vs.removeValve(valves[i]);
2079                    break;
2080                }
2081            }
2082            vs.addValve(remoteAddrValve);
2083        }
2084    }
2085
2086
2087    /**
2088     * Configures the Remote Host Filter valve for the given virtual
2089     * server.
2090     *
2091     * This valve enforces request acceptance/denial based on the name of the
2092     * remote host from where the request originated.
2093     */

2094    public void configureRemoteHostFilterValve(
2095            VirtualServer vs,
2096            com.sun.enterprise.config.serverbeans.VirtualServer vsBean,
2097            HttpProtocol httpProtocol) {
2098
2099        RemoteHostValve remoteHostValve = null;
2100
2101        if (vsBean == null) {
2102            return;
2103        }
2104
2105        ElementProperty allow = vsBean.getElementPropertyByName(
2106            "allowRemoteHost");
2107        ElementProperty deny = vsBean.getElementPropertyByName(
2108            "denyRemoteHost");
2109        if ((allow != null && allow.getValue() != null)
2110                || (deny != null && deny.getValue() != null)) {
2111            remoteHostValve = new RemoteHostValve();
2112        }
2113
2114        if (allow != null && allow.getValue() != null) {
2115            _logger.fine("Allowing access to " + vs.getID()+ " from " +
2116                         allow.getValue());
2117            if (httpProtocol == null || !httpProtocol.isDnsLookupEnabled()) {
2118                _logger.log(Level.WARNING,
2119                            "webcontainer.allowRemoteHost.dnsLookupDisabled",
2120                            vs.getID());
2121            }
2122            remoteHostValve.setAllow(allow.getValue());
2123        }
2124
2125        if (deny != null && deny.getValue() != null) {
2126            _logger.fine("Denying access to " + vs.getID()+ " from " +
2127                         deny.getValue());
2128            if (httpProtocol == null || !httpProtocol.isDnsLookupEnabled()) {
2129                _logger.log(Level.WARNING,
2130                            "webcontainer.denyRemoteHost.dnsLookupDisabled",
2131                            vs.getID());
2132            }
2133            remoteHostValve.setDeny(deny.getValue());
2134        }
2135
2136        if (remoteHostValve != null) {
2137            // Remove existing RemoteHostValve (if any), in case of a reconfig
2138
Valve[] valves = vs.getValves();
2139            for (int i=0; valves!=null && i<valves.length; i++) {
2140                if (valves[i] instanceof RemoteHostValve) {
2141                    vs.removeValve(valves[i]);
2142                    break;
2143                }
2144            }
2145            vs.addValve(remoteHostValve);
2146        }
2147    }
2148
2149
2150    /**
2151     * Undeploy a web application.
2152     *
2153     * @param contextRoot the context's name to undeploy
2154     * @param appName the J2EE appname used at deployment time
2155     * @param virtualServers List of current virtual-server object.
2156     * @param wbd Web bundle descriptor, or null if dummy context
2157     * (see loadWebModule())
2158     */

2159    public void unloadWebModule(String JavaDoc contextRoot,
2160                                String JavaDoc appName,
2161                                String JavaDoc virtualServers,
2162                                WebBundleDescriptor wbd) {
2163        unloadWebModule(contextRoot, appName, virtualServers, wbd, false);
2164    }
2165
2166    /**
2167     * Undeploy a web application.
2168     *
2169     * @param contextRoot the context's name to undeploy
2170     * @param appName the J2EE appname used at deployment time
2171     * @param virtualServers List of current virtual-server object.
2172     * @param wbd Web bundle descriptor, or null if dummy context
2173     * (see loadWebModule())
2174     * @param dummy true if the web module to be undeployed is a dummy web
2175     * module, that is, a web module created off of a virtual server's
2176     * docroot
2177     */

2178    public void unloadWebModule(String JavaDoc contextRoot,
2179                                String JavaDoc appName,
2180                                String JavaDoc virtualServers,
2181                                WebBundleDescriptor wbd,
2182                                boolean dummy) {
2183        disableWSMonitoring(wbd);
2184
2185        if (_logger.isLoggable(Level.FINEST)) {
2186            _logger.finest("WebContainer.unloadWebModule(): contextRoot: "
2187                           + contextRoot + " appName:" + appName);
2188        }
2189
2190        //Hercules:add
2191
SessionPurgeUtil purgeUtil = new SessionPurgeUtil(_embedded);
2192        //end: Hercules:add
2193

2194        cleanSecurityContext(appName);
2195
2196        // unregister WebBundleDescriptor from the WebModulesManager
2197
if (webModulesManager != null) {
2198            webModulesManager.unregisterDescriptor(appName);
2199        }
2200        
2201        // tomcat contextRoot starts with "/"
2202
if (!contextRoot.equals("") && !contextRoot.startsWith("/") ) {
2203            contextRoot = "/" + contextRoot;
2204        } else if ("/".equals(contextRoot)) {
2205            // Make corresponding change as in WebModuleConfig.getContextPath()
2206
contextRoot = "";
2207        }
2208        
2209        Engine[] engines = _embedded.getEngines();
2210        List JavaDoc hostList = StringUtils.parseStringList(virtualServers, " ,");
2211        boolean unloadToAll = (hostList == null) || (hostList.size() == 0);
2212        boolean hasBeenUndeployed = false;
2213        Container[] hostArray = null;
2214        VirtualServer host = null;
2215        WebModule context = null;
2216        
2217        for (int j = 0; j < engines.length; j++) {
2218            hostArray = engines[j].findChildren();
2219            for (int i = 0; i < hostArray.length; i++) {
2220                host = (VirtualServer) hostArray[i];
2221
2222                /**
2223                 * Related to Bug: 4904290
2224                 * Do not unloadload module on ADMIN_VS
2225                 */

2226                if ( unloadToAll && host.getName().equalsIgnoreCase(ADMIN_VS)){
2227                    continue;
2228                }
2229
2230                if (unloadToAll
2231                        || hostList.contains(host.getName())
2232                        || verifyAlias(hostList,host)){
2233
2234                    context = (WebModule) host.findChild(contextRoot);
2235                    if (context != null) {
2236                        //Hercules:add
2237
if (_logger.isLoggable(Level.FINEST)) {
2238                            _logger.finest("about to call SessionPurgeUtil "
2239                                           + "for " + appName
2240                                           + " contextRoot: " + contextRoot);
2241                        }
2242                        purgeUtil.purgeSessionsForContext(context);
2243                        //end: Hercules:add
2244
disableMonitoring(context, host.getName());
2245                        host.removeChild(context);
2246                        try {
2247                            ((StandardContext)context).destroy();
2248                        } catch (Exception JavaDoc ex) {
2249                            _logger.log(Level.WARNING,
2250                                "[WebContainer] Context " + contextRoot
2251                                + " threw exception in destroy()", ex);
2252                        }
2253                        // START SJSAS 6330332
2254
Switch sw = Switch.getSwitch();
2255                        sw.removeDescriptorFor(context);
2256                        // END SJSAS 6330332
2257
if (_logger.isLoggable(Level.FINEST)) {
2258                            _logger.log(Level.FINEST,
2259                                "[WebContainer] Context " + contextRoot
2260                                + " undeployed from " + host);
2261                        }
2262                        hasBeenUndeployed = true;
2263                        ((StandardHost)host).fireContainerEvent(
2264                            Deployer.REMOVE_EVENT, context);
2265                        /*
2266                         * If the web module that has been unloaded
2267                         * contained any mappings for ad-hoc paths,
2268                         * those mappings must be preserved by registering an
2269                         * ad-hoc web module at the same context root
2270                         */

2271                        if (context.hasAdHocPaths()
2272                                || context.hasAdHocSubtrees()) {
2273                            WebModule wm = createAdHocWebModule(
2274                                            host,
2275                                            contextRoot,
2276                                            context.getJ2EEApplication());
2277                            wm.addAdHocPaths(context.getAdHocPaths());
2278                            wm.addAdHocSubtrees(context.getAdHocSubtrees());
2279                        }
2280
2281                        // START GlassFish 141
2282
if (!dummy) {
2283                            WebModuleConfig wmInfo =
2284                                host.createSystemDefaultWebModuleIfNecessary();
2285                            if (wmInfo != null) {
2286                                loadStandaloneWebModule(host, wmInfo);
2287                            }
2288                        }
2289                        // END GlassFish 141
2290
}
2291                }
2292            }
2293        }
2294        
2295
2296        if (!hasBeenUndeployed) {
2297            _logger.log(Level.SEVERE,
2298                "[WebContainer] Undeployment failed for context "
2299                + contextRoot);
2300        }
2301        
2302    }
2303    
2304    
2305    /**
2306     * Creates and configures a web module for each virtual server
2307     * that the web module is hosted under. If the web module has been
2308     * disabled by a call to disableWebModule, enable the module
2309     * instead of re-crearing new one.
2310     *
2311     * If no virtual servers are specified, then the web module is
2312     * enabled` on EVERY virtual server.
2313     */

2314    public void enableWebModule(WebModuleConfig wmInfo,
2315                                String JavaDoc j2eeApplication){
2316        String JavaDoc vsIDs = wmInfo.getVirtualServers();
2317        List JavaDoc vsList = StringUtils.parseStringList(vsIDs, " ,");
2318        boolean enabledToAll = (vsList == null) || (vsList.size() == 0);
2319
2320        Engine[] engines = _embedded.getEngines();
2321
2322        for (int j=0; j<engines.length; j++) {
2323            Container[] vsArray = engines[j].findChildren();
2324            for (int i = 0; i < vsArray.length; i++) {
2325                if (vsArray[i] instanceof VirtualServer) {
2326                    VirtualServer vs = (VirtualServer) vsArray[i];
2327
2328                    /*
2329                     * Fix for 4913636: If vsList is null and virtual server is
2330                     * equal to __asadmin, continue with next iteration
2331             * because we don't want to load user apps on __asadmin
2332                     */

2333                    if (vs.getID().equals(ADMIN_VS) && enabledToAll) {
2334                        continue;
2335                    }
2336
2337                    if ( enabledToAll
2338                            || vsList.contains(vs.getID())
2339                            || verifyAlias(vsList,vs)){
2340
2341                        loadWebModule(vs, wmInfo, j2eeApplication);
2342                    }
2343                }
2344            }
2345        }
2346    }
2347
2348
2349    /**
2350     * Disable a web application.
2351     * @param contextRoot the context's name to undeploy
2352     * @param appName the J2EE appname used at deployment time
2353     * @param virtualServers the list of current virtual-server object.
2354     */

2355    public void disableWebModule(String JavaDoc contextRoot,
2356                                 String JavaDoc appName,
2357                                 String JavaDoc virtualServers){
2358                                    
2359        // tomcat contextRoot starts with "/"
2360
if (!contextRoot.equals("") && !contextRoot.startsWith("/") ) {
2361            contextRoot = "/" + contextRoot;
2362        }
2363        
2364        Engine[] engines = _embedded.getEngines();
2365        List JavaDoc hostList = StringUtils.parseStringList(virtualServers, " ,");
2366        boolean disableToAll = (hostList == null) || (hostList.size() == 0);
2367        boolean hasBeenDisabled = false;
2368        Container[] hostArray = null;
2369        VirtualServer host = null;
2370        Context context = null;
2371        
2372        for (int j = 0; j < engines.length; j++) {
2373            hostArray = engines[j].findChildren();
2374            for (int i = 0; i < hostArray.length; i++) {
2375                host = (VirtualServer) hostArray[i];
2376
2377                /**
2378                 * Related to Bug: 4904290
2379                 * Do not unloadload module on ADMIN_VS
2380                 */

2381                if ( disableToAll
2382                        && host.getName().equalsIgnoreCase(ADMIN_VS)){
2383                    continue;
2384                }
2385
2386                if (disableToAll
2387                        || hostList.contains(host.getName())
2388                        || verifyAlias(hostList,host)){
2389
2390                    context = (Context) host.findChild(contextRoot);
2391                    if (context != null) {
2392                        context.setAvailable(false);
2393                        if (_logger.isLoggable(Level.FINEST)) {
2394                            _logger.log(Level.FINEST,
2395                                        "[WebContainer] Context "
2396                                        + contextRoot + " disabled from "
2397                                        + host);
2398                        }
2399                        hasBeenDisabled = true;
2400                    }
2401                }
2402            }
2403        }
2404        
2405        if (!hasBeenDisabled){
2406            _logger.log(Level.WARNING,
2407                        "[WebContainer] moduleDisabled fail for context "
2408                        + contextRoot);
2409        }
2410        
2411    }
2412
2413
2414    /**
2415     * Save the server-wide dynamic reloading settings for use when
2416     * configuring each web module.
2417     */

2418    private void getDynamicReloadingSettings(DasConfig appsBean) {
2419        if (appsBean != null) {
2420            _reloadingEnabled = appsBean.isDynamicReloadEnabled();
2421            String JavaDoc seconds = appsBean.getDynamicReloadPollIntervalInSeconds();
2422            if (seconds != null) {
2423                try {
2424                    _pollInterval = Integer.parseInt(seconds);
2425                } catch (NumberFormatException JavaDoc e) {
2426                }
2427            }
2428        }
2429    }
2430
2431    /**
2432     * Set the level for the web container logger and determine the
2433     * debug setting for Catalina's containers based on the iAS log
2434     * level.
2435     */

2436    private void setLogLevel(Level JavaDoc level) {
2437        _logLevel = level;
2438        _logger.setLevel(_logLevel);
2439
2440        // Determine the appropriate value for Catalina's debug level
2441
if (level.equals(Level.FINE))
2442            _debug = 1;
2443        else if (level.equals(Level.FINER))
2444            _debug = 2;
2445        else if (level.equals(Level.FINEST))
2446            _debug = 5;
2447        else
2448            _debug = 0;
2449    }
2450
2451
2452   /*
2453    * Initializes the web container log level from the domain.xml.
2454    *
2455    * @param logserviceBean The log service bean from which to retrieve the
2456    * web container log level
2457    */

2458    private void initLogLevel(LogService logserviceBean)
2459            throws ConfigException {
2460
2461        Level JavaDoc level = Level.SEVERE;
2462        setLogLevel(level);
2463
2464        if (logserviceBean != null) {
2465            try {
2466                level = Level.parse(logserviceBean.getModuleLogLevels().getRoot());
2467                setLogLevel(level);
2468            } catch (NullPointerException JavaDoc e) {
2469            } catch (IllegalArgumentException JavaDoc e) { }
2470        }
2471
2472        // If the <web-container> element in server.xml contains a
2473
// log-level setting then use that
2474
try {
2475            level = Level.parse(ServerBeansFactory.getWebContainerLogLevel(
2476                                                            _configContext));
2477            setLogLevel(level);
2478        } catch (NullPointerException JavaDoc e) {
2479            if (_debug > 0)
2480                _logger.finest("Defaulting <web-container> log-level");
2481        } catch (IllegalArgumentException JavaDoc e) {
2482        }
2483        if (_debug > 0) {
2484            _logger.fine("Web container log level: " + _logLevel);
2485        }
2486    }
2487
2488
2489   /*
2490    * Initializes the web container monitoring level from the domain.xml.
2491    *
2492    * @param monitoringBean The monitoring service bean from which to retrieve
2493    * the web container monitoring level
2494    */

2495    private void initMonitoringLevel(MonitoringService monitoringBean) {
2496
2497        monitoringLevel = MonitoringLevel.OFF; // default per DTD
2498

2499        if (monitoringBean != null) {
2500            ModuleMonitoringLevels levels =
2501                monitoringBean.getModuleMonitoringLevels();
2502            if (levels != null) {
2503                monitoringLevel = MonitoringLevel.instance(
2504                                                levels.getWebContainer());
2505            }
2506        }
2507    }
2508
2509
2510    /**
2511     * Checks if SSO is enabled for this virtual server.
2512     *
2513     * @param The virtual server id
2514     *
2515     * @return The value of the sso-enabled property for this virtual server
2516     */

2517    private boolean isSSOEnabled(com.sun.enterprise.config.serverbeans.VirtualServer vsBean)
2518    {
2519        ElementProperty ssoProperty =
2520            vsBean.getElementPropertyByName(SSO_ENABLED);
2521
2522        if (ssoProperty!=null && ssoProperty.getValue()!=null
2523             && !ConfigBean.toBoolean( ssoProperty.getValue())) {
2524           return false;
2525        }
2526        return true;
2527    }
2528
2529
2530    /**
2531     * Gets the VirtualServer config bean corresponding to the given id.
2532     *
2533     * @param vsID The virtual server id
2534     *
2535     * @return The VirtualServer config bean corresponding to the given id, or
2536     * null if no match is found
2537     */

2538    private com.sun.enterprise.config.serverbeans.VirtualServer findVirtualServerBean(String JavaDoc vsID) {
2539
2540        HttpService httpService = null;
2541        try {
2542            httpService = ServerBeansFactory.getHttpServiceBean(_configContext);
2543        } catch (ConfigException e) {
2544            String JavaDoc msg = _rb.getString("webcontainer.httpConfigError");
2545            _logger.log(Level.SEVERE, msg, e);
2546        }
2547
2548        com.sun.enterprise.config.serverbeans.VirtualServer[] vses
2549            = httpService.getVirtualServer();
2550        for (int i=0; vses!=null && i<vses.length; i++) {
2551            if (vsID.equals(vses[i].getId())) {
2552                return vses[i];
2553            }
2554        }
2555
2556        return null;
2557    }
2558
2559    
2560    /**
2561     * Get the lifecycle listeners associated with this lifecycle. If this
2562     * Lifecycle has no listeners registered, a zero-length array is returned.
2563     */

2564    public LifecycleListener[] findLifecycleListeners() {
2565       return new LifecycleListener[0];
2566    }
2567    
2568    
2569    /**
2570     * Clean security policy generated at deployment time.
2571     * NOTE: This routine calls destroy on the WebSecurityManagers,
2572     * but that does not cause deletion of the underlying policy (files).
2573     * The underlying policy is deleted when removePolicy
2574     * (in AppDeployerBase and WebModuleDeployer) is called.
2575     * @param appName the app name
2576     */

2577    private void cleanSecurityContext(String JavaDoc appName) {
2578    String JavaDoc cIDs[] = webSecurityManagerFactory.getContextIdsOfApp(appName);
2579
2580    for (int i=0; cIDs != null && i <cIDs.length; i++) {
2581        WebSecurityManager wsm
2582        = webSecurityManagerFactory.getWebSecurityManager(cIDs[i]);
2583
2584        _logger.log(Level.FINE,"[JACC]: Removing WebSecurityManager: "
2585                + cIDs[i]);
2586
2587        if (wsm != null) {
2588        try {
2589            wsm.destroy();
2590        } catch (javax.security.jacc.PolicyContextException JavaDoc pce){
2591            // log it and continue
2592
_logger.log(Level.WARNING,
2593                            "Unable to destroy WebSecurityManager",
2594                            pce);
2595        }
2596        webSecurityManagerFactory.removeWebSecurityManager(cIDs[i]);
2597        }
2598    }
2599    }
2600           
2601    /**
2602     * Virtual servers are maintained in the reference contained
2603     * in Server element. First, we need to find the server
2604     * and then get the virtual server from the correct reference
2605     *
2606     * @param appName Name of the app to get vs
2607     * @param configCtx config context to use to obtain virtual servers. If
2608     * this parameter is null, config context cached at startup time will
2609     * be used.
2610     *
2611     * @return virtual servers as a string (separated by space or comma)
2612     */

2613    private String JavaDoc getVirtualServers(String JavaDoc appName, ConfigContext configCtx) {
2614        if (configCtx == null) {
2615            configCtx = _configContext;
2616        }
2617        String JavaDoc ret = null;
2618        try {
2619            ret = ServerBeansFactory.getVirtualServersByAppName(configCtx,
2620                                                                appName);
2621        } catch (ConfigException ce) {
2622            _logger.log(Level.WARNING,
2623                        "No virtual servers defined for " + appName,
2624                        ce);
2625        }
2626        return ret;
2627    }
2628
2629    /**
2630     * Adds the given mime mappings to those of the specified context, unless
2631     * they're already present in the context (that is, the mime mappings of
2632     * the specified context, which correspond to those in default-web.xml,
2633     * can't be overridden).
2634     *
2635     * @param ctx The StandardContext to whose mime mappings to add
2636     * @param mimeMap The mime mappings to be added
2637     */

2638    private void addMimeMappings(StandardContext ctx, MimeMap mimeMap) {
2639        if (mimeMap == null) {
2640            return;
2641        }
2642
2643        for (Iterator JavaDoc itr = mimeMap.getExtensions(); itr.hasNext(); ) {
2644            String JavaDoc extension = (String JavaDoc) itr.next();
2645            if (ctx.findMimeMapping(extension) == null) {
2646                ctx.addMimeMapping(extension, mimeMap.getType(extension));
2647            }
2648        }
2649    }
2650    
2651    /**
2652     * Enables monitoring of web service endpoints in for all webmodules.
2653     */

2654    private void enableAllWSEndpoints() {
2655
2656        Applications appsBean = null;
2657        try {
2658            appsBean = ServerBeansFactory.getApplicationsBean(_configContext);
2659        } catch (ConfigException e) {
2660            String JavaDoc msg = _rb.getString("webcontainer.appsConfigError");
2661            _logger.log(Level.SEVERE, msg, e);
2662        }
2663
2664        if (appsBean != null) {
2665            J2eeApplication[] j2eeAppBeans = appsBean.getJ2eeApplication();
2666            if (j2eeAppBeans != null) {
2667                for (int i = 0; i < j2eeAppBeans.length; i++) {
2668                    //Begin EE: 4927099 - load only associated applications
2669
if ( isReferenced(j2eeAppBeans[i].getName()) ) {
2670                        enableWSMonitoring(j2eeAppBeans[i].getName());
2671                    }
2672                    //End EE: 4927099 - load only associated applications
2673
}
2674            }
2675        }
2676    }
2677 
2678     /**
2679      * Disables monitoring of web service endpoints in a webmodule.
2680      *
2681      * @param wbd WebBundleDescriptor of the web module
2682      *
2683      * @return boolean true, if web service mbeans were unloaded successfully
2684      */

2685     private boolean disableWSMonitoring(WebBundleDescriptor wbd) {
2686
2687       boolean result = true;
2688
2689            try {
2690            Switch.getSwitch().getManagementObjectManager().
2691                deleteWSEndpointMBeans(wbd, instance.getName());
2692            } catch (Exception JavaDoc e) {
2693                e.printStackTrace();
2694                return false;
2695            }
2696            return true;
2697    }
2698
2699    /**
2700     * Enables monitoring of web service endpoints in a webmodule.
2701     *
2702     * @param id ID of the application
2703     *
2704     * @return boolean true, if web service mbeans were intialized successfully
2705     */

2706    private boolean enableWSMonitoring(String JavaDoc id) {
2707
2708       boolean result = true;
2709
2710       ApplicationRegistry registry = ApplicationRegistry.getInstance();
2711            ClassLoader JavaDoc appLoader = registry.getClassLoaderForApplication(id);
2712            if (appLoader != null) {
2713                Application appDesc = registry.getApplication(appLoader);
2714             
2715                // Check to see if this app had deployed successfully (4663247)
2716
if(appDesc == null){
2717                    Object JavaDoc[] params = { id };
2718                    _logger.log(Level.SEVERE, "webcontainer.notLoaded",
2719                                params);
2720                } else {
2721                    //end Hercules: add
2722
String JavaDoc j2eeApplication = appDesc.getRegistrationName();
2723                    Set JavaDoc wbds = appDesc.getWebBundleDescriptors();
2724                    WebBundleDescriptor wbd = null;
2725                    for (Iterator JavaDoc itr = wbds.iterator(); itr.hasNext(); ) {
2726                        wbd = (WebBundleDescriptor) itr.next();
2727
2728                        try {
2729                            Switch.getSwitch().getManagementObjectManager().
2730                            createWSEndpointMBeans(wbd, instance.getName());
2731                        } catch (Exception JavaDoc e) {
2732                            e.printStackTrace();
2733                            return false;
2734                        }
2735                    }
2736                }
2737            }
2738        return true;
2739    }
2740
2741    void enableWSMonitoring(WebBundleDescriptor wbd, String JavaDoc serverName) {
2742         try {
2743             Switch.getSwitch().getManagementObjectManager().
2744             createWSEndpointMBeans(wbd, serverName);
2745         } catch (Exception JavaDoc e) {
2746             e.printStackTrace();
2747         }
2748     }
2749
2750    /**
2751     * Enables monitoring on the Servlets in a webmodule.
2752     *
2753     * @param ctx Web module to be monitored
2754     * @param vsId The engine that is currently loading the webmodule
2755     */

2756    void enableMonitoring(WebModule ctx, String JavaDoc vsId) {
2757
2758        if (!ctx.hasWebXml()) {
2759            // dummy web module
2760
return;
2761        }
2762
2763        String JavaDoc j2eeServer = _serverContext.getInstanceName();
2764
2765        // Register web module stats
2766
registerWebModuleStats(ctx.getJ2EEApplication(), j2eeServer, vsId,
2767                               ctx, null);
2768
2769        // Register stats for each of the web module's servlets
2770
Container[] children = ctx.findChildren();
2771        if (children != null) {
2772            for (int i = 0; i < children.length; i++) {
2773                registerServletStats(ctx.getJ2EEApplication(), j2eeServer,
2774                                     ctx.getModuleName(), vsId, ctx.getPath(),
2775                                     children[i].getName(), null);
2776            }
2777        }
2778    }
2779
2780    
2781    /**
2782     * Disables monitoring on the given web module.
2783     */

2784    protected void disableMonitoring(WebModule ctx, String JavaDoc vsId) {
2785
2786        if (!ctx.hasWebXml()) {
2787            // dummy web module
2788
return;
2789        }
2790
2791        /*
2792         * Standalone webmodules are loaded with the application name set to
2793         * the string "null"
2794         */

2795        String JavaDoc appName = ctx.getJ2EEApplication();
2796        if ("null".equalsIgnoreCase(appName)) {
2797            appName = null;
2798        }
2799
2800        // Unregister stats for each of the web module's servlets
2801
Container[] children = ctx.findChildren();
2802        if (children != null) {
2803            for (int k = 0; k < children.length; k++) {
2804                unregisterServletStats(appName, ctx.getModuleName(),
2805                                       ctx.getPath(), vsId,
2806                                       children[k].getName());
2807            }
2808        }
2809        // Unregister web module stats
2810
unregisterWebModuleStats(appName, ctx.getModuleName(),
2811                                 ctx.getPath(), vsId);
2812
2813    }
2814
2815    /*
2816     * Excludes, from TLD scanning, any JARs on the classpath and higher up in
2817     * the classloader delegation chain that are known not to contain any TLDs
2818     * or TLD listeners.
2819     */

2820    private void setNoTldScan() {
2821        boolean first = true;
2822        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
2823        StringBuffer JavaDoc sbListener = new StringBuffer JavaDoc();
2824        List JavaDoc tldJars = null;
2825        List JavaDoc tldListeners = null;
2826        
2827        String JavaDoc prop = System.getProperty("com.sun.enterprise.taglibs");
2828        if (prop != null) {
2829            tldJars = StringUtils.parseStringList(prop, ",");
2830        }
2831        
2832        prop = System.getProperty("com.sun.enterprise.taglisteners");
2833        if (prop != null) {
2834            tldListeners = StringUtils.parseStringList(prop, ",");
2835        }
2836        
2837        // Check to see if we need to scan the parent classloader when
2838
// searching for TLD listener. JSF application mandate the search, as
2839
// well as shared TLD added to the
2840
// property com.sun.enterprise.taglisteners
2841
if ( tldListeners != null ){
2842            int size = tldListeners.size();
2843            if ( size > 0 ){
2844                // By default, domain.xml contains 1 elements.
2845
if ( !tldListeners.contains("jsf-impl.jar") || (size > 1))
2846                    TldConfig.setScanParentTldListener(true);
2847            }
2848        }
2849
2850        ClassLoader JavaDoc loader = getClass().getClassLoader();
2851        while (loader != null) {
2852            if (loader instanceof URLClassLoader JavaDoc) {
2853                URL JavaDoc[] urls = ((URLClassLoader JavaDoc) loader).getURLs();
2854                for (int i=0; i<urls.length; i++) {
2855                    String JavaDoc url = urls[i].toString();
2856                    int index = url.lastIndexOf('/');
2857                    if (index != -1) {
2858                        url = url.substring(index+1);
2859                    }
2860                    if (url != null && url.endsWith(".jar")
2861                && (tldJars == null || !tldJars.contains(url))
2862                            
2863                            ) {
2864                        if (first) {
2865                            sb.append(url);
2866                            first = false;
2867                        } else {
2868                            sb.append(',');
2869                            sb.append(url);
2870                        }
2871                    }
2872                    
2873                    if (url != null && url.endsWith(".jar")
2874                && (tldListeners == null || !tldListeners.contains(url))
2875                            
2876                            ) {
2877                        if (first) {
2878                            sbListener.append(url);
2879                            first = false;
2880                        } else {
2881                            sbListener.append(',');
2882                            sbListener.append(url);
2883                        }
2884                    }
2885                }
2886            }
2887            loader = loader.getParent();
2888        }
2889
2890        if (sbListener.length() > 0) {
2891            TldConfig.setNoTldListeners(sbListener.toString());
2892        }
2893        
2894        if (sb.length() > 0) {
2895            TldLocationsCache.setNoTldJars(sb.toString());
2896        }
2897    }
2898    
2899
2900    // Begin EE: 4927099 load only associated applications
2901
/**
2902     * Returns true if the names application is referenced by this server.
2903     *
2904     * @param appName name of the application id
2905     * @return true if the names application is referenced by this server
2906     */

2907    private boolean isReferenced(String JavaDoc appName) {
2908
2909        Servers servers = domain.getServers();
2910        Server server = servers.getServerByName(
2911                                _serverContext.getInstanceName());
2912
2913        ApplicationRef ref = server.getApplicationRefByRef(appName);
2914        return (ref == null) ? false : true;
2915    }
2916    // End EE: 4927099 load only associated applications
2917

2918
2919    /*
2920     * Creates a ServletStats instance for the servlet with the given
2921     * <code>servletName</code> and registers it with the monitoring registry.
2922     *
2923     * @param j2eeApplication String representing the J2EE Application to which
2924     * the web module belongs, or null if the web module is stand-alone
2925     * @param j2eeServer The server instance name
2926     * @param webModuleName The name of the web module to which the servlet
2927     * belongs
2928     * @param vsId The id of the virtual server on which the web module has
2929     * been deployed
2930     * @param contextRoot Context root at which web module has been deployed
2931     * @param servletName The servlet name
2932     * @param listener The listener for monitoring level changes
2933     */

2934    private void registerServletStats(String JavaDoc j2eeApplication,
2935                                      String JavaDoc j2eeServer,
2936                                      String JavaDoc webModuleName,
2937                                      String JavaDoc vsId,
2938                                      String JavaDoc contextRoot,
2939                                      String JavaDoc servletName,
2940                                      MonitoringLevelListener listener) {
2941
2942        PwcServletStats pwcServletStats = new PwcServletStatsImpl(
2943                                    _serverContext.getDefaultDomainName(),
2944                                    vsId, contextRoot, servletName,
2945                                    j2eeApplication, j2eeServer);
2946        ServletStats servletStats = new ServletStatsImpl(pwcServletStats);
2947
2948
2949        MonitoringRegistry monitoringRegistry =
2950                _serverContext.getMonitoringRegistry();
2951
2952        /*
2953         * Standalone webmodules are loaded with the application name set to
2954         * the string "null"
2955         */

2956        String JavaDoc app = ("null".equalsIgnoreCase(j2eeApplication) ?
2957                        null : j2eeApplication);
2958        try {
2959            monitoringRegistry.registerServletStats(servletStats,
2960                                                    app,
2961                                                    webModuleName,
2962                                                    contextRoot,
2963                                                    vsId,
2964                                                    servletName,
2965                                                    listener);
2966        } catch(Exception JavaDoc e) {
2967            _logger.log(Level.WARNING,
2968                        "Exception during registration of servletstats",
2969                        e);
2970        }
2971    }
2972
2973
2974    /*
2975     * Removes the ServletStats instance associated with the servlet with the
2976     * given <code>servletName</code> from the monitoring registry.
2977     *
2978     * @param j2eeApplication String representing the J2EE Application to which
2979     * the web module belongs, or null if the web module is stand-alone
2980     * @param webModuleName The name of the web module to which the servlet
2981     * belongs
2982     * @param contextRoot Context root at which web module has been deployed
2983     * @param vsId The id of the virtual server on which the web module has
2984     * been deployed
2985     * @param servletName The servlet name
2986     */

2987    private void unregisterServletStats(String JavaDoc j2eeApplication,
2988                                        String JavaDoc webModuleName,
2989                                        String JavaDoc contextRoot,
2990                                        String JavaDoc vsId,
2991                                        String JavaDoc servletName) {
2992
2993        MonitoringRegistry monitoringRegistry =
2994                _serverContext.getMonitoringRegistry();
2995
2996        try {
2997            monitoringRegistry.unregisterServletStats(j2eeApplication,
2998                                                      webModuleName,
2999                                                      contextRoot,
3000                                                      vsId,
3001                                                      servletName);
3002        } catch (Exception JavaDoc e) {
3003            _logger.log(Level.WARNING,
3004                        "Exception during unregistration of servletstats",
3005                        e);
3006        }
3007    }
3008
3009
3010    /*
3011     * Creates a WebModuleStats instance for the given web module and
3012     * registers it with the monitoring registry.
3013     *
3014     * @param j2eeApplication String representing the J2EE Application to which
3015     * the web module belongs, or null if the web module is stand-alone
3016     * @param j2eeServer The server instance name
3017     * @param vsId The id of the virtual server on which the web module has
3018     * been deployed
3019     * @param ctx The web module
3020     * @param listener The listener for monitoring level changes
3021     *
3022     * @return The WebModuleStats that was registered with the monitoring
3023     * registry
3024     */

3025    private WebModuleStats registerWebModuleStats(
3026                                        String JavaDoc j2eeApplication,
3027                                        String JavaDoc j2eeServer,
3028                                        String JavaDoc vsId,
3029                                        WebModule ctx,
3030                                        MonitoringLevelListener listener) {
3031
3032        WebContainerFeatureFactory webFeatureFac =
3033            _serverContext.getPluggableFeatureFactory().getWebContainerFeatureFactory();
3034        WebModuleStatsImpl webStats = (WebModuleStatsImpl)
3035            webFeatureFac.getWebModuleStats();
3036        PwcWebModuleStatsImpl pwcWebStats = new PwcWebModuleStatsImpl(
3037                                        ctx.getObjectName(),
3038                                        ctx.getPath(),
3039                                        _serverContext.getDefaultDomainName(),
3040                                        vsId,
3041                                        j2eeApplication,
3042                                        j2eeServer);
3043        webStats.setPwcWebModuleStats(pwcWebStats);
3044        webStats.setSessionManager(ctx.getManager());
3045
3046        MonitoringRegistry monitoringRegistry =
3047                _serverContext.getMonitoringRegistry();
3048
3049        /*
3050         * Standalone webmodules are loaded with the application name set to
3051         * the string "null"
3052         */

3053        String JavaDoc app = ("null".equalsIgnoreCase(j2eeApplication) ?
3054                        null : j2eeApplication);
3055        try {
3056            monitoringRegistry.registerWebModuleStats(webStats,
3057                                                      app,
3058                                                      ctx.getModuleName(),
3059                                                      ctx.getPath(),
3060                                                      vsId,
3061                                                      listener);
3062        } catch (Exception JavaDoc e) {
3063            _logger.log(Level.WARNING,
3064                        "Fail to register WebModuleStats for "
3065                        + ctx.getModuleName() + " deployed on " + vsId, e);
3066        }
3067
3068        return webStats;
3069    }
3070
3071
3072    /*
3073     * Removes the WebModuleStats instance associated with the web module with
3074     * the given <code>webModuleName</code> from the monitoring registry.
3075     *
3076     * @param j2eeApplication String representing the J2EE Application to which
3077     * the web module belongs, or null if the web module is stand-alone
3078     * @param webModuleName The web module name
3079     * @param contextRoot Context root at which web module has been deployed
3080     * @param vsId The id of the virtual server on which the web module has
3081     * been deployed
3082     */

3083    private void unregisterWebModuleStats(String JavaDoc j2eeApplication,
3084                                          String JavaDoc webModuleName,
3085                                          String JavaDoc contextRoot,
3086                                          String JavaDoc vsId) {
3087
3088        MonitoringRegistry monitoringRegistry =
3089                _serverContext.getMonitoringRegistry();
3090
3091        try {
3092            monitoringRegistry.unregisterWebModuleStats(j2eeApplication,
3093                                                        webModuleName,
3094                                                        contextRoot,
3095                                                        vsId);
3096        } catch (Exception JavaDoc e) {
3097            _logger.log(Level.WARNING,
3098                        "Fail to unregister WebModuleStats for "
3099                        + webModuleName + " deployed on " + vsId, e);
3100        }
3101    }
3102    
3103    /**
3104     * Invoked when a reference is created from a
3105     * server instance (or cluster) to a particular module.
3106     *
3107     * @throws AdminEventListenerException when the listener is unable to
3108     * process the event.
3109     */

3110    public void moduleReferenceAdded(ModuleDeployEvent event)
3111    { // throws AdminEventListenerException {
3112

3113    }
3114
3115    /**
3116     * Invoked when a reference is removed from a
3117     * server instance (or cluster) to a particular module.
3118     *
3119     * @throws AdminEventListenerException when the listener is unable to
3120     * process the event.
3121     */

3122    public void moduleReferenceRemoved(ModuleDeployEvent event)
3123    { // throws AdminEventListenerException {
3124

3125    }
3126    
3127    
3128    /**
3129     * Invoked when an application reference is created from a
3130     * server instance (or cluster) to a particular application.
3131     *
3132     * @throws AdminEventListenerException when the listener is unable to
3133     * process the event.
3134     */

3135    public void applicationReferenceAdded(ApplicationDeployEvent event)
3136    {// throws AdminEventListenerException {
3137

3138    }
3139
3140    /**
3141     * Invoked when a reference is removed from a
3142     * server instance (or cluster) to a particular application.
3143     *
3144     * @throws AdminEventListenerException when the listener is unable to
3145     * process the event.
3146     */

3147    public void applicationReferenceRemoved(ApplicationDeployEvent event)
3148    { // throws AdminEventListenerException {
3149
}
3150    
3151    /**
3152     * Return the current <code>WebContainer</code> child instance.
3153     */

3154    public static WebContainer getInstance(){
3155        return webContainer;
3156    }
3157    
3158    /**
3159     * Return the parent/top-level container in _embedded for virtual
3160     * servers.
3161     */

3162    public Engine[] getEngines() {
3163        return _embedded.getEngines();
3164    }
3165
3166
3167    /**
3168     * Registers the given ad-hoc path at the given context root.
3169     *
3170     * @param path The ad-hoc path to register
3171     * @param ctxtRoot The context root at which to register
3172     * @param appName The name of the application with which the ad-hoc path is
3173     * associated
3174     * @param servletInfo Info about the ad-hoc servlet that will service
3175     * requests on the given path
3176     */

3177    public void registerAdHocPath(String JavaDoc path,
3178                                  String JavaDoc ctxtRoot,
3179                                  String JavaDoc appName,
3180                                  AdHocServletInfo servletInfo) {
3181
3182        registerAdHocPathAndSubtree(path, null, ctxtRoot, appName, servletInfo);
3183    }
3184
3185
3186    /**
3187     * Registers the given ad-hoc path and subtree at the given context root.
3188     *
3189     * @param path The ad-hoc path to register
3190     * @param subtree The ad-hoc subtree path to register
3191     * @param ctxtRoot The context root at which to register
3192     * @param appName The name of the application with which the ad-hoc path
3193     * and subtree are associated
3194     * @param servletInfo Info about the ad-hoc servlet that will service
3195     * requests on the given ad-hoc path and subtree
3196     */

3197    public void registerAdHocPathAndSubtree(String JavaDoc path,
3198                                            String JavaDoc subtree,
3199                                            String JavaDoc ctxtRoot,
3200                                            String JavaDoc appName,
3201                                            AdHocServletInfo servletInfo) {
3202        WebModule wm = null;
3203
3204        Engine[] engines = _embedded.getEngines();
3205        for (int j=0; j<engines.length; j++) {
3206
3207            Container[] vsList = engines[j].findChildren();
3208            for (int i = 0; i < vsList.length; i++) {
3209
3210                VirtualServer vs = (VirtualServer)vsList[i];
3211                if (vs.getName().equalsIgnoreCase(ADMIN_VS)) {
3212                    // Do not deploy on admin vs
3213
continue;
3214                }
3215
3216                wm = (WebModule) vs.findChild(ctxtRoot);
3217                if (wm == null) {
3218                    wm = createAdHocWebModule(vs, ctxtRoot, appName);
3219                }
3220                wm.addAdHocPathAndSubtree(path, subtree, servletInfo);
3221            }
3222        }
3223    }
3224
3225
3226    /**
3227     * Unregisters the given ad-hoc path from the given context root.
3228     *
3229     * @param path The ad-hoc path to unregister
3230     * @param ctxtRoot The context root from which to unregister
3231     */

3232    public void unregisterAdHocPath(String JavaDoc path, String JavaDoc ctxtRoot) {
3233        unregisterAdHocPathAndSubtree(path, null, ctxtRoot);
3234    }
3235
3236
3237    /**
3238     * Unregisters the given ad-hoc path and subtree from the given context
3239     * root.
3240     *
3241     * @param path The ad-hoc path to unregister
3242     * @param subtree The ad-hoc subtree to unregister
3243     * @param ctxtRoot The context root from which to unregister
3244     */

3245    public void unregisterAdHocPathAndSubtree(String JavaDoc path,
3246                                              String JavaDoc subtree,
3247                                              String JavaDoc ctxtRoot) {
3248
3249        WebModule wm = null;
3250
3251        Engine[] engines = _embedded.getEngines();
3252        for (int j=0; j<engines.length; j++) {
3253
3254            Container[] vsList = engines[j].findChildren();
3255            for (int i = 0; i < vsList.length; i++) {
3256
3257                VirtualServer vs = (VirtualServer) vsList[i];
3258                if (vs.getName().equalsIgnoreCase(ADMIN_VS)) {
3259                    // Do not undeploy from admin vs, because we never
3260
// deployed onto it
3261
continue;
3262                }
3263
3264                wm = (WebModule) vs.findChild(ctxtRoot);
3265                if (wm == null) {
3266                    continue;
3267                }
3268
3269                /*
3270                 * If the web module was created by the container for the
3271                 * sole purpose of mapping ad-hoc paths and subtrees,
3272                 * and does no longer contain any ad-hoc paths or subtrees,
3273                 * remove the web module.
3274                 */

3275                wm.removeAdHocPath(path);
3276                wm.removeAdHocSubtree(subtree);
3277                if ((wm instanceof AdHocWebModule)
3278                        && !wm.hasAdHocPaths()
3279                        && !wm.hasAdHocSubtrees()) {
3280                    vs.removeChild(wm);
3281                    try {
3282                        wm.destroy();
3283                    } catch (Exception JavaDoc ex) {
3284                        _logger.log(Level.WARNING,
3285                            "[WebContainer] Context " + wm.getPath()
3286                            + " threw exception in destroy()", ex);
3287                    }
3288                }
3289            }
3290        }
3291    }
3292
3293
3294    /*
3295     * Creates an ad-hoc web module and registers it on the given virtual
3296     * server at the given context root.
3297     *
3298     * @param vs The virtual server on which to add the ad-hoc web module
3299     * @param ctxtRoot The context root at which to register the ad-hoc
3300     * web module
3301     * @param appName The name of the application to which the ad-hoc module
3302     * being generated belongs
3303     *
3304     * @return The newly created ad-hoc web module
3305     */

3306    private WebModule createAdHocWebModule(VirtualServer vs,
3307                                           String JavaDoc ctxtRoot,
3308                                           String JavaDoc appName) {
3309
3310        AdHocWebModule wm = new AdHocWebModule(this);
3311
3312        wm.restrictedSetPipeline(new WebPipeline(wm));
3313
3314        // The Parent ClassLoader of the AdhocWebModule was null
3315
// [System ClassLoader]. With the new hierarchy, the thread context
3316
// classloader needs to be set.
3317
if (Boolean.getBoolean(com.sun.enterprise.server.PELaunch.USE_NEW_CLASSLOADER_PROPERTY)) {
3318            wm.setParentClassLoader(
3319                Thread.currentThread().getContextClassLoader());
3320        }
3321
3322        wm.setContextRoot(ctxtRoot);
3323        wm.setJ2EEApplication(appName);
3324        wm.setName(ctxtRoot);
3325        wm.setDocBase(vs.getAppBase());
3326        wm.setEngineName(vs.getParent().getName());
3327
3328        String JavaDoc domain = _serverContext.getDefaultDomainName();
3329        wm.setDomain(domain);
3330  
3331        String JavaDoc j2eeServer = _serverContext.getInstanceName();
3332        wm.setJ2EEServer(j2eeServer);
3333
3334        String JavaDoc server = domain + ":j2eeType=J2EEServer,name=" + j2eeServer;
3335        wm.setServer(server);
3336
3337        wm.setCrossContext(true);
3338        wm.setJavaVMs(J2EEModuleUtil.getjavaVMs());
3339
3340        vs.addChild(wm);
3341
3342        return wm;
3343    }
3344
3345
3346    /**
3347     * Adds all libraries specified via the --libraries deployment option to
3348     * the given loader associated with the given web context.
3349     *
3350     * @param loader The loader to configure
3351     * @param ctx The loader's associated web context
3352     */

3353    private void addLibs(Loader JavaDoc loader, WebModule ctx) {
3354 
3355        String JavaDoc list = ASClassLoaderUtil.getLibrariesForWebModule(ctx.getID());
3356        if (list == null) {
3357            return;
3358        }
3359        String JavaDoc[] libs = list.split(",");
3360        if (libs == null) {
3361            return;
3362        }
3363
3364        File JavaDoc libDir = new File JavaDoc(instance.getLibPath());
3365        String JavaDoc libDirPath = libDir.getAbsolutePath();
3366        String JavaDoc appLibsPrefix = libDirPath + File.separator + "applibs"
3367            + File.separator;
3368
3369        for (int i=0; i<libs.length; i++) {
3370            File JavaDoc file = new File JavaDoc(libs[i]);
3371            if (file.isAbsolute()) {
3372                loader.addRepository("file:" + file.getAbsolutePath());
3373            } else {
3374                loader.addRepository("file:" + appLibsPrefix + libs[i]);
3375            }
3376        }
3377    }
3378
3379
3380    /**
3381     * Configures the given classloader with its attributes specified in
3382     * sun-web.xml.
3383     *
3384     * @param loader The classloader to configure
3385     * @param clBean The class-loader info from sun-web.xml
3386     * @param ctx The classloader's associated web module
3387     */

3388    private void configureLoaderAttributes(
3389            Loader JavaDoc loader,
3390            com.sun.enterprise.deployment.runtime.web.ClassLoader clBean,
3391            WebModule ctx) {
3392
3393        String JavaDoc value = null;
3394
3395        value = clBean.getAttributeValue(
3396            com.sun.enterprise.deployment.runtime.web.ClassLoader.DELEGATE);
3397
3398        /*
3399         * The DOL will *always* return a value: If 'delegate' has not been
3400         * configured in sun-web.xml, its default value will be returned,
3401         * which is FALSE in the case of sun-web-app_2_2-0.dtd and
3402         * sun-web-app_2_3-0.dtd, and TRUE in the case of
3403         * sun-web-app_2_4-0.dtd.
3404         */

3405        boolean delegate = ConfigBean.toBoolean(value);
3406        loader.setDelegate(delegate);
3407
3408        // Get any extra paths to be added to the class path of this
3409
// class loader
3410
List JavaDoc pathElements = null;
3411        value = clBean.getAttributeValue(
3412            com.sun.enterprise.deployment.runtime.web.ClassLoader.EXTRA_CLASS_PATH);
3413        if (value != null) {
3414            pathElements = StringUtils.parseStringList(value, ";:");
3415            if (pathElements != null) {
3416                ListIterator JavaDoc iter = pathElements.listIterator();
3417                while (iter.hasNext()) {
3418                    String JavaDoc path = (String JavaDoc) iter.next();
3419                    if (_logger.isLoggable(Level.FINE)) {
3420                        _logger.fine("WebModule[" + ctx.getPath()
3421                                     + "]: Adding " + path + " to the classpath");
3422                    }
3423
3424                    try {
3425                        URL JavaDoc url = new File JavaDoc(path).toURI().toURL();
3426                        loader.addRepository(url.toString());
3427                    } catch (MalformedURLException JavaDoc e) {
3428                        String JavaDoc msg = _rb.getString("webcontainer.classpathError");
3429                        Object JavaDoc[] params = { path };
3430                        msg = MessageFormat.format(msg, params);
3431                        _logger.log(Level.SEVERE, msg, e);
3432                    }
3433                }
3434            }
3435        }
3436
3437        value = clBean.getAttributeValue(
3438            com.sun.enterprise.deployment.runtime.web.ClassLoader.DYNAMIC_RELOAD_INTERVAL);
3439        if (value != null) {
3440            // Log warning if dynamic-reload-interval is specified
3441
// in sun-web.xml since it is not supported
3442
_logger.log(Level.WARNING,
3443                        "webcontainer.dynamicReloadInterval");
3444        }
3445
3446        _logger.fine("WebModule[" + ctx.getPath()
3447             + "]: Setting delegate to " + delegate
3448             + ", extra-class-path to " + pathElements);
3449    }
3450
3451
3452    /**
3453     * Configures the given classloader with its properties specified in
3454     * sun-web.xml.
3455     *
3456     * @param loader The classloader to configure
3457     * @param clBean The class-loader info from sun-web.xml
3458     */

3459    private void configureLoaderProperties(
3460            Loader JavaDoc loader,
3461            com.sun.enterprise.deployment.runtime.web.ClassLoader clBean) {
3462
3463        String JavaDoc name = null;
3464        String JavaDoc value = null;
3465
3466        WebProperty[] props = clBean.getWebProperty();
3467        if (props == null || props.length == 0) {
3468            return;
3469        }
3470
3471        for (int i = 0; i < props.length; i++) {
3472
3473            name = props[i].getAttributeValue(WebProperty.NAME);
3474            value = props[i].getAttributeValue(WebProperty.VALUE);
3475
3476            if (name == null || value == null) {
3477                throw new IllegalArgumentException JavaDoc(
3478                    _rb.getString("webcontainer.nullWebProperty"));
3479            }
3480
3481            if (name.equalsIgnoreCase("ignoreHiddenJarFiles")) {
3482                loader.setIgnoreHiddenJarFiles(ConfigBean.toBoolean(value));
3483            } else {
3484                Object JavaDoc[] params = { name, value };
3485                _logger.log(Level.WARNING,
3486                            "webcontainer.invalidProperty",
3487                            params);
3488            }
3489        }
3490    }
3491
3492
3493    /**
3494     * Configures the given virtual server with its redirect properties.
3495     *
3496     * @param vs The virtual server to configure
3497     * @param vsBean
3498     */

3499    private void configureRedirect(
3500        VirtualServer vs,
3501        com.sun.enterprise.config.serverbeans.VirtualServer vsBean) {
3502
3503        if (vsBean == null) {
3504            return;
3505        }
3506
3507        ElementProperty[] props = vsBean.getElementProperty();
3508        if (props == null) {
3509            return;
3510        }
3511
3512        for (int i=0; i<props.length; i++) {
3513
3514            String JavaDoc propName = props[i].getName();
3515            String JavaDoc propValue = props[i].getValue();
3516            if (propName == null || propValue == null) {
3517                _logger.log(Level.WARNING,
3518                            "webcontainer.nullVirtualServerProperty",
3519                            vs.getID());
3520            }
3521
3522            if (!propName.startsWith("redirect_")) {
3523                continue;
3524            }
3525
3526            /*
3527             * Validate the prop value
3528             */

3529            String JavaDoc from = null;
3530            String JavaDoc url = null;
3531            String JavaDoc urlPrefix = null;
3532            String JavaDoc escape = null;
3533
3534            String JavaDoc[] redirectParams = propValue.split(" ");
3535            for (int j=0; j<redirectParams.length; j++) {
3536
3537                if (redirectParams[j].startsWith("from=")) {
3538                    if (from != null) {
3539                        _logger.log(Level.WARNING,
3540                                    "webcontainer.redirectMultipleElement",
3541                                    new Object JavaDoc[] { propValue, "from" });
3542                    }
3543                    from = redirectParams[j].substring("from=".length());
3544                }
3545
3546                if (redirectParams[j].startsWith("url=")) {
3547                    if (url != null) {
3548                        _logger.log(Level.WARNING,
3549                                    "webcontainer.redirectMultipleElement",
3550                                    new Object JavaDoc[] { propValue, "url" });
3551                    }
3552                    url = redirectParams[j].substring("url=".length());
3553                }
3554
3555                if (redirectParams[j].startsWith("url-prefix=")) {
3556                    if (urlPrefix != null) {
3557                        _logger.log(Level.WARNING,
3558                                    "webcontainer.redirectMultipleElement",
3559                                    new Object JavaDoc[] { propValue, "url-prefix" });
3560                    }
3561                    urlPrefix = redirectParams[j].substring(
3562                                                    "url-prefix=".length());
3563                }
3564
3565                if (redirectParams[j].startsWith("escape=")) {
3566                    if (escape != null) {
3567                        _logger.log(Level.WARNING,
3568                                    "webcontainer.redirectMultipleElement",
3569                                    new Object JavaDoc[] { propValue, "escape" });
3570                    }
3571                    escape = redirectParams[j].substring("escape=".length());
3572                }
3573            }
3574
3575            if (from == null || from.length() == 0) {
3576                _logger.log(Level.WARNING,
3577                            "webcontainer.redirectMissingFrom",
3578                            propValue);
3579            }
3580
3581            // Either url or url-prefix (but not both!) must be present
3582
if ((url == null || url.length() == 0)
3583                    && (urlPrefix == null || urlPrefix.length() == 0)) {
3584                _logger.log(Level.WARNING,
3585                            "webcontainer.redirectMissingUrlOrUrlPrefix",
3586                            propValue);
3587            }
3588            if (url != null && url.length() > 0
3589                    && urlPrefix != null && urlPrefix.length() > 0) {
3590                _logger.log(Level.WARNING,
3591                            "webcontainer.redirectBothUrlAndUrlPrefix",
3592                            propValue);
3593            }
3594
3595            boolean escapeURI = true;
3596            if (escape != null) {
3597                if ("yes".equalsIgnoreCase(escape)) {
3598                    escapeURI = true;
3599                } else if ("no".equalsIgnoreCase(escape)) {
3600                    escapeURI = false;
3601                } else {
3602                    _logger.log(Level.WARNING,
3603                                "webcontainer.redirectInvalidEscape",
3604                                propValue);
3605                }
3606            }
3607
3608            vs.addRedirect(from, url, urlPrefix, escapeURI);
3609        }
3610
3611    }
3612
3613
3614    /**
3615     * Configures the given virtual server with its send-error properties.
3616     *
3617     * @param vs The virtual server to be configured
3618     * @param vsBean The virtual server bean
3619     */

3620    private void configureErrorPage(
3621        VirtualServer vs,
3622        com.sun.enterprise.config.serverbeans.VirtualServer vsBean) {
3623
3624        ErrorPage errorPage = null;
3625
3626        if (vsBean == null) {
3627            return;
3628        }
3629
3630        ElementProperty[] props = vsBean.getElementProperty();
3631        if (props == null) {
3632            return;
3633        }
3634
3635        for (int i=0; i<props.length; i++) {
3636
3637            String JavaDoc propName = props[i].getName();
3638            String JavaDoc propValue = props[i].getValue();
3639            if (propName == null || propValue == null) {
3640                _logger.log(Level.WARNING,
3641                            "webcontainer.nullVirtualServerProperty",
3642                            vs.getID());
3643            }
3644
3645            if (!propName.startsWith("send-error_")) {
3646                continue;
3647            }
3648
3649            /*
3650             * Validate the prop value
3651             */

3652            String JavaDoc path = null;
3653            String JavaDoc reason = null;
3654            String JavaDoc status = null;
3655
3656            String JavaDoc[] errorParams = propValue.split(" ");
3657            for (int j=0; j<errorParams.length; j++) {
3658
3659                if (errorParams[j].startsWith("path=")) {
3660                    if (path != null) {
3661                        _logger.log(Level.WARNING,
3662                                    "webcontainer.sendErrorMultipleElement",
3663                                    new Object JavaDoc[] { propValue, "path" });
3664                    }
3665                    path = errorParams[j].substring("path=".length());
3666                }
3667
3668                if (errorParams[j].startsWith("reason=")) {
3669                    if (reason != null) {
3670                        _logger.log(Level.WARNING,
3671                                    "webcontainer.sendErrorMultipleElement",
3672                                    new Object JavaDoc[] { propValue, "reason" });
3673                    }
3674                    reason = errorParams[j].substring("reason=".length());
3675                }
3676
3677                if (errorParams[j].startsWith("code=")) {
3678                    if (status != null) {
3679                        _logger.log(Level.WARNING,
3680                                    "webcontainer.sendErrorMultipleElement",
3681                                    new Object JavaDoc[] { propValue, "code" });
3682                    }
3683                    status = errorParams[j].substring("code=".length());
3684                }
3685            }
3686
3687            if (path == null || path.length() == 0) {
3688                _logger.log(Level.WARNING,
3689                            "webcontainer.sendErrorMissingPath",
3690                            propValue);
3691            }
3692
3693            errorPage = new ErrorPage();
3694            errorPage.setLocation(path);
3695            errorPage.setErrorCode(status);
3696            errorPage.setReason(reason);
3697
3698            vs.addErrorPage(errorPage);
3699        }
3700
3701    }
3702
3703
3704    /*
3705     * Gets the instance classpath, which is composed of the pathnames of
3706     * domain_root/lib/classes and domain_root/lib/[*.jar|*.zip] (in this
3707     * order), separated by the path-separator character.
3708     *
3709     * @param instanceEnv The instance whose classpath is to be determined
3710     *
3711     * @return The instance classpath
3712     */

3713    private String JavaDoc getInstanceClassPath(InstanceEnvironment instanceEnv) {
3714
3715        if (instanceEnv == null) {
3716            return null;
3717        }
3718
3719        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
3720
3721        File JavaDoc libDir = new File JavaDoc(instanceEnv.getLibPath());
3722        String JavaDoc libDirPath = libDir.getAbsolutePath();
3723
3724        // Append domain_root/lib/classes
3725
sb.append(libDirPath + File.separator + "classes");
3726        sb.append(File.pathSeparator);
3727
3728        // Append domain_root/lib/[*.jar|*.zip]
3729
String JavaDoc[] files = libDir.list();
3730        if (files != null) {
3731            for (int i=0; i<files.length; i++) {
3732                if (files[i].endsWith(".jar") || files[i].endsWith(".zip")) {
3733                    sb.append(libDirPath + File.separator + files[i]);
3734                    sb.append(File.pathSeparator);
3735                }
3736            }
3737        }
3738
3739        return sb.toString();
3740    }
3741
3742
3743    /*
3744     * Gets the instance classpath, which is composed of the pathnames of
3745     * domain_root/lib/classes and domain_root/lib/[*.jar|*.zip] (in this
3746     * order), separated by the path-separator character.
3747     *
3748     * @return The instance classpath
3749     */

3750    String JavaDoc getInstanceClassPath() {
3751        return this.instanceClassPath;
3752    }
3753  
3754}
3755         
3756
Popular Tags