KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > jetty > deployment > JettyModuleBuilder


1 /**
2  *
3  * Copyright 2003-2004 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.geronimo.jetty.deployment;
19
20 import java.io.File JavaDoc;
21 import java.io.FileFilter JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.net.MalformedURLException JavaDoc;
24 import java.net.URI JavaDoc;
25 import java.net.URISyntaxException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.security.Permission JavaDoc;
28 import java.security.PermissionCollection JavaDoc;
29 import java.security.Permissions JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Collections JavaDoc;
33 import java.util.Enumeration JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.Set JavaDoc;
40 import java.util.jar.JarFile JavaDoc;
41 import java.util.zip.ZipEntry JavaDoc;
42 import javax.management.MalformedObjectNameException JavaDoc;
43 import javax.management.ObjectName JavaDoc;
44 import javax.security.jacc.WebResourcePermission JavaDoc;
45 import javax.security.jacc.WebRoleRefPermission JavaDoc;
46 import javax.security.jacc.WebUserDataPermission JavaDoc;
47 import javax.servlet.Servlet JavaDoc;
48 import javax.transaction.UserTransaction JavaDoc;
49
50 import org.apache.geronimo.common.DeploymentException;
51 import org.apache.geronimo.deployment.service.ServiceConfigBuilder;
52 import org.apache.geronimo.deployment.util.DeploymentUtil;
53 import org.apache.geronimo.deployment.xbeans.DependencyType;
54 import org.apache.geronimo.deployment.xbeans.GbeanType;
55 import org.apache.geronimo.gbean.GBeanData;
56 import org.apache.geronimo.gbean.GBeanInfo;
57 import org.apache.geronimo.gbean.GBeanInfoBuilder;
58 import org.apache.geronimo.j2ee.deployment.EARContext;
59 import org.apache.geronimo.j2ee.deployment.Module;
60 import org.apache.geronimo.j2ee.deployment.ModuleBuilder;
61 import org.apache.geronimo.j2ee.deployment.WebServiceBuilder;
62 import org.apache.geronimo.j2ee.deployment.WebModule;
63 import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContext;
64 import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContextImpl;
65 import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
66 import org.apache.geronimo.jetty.JettyClassLoader;
67 import org.apache.geronimo.jetty.JettyFilterHolder;
68 import org.apache.geronimo.jetty.JettyFilterMapping;
69 import org.apache.geronimo.jetty.JettyServletHolder;
70 import org.apache.geronimo.jetty.JettyWebAppContext;
71 import org.apache.geronimo.kernel.GBeanNotFoundException;
72 import org.apache.geronimo.kernel.Kernel;
73 import org.apache.geronimo.kernel.repository.Repository;
74 import org.apache.geronimo.naming.deployment.ENCConfigBuilder;
75 import org.apache.geronimo.naming.deployment.GBeanResourceEnvironmentBuilder;
76 import org.apache.geronimo.schema.SchemaConversionUtils;
77 import org.apache.geronimo.security.deploy.DefaultPrincipal;
78 import org.apache.geronimo.security.deployment.SecurityBuilder;
79 import org.apache.geronimo.security.deployment.SecurityConfiguration;
80 import org.apache.geronimo.security.jacc.ComponentPermissions;
81 import org.apache.geronimo.security.util.URLPattern;
82 import org.apache.geronimo.transaction.context.OnlineUserTransaction;
83 import org.apache.geronimo.xbeans.geronimo.jetty.JettyWebAppDocument;
84 import org.apache.geronimo.xbeans.geronimo.jetty.JettyWebAppType;
85 import org.apache.geronimo.xbeans.j2ee.DispatcherType;
86 import org.apache.geronimo.xbeans.j2ee.ErrorPageType;
87 import org.apache.geronimo.xbeans.j2ee.FilterMappingType;
88 import org.apache.geronimo.xbeans.j2ee.FilterType;
89 import org.apache.geronimo.xbeans.j2ee.FormLoginConfigType;
90 import org.apache.geronimo.xbeans.j2ee.HttpMethodType;
91 import org.apache.geronimo.xbeans.j2ee.JspConfigType;
92 import org.apache.geronimo.xbeans.j2ee.ListenerType;
93 import org.apache.geronimo.xbeans.j2ee.LocaleEncodingMappingListType;
94 import org.apache.geronimo.xbeans.j2ee.LocaleEncodingMappingType;
95 import org.apache.geronimo.xbeans.j2ee.LoginConfigType;
96 import org.apache.geronimo.xbeans.j2ee.MimeMappingType;
97 import org.apache.geronimo.xbeans.j2ee.ParamValueType;
98 import org.apache.geronimo.xbeans.j2ee.RoleNameType;
99 import org.apache.geronimo.xbeans.j2ee.SecurityConstraintType;
100 import org.apache.geronimo.xbeans.j2ee.SecurityRoleRefType;
101 import org.apache.geronimo.xbeans.j2ee.SecurityRoleType;
102 import org.apache.geronimo.xbeans.j2ee.ServletMappingType;
103 import org.apache.geronimo.xbeans.j2ee.ServletType;
104 import org.apache.geronimo.xbeans.j2ee.TaglibType;
105 import org.apache.geronimo.xbeans.j2ee.UrlPatternType;
106 import org.apache.geronimo.xbeans.j2ee.WebAppDocument;
107 import org.apache.geronimo.xbeans.j2ee.WebAppType;
108 import org.apache.geronimo.xbeans.j2ee.WebResourceCollectionType;
109 import org.apache.geronimo.xbeans.j2ee.WelcomeFileListType;
110 import org.apache.xmlbeans.XmlException;
111 import org.apache.xmlbeans.XmlObject;
112 import org.mortbay.http.BasicAuthenticator;
113 import org.mortbay.http.ClientCertAuthenticator;
114 import org.mortbay.http.DigestAuthenticator;
115 import org.mortbay.jetty.servlet.FormAuthenticator;
116
117
118 /**
119  * @version $Rev: 169154 $ $Date: 2005-05-08 12:35:23 -0700 (Sun, 08 May 2005) $
120  */

121 public class JettyModuleBuilder implements ModuleBuilder {
122     private final URI JavaDoc defaultParentId;
123     private final ObjectName JavaDoc jettyContainerObjectName;
124     private final ObjectName JavaDoc defaultServlets;
125     private final ObjectName JavaDoc defaultFilters;
126     private final ObjectName JavaDoc defaultFilterMappings;
127     private final ObjectName JavaDoc pojoWebServiceTemplate;
128
129     private final WebServiceBuilder webServiceBuilder;
130
131     private final List JavaDoc defaultWelcomeFiles;
132     private final Integer JavaDoc defaultSessionTimeoutSeconds;
133
134     private final Repository repository;
135     private final Kernel kernel;
136
137     public JettyModuleBuilder(URI JavaDoc defaultParentId,
138                               Integer JavaDoc defaultSessionTimeoutSeconds,
139                               List JavaDoc defaultWelcomeFiles,
140                               ObjectName JavaDoc jettyContainerObjectName,
141                               ObjectName JavaDoc defaultServlets,
142                               ObjectName JavaDoc defaultFilters,
143                               ObjectName JavaDoc defaultFilterMappings,
144                               ObjectName JavaDoc pojoWebServiceTemplate,
145                               WebServiceBuilder webServiceBuilder,
146                               Repository repository,
147                               Kernel kernel) {
148         this.defaultParentId = defaultParentId;
149         this.defaultSessionTimeoutSeconds = (defaultSessionTimeoutSeconds == null) ? new Integer JavaDoc(30 * 60) : defaultSessionTimeoutSeconds;
150         this.jettyContainerObjectName = jettyContainerObjectName;
151         this.defaultServlets = defaultServlets;
152         this.defaultFilters = defaultFilters;
153         this.defaultFilterMappings = defaultFilterMappings;
154         this.pojoWebServiceTemplate = pojoWebServiceTemplate;
155         this.webServiceBuilder = webServiceBuilder;
156         this.repository = repository;
157         this.kernel = kernel;
158
159         //todo locale mappings
160

161         this.defaultWelcomeFiles = defaultWelcomeFiles;
162     }
163
164     public Module createModule(File JavaDoc plan, JarFile JavaDoc moduleFile) throws DeploymentException {
165         return createModule(plan, moduleFile, "war", null, true);
166     }
167
168     public Module createModule(Object JavaDoc plan, JarFile JavaDoc moduleFile, String JavaDoc targetPath, URL JavaDoc specDDUrl, URI JavaDoc earConfigId) throws DeploymentException {
169         return createModule(plan, moduleFile, targetPath, specDDUrl, false);
170     }
171
172     private Module createModule(Object JavaDoc plan, JarFile JavaDoc moduleFile, String JavaDoc targetPath, URL JavaDoc specDDUrl, boolean standAlone) throws DeploymentException {
173         assert moduleFile != null: "moduleFile is null";
174         assert targetPath != null: "targetPath is null";
175         assert !targetPath.endsWith("/"): "targetPath must not end with a '/'";
176
177         // parse the spec dd
178
String JavaDoc specDD;
179         WebAppType webApp;
180         try {
181             if (specDDUrl == null) {
182                 specDDUrl = DeploymentUtil.createJarURL(moduleFile, "WEB-INF/web.xml");
183             }
184
185             // read in the entire specDD as a string, we need this for getDeploymentDescriptor
186
// on the J2ee management object
187
specDD = DeploymentUtil.readAll(specDDUrl);
188         } catch (Exception JavaDoc e) {
189             //no web.xml, not for us
190
return null;
191         }
192         //we found web.xml, if it won't parse that's an error.
193
try {
194             // parse it
195
XmlObject parsed = SchemaConversionUtils.parse(specDD);
196             WebAppDocument webAppDoc = SchemaConversionUtils.convertToServletSchema(parsed);
197             webApp = webAppDoc.getWebApp();
198         } catch (XmlException xmle) {
199             throw new DeploymentException("Error parsing web.xml", xmle);
200         }
201         check(webApp);
202
203         //look for a webservices dd
204
Map JavaDoc portMap = Collections.EMPTY_MAP;
205         try {
206             URL JavaDoc wsDDUrl = DeploymentUtil.createJarURL(moduleFile, "WEB-INF/webservices.xml");
207             portMap = webServiceBuilder.parseWebServiceDescriptor(wsDDUrl, moduleFile, false);
208         } catch (MalformedURLException JavaDoc e) {
209             //no descriptor
210
}
211
212         // parse vendor dd
213
JettyWebAppType jettyWebApp = getJettyWebApp(plan, moduleFile, standAlone, targetPath, webApp);
214
215         // get the ids from either the application plan or for a stand alone module from the specific deployer
216
URI JavaDoc configId = null;
217         try {
218             configId = new URI JavaDoc(jettyWebApp.getConfigId());
219         } catch (URISyntaxException JavaDoc e) {
220             throw new DeploymentException("Invalid configId " + jettyWebApp.getConfigId(), e);
221         }
222
223         URI JavaDoc parentId = null;
224         if (jettyWebApp.isSetParentId()) {
225             try {
226                 parentId = new URI JavaDoc(jettyWebApp.getParentId());
227             } catch (URISyntaxException JavaDoc e) {
228                 throw new DeploymentException("Invalid parentId " + jettyWebApp.getParentId(), e);
229             }
230         } else {
231             parentId = defaultParentId;
232         }
233
234         WebModule module = new WebModule(standAlone, configId, parentId, moduleFile, targetPath, webApp, jettyWebApp, specDD, portMap);
235         module.setContextRoot(jettyWebApp.getContextRoot());
236         return module;
237     }
238
239     JettyWebAppType getJettyWebApp(Object JavaDoc plan, JarFile JavaDoc moduleFile, boolean standAlone, String JavaDoc targetPath, WebAppType webApp) throws DeploymentException {
240         JettyWebAppType jettyWebApp = null;
241         try {
242             // load the geronimo-jetty.xml from either the supplied plan or from the earFile
243
try {
244                 if (plan instanceof XmlObject) {
245                     jettyWebApp = (JettyWebAppType) SchemaConversionUtils.getNestedObjectAsType((XmlObject) plan,
246                             "web-app",
247                             JettyWebAppType.type);
248                 } else {
249                     JettyWebAppDocument jettyWebAppdoc = null;
250                     if (plan != null) {
251                         jettyWebAppdoc = JettyWebAppDocument.Factory.parse((File JavaDoc) plan);
252                     } else {
253                         URL JavaDoc path = DeploymentUtil.createJarURL(moduleFile, "WEB-INF/geronimo-jetty.xml");
254                         jettyWebAppdoc = JettyWebAppDocument.Factory.parse(path);
255                     }
256                     if (jettyWebAppdoc != null) {
257                         jettyWebApp = jettyWebAppdoc.getWebApp();
258                     }
259                 }
260             } catch (IOException JavaDoc e) {
261             }
262
263             // if we got one extract and validate it otherwise create a default one
264
if (jettyWebApp != null) {
265                 jettyWebApp = (JettyWebAppType) SchemaConversionUtils.convertToGeronimoNamingSchema(jettyWebApp);
266                 jettyWebApp = (JettyWebAppType) SchemaConversionUtils.convertToGeronimoSecuritySchema(jettyWebApp);
267                 jettyWebApp = (JettyWebAppType) SchemaConversionUtils.convertToGeronimoServiceSchema(jettyWebApp);
268                 SchemaConversionUtils.validateDD(jettyWebApp);
269             } else {
270                 String JavaDoc path;
271                 if (standAlone) {
272                     // default configId is based on the moduleFile name
273
path = new File JavaDoc(moduleFile.getName()).getName();
274                 } else {
275                     // default configId is based on the module uri from the application.xml
276
path = targetPath;
277                 }
278                 jettyWebApp = createDefaultPlan(path, webApp);
279             }
280         } catch (XmlException e) {
281             throw new DeploymentException("xml problem", e);
282         }
283         return jettyWebApp;
284     }
285
286     private JettyWebAppType createDefaultPlan(String JavaDoc path, WebAppType webApp) {
287         String JavaDoc id = webApp.getId();
288         if (id == null) {
289             id = path;
290             if (id.endsWith(".war")) {
291                 id = id.substring(0, id.length() - 4);
292             }
293             if (id.endsWith("/")) {
294                 id = id.substring(0, id.length() - 1);
295             }
296         }
297
298         JettyWebAppType jettyWebApp = JettyWebAppType.Factory.newInstance();
299
300         // set the parentId, configId and context root
301
jettyWebApp.setParentId(defaultParentId.toString());
302         if (null != webApp.getId()) {
303             id = webApp.getId();
304         }
305         jettyWebApp.setConfigId(id);
306         jettyWebApp.setContextRoot(id);
307         return jettyWebApp;
308     }
309
310     public void installModule(JarFile JavaDoc earFile, EARContext earContext, Module module) throws DeploymentException {
311         try {
312             URI JavaDoc baseDir = URI.create(module.getTargetPath() + "/");
313
314             // add the warfile's content to the configuration
315
JarFile JavaDoc warFile = module.getModuleFile();
316             Enumeration JavaDoc entries = warFile.entries();
317             while (entries.hasMoreElements()) {
318                 ZipEntry JavaDoc entry = (ZipEntry JavaDoc) entries.nextElement();
319                 URI JavaDoc targetPath = baseDir.resolve(new URI JavaDoc(null, entry.getName(), null));
320                 if (entry.getName().equals("WEB-INF/web.xml")) {
321                     earContext.addFile(targetPath, module.getOriginalSpecDD());
322                 } else {
323                     earContext.addFile(targetPath, warFile, entry);
324                 }
325             }
326
327             // add the manifest classpath entries declared in the war to the class loader
328
// we have to explicitly add these since we are unpacking the web module
329
// and the url class loader will not pick up a manifiest from an unpacked dir
330
earContext.addManifestClassPath(warFile, URI.create(module.getTargetPath()));
331
332             // add the dependencies declared in the geronimo-jetty.xml file
333
JettyWebAppType jettyWebApp = (JettyWebAppType) module.getVendorDD();
334             DependencyType[] dependencies = jettyWebApp.getDependencyArray();
335             ServiceConfigBuilder.addDependencies(earContext, dependencies, repository);
336         } catch (IOException JavaDoc e) {
337             throw new DeploymentException("Problem deploying war", e);
338         } catch (URISyntaxException JavaDoc e) {
339             throw new DeploymentException("Could not construct URI for location of war entry", e);
340         }
341     }
342
343     public void initContext(EARContext earContext, Module module, ClassLoader JavaDoc cl) {
344         // web application do not add anything to the shared context
345
}
346
347     public void addGBeans(EARContext earContext, Module module, ClassLoader JavaDoc cl) throws DeploymentException {
348         J2eeContext earJ2eeContext = earContext.getJ2eeContext();
349         J2eeContext moduleJ2eeContext = J2eeContextImpl.newModuleContextFromApplication(earJ2eeContext, NameFactory.WEB_MODULE, module.getName());
350         WebModule webModule = (WebModule) module;
351
352         WebAppType webApp = (WebAppType) webModule.getSpecDD();
353         JettyWebAppType jettyWebApp = (JettyWebAppType) webModule.getVendorDD();
354
355         boolean contextPriorityClassLoader = false;
356         if (jettyWebApp != null) {
357             contextPriorityClassLoader = Boolean.valueOf(jettyWebApp.getContextPriorityClassloader()).booleanValue();
358         }
359         // construct the webClassLoader
360
ClassLoader JavaDoc webClassLoader = getWebClassLoader(earContext, webModule, cl, contextPriorityClassLoader);
361
362         if (jettyWebApp != null) {
363             GbeanType[] gbeans = jettyWebApp.getGbeanArray();
364             ServiceConfigBuilder.addGBeans(gbeans, webClassLoader, moduleJ2eeContext, earContext);
365         }
366
367         ObjectName JavaDoc webModuleName = null;
368         try {
369             webModuleName = NameFactory.getModuleName(null, null, null, null, null, moduleJ2eeContext);
370         } catch (MalformedObjectNameException JavaDoc e) {
371             throw new DeploymentException("Could not construct module name", e);
372         }
373
374         UserTransaction JavaDoc userTransaction = new OnlineUserTransaction();
375         //this may add to the web classpath with enhanced classes.
376
Map JavaDoc compContext = buildComponentContext(earContext, webModule, webApp, jettyWebApp, userTransaction, webClassLoader);
377
378         GBeanData webModuleData = new GBeanData(webModuleName, JettyWebAppContext.GBEAN_INFO);
379         try {
380             webModuleData.setReferencePattern("J2EEServer", earContext.getServerObjectName());
381             if (!earContext.getJ2EEApplicationName().equals("null")) {
382                 webModuleData.setReferencePattern("J2EEApplication", earContext.getApplicationObjectName());
383             }
384
385             webModuleData.setAttribute("deploymentDescriptor", module.getOriginalSpecDD());
386             Set JavaDoc securityRoles = collectRoleNames(webApp);
387             Map JavaDoc rolePermissions = new HashMap JavaDoc();
388
389             webModuleData.setAttribute("uri", URI.create(module.getTargetPath() + "/"));
390             webModuleData.setAttribute("componentContext", compContext);
391             webModuleData.setAttribute("userTransaction", userTransaction);
392             //classpath may have been augmented with enhanced classes
393
webModuleData.setAttribute("webClassPath", webModule.getWebClasspath());
394             // unsharableResources, applicationManagedSecurityResources
395
GBeanResourceEnvironmentBuilder rebuilder = new GBeanResourceEnvironmentBuilder(webModuleData);
396             ENCConfigBuilder.setResourceEnvironment(earContext, webModule.getModuleURI(), rebuilder, webApp.getResourceRefArray(), jettyWebApp.getResourceRefArray());
397
398             webModuleData.setAttribute("contextPath", webModule.getContextRoot());
399             webModuleData.setAttribute("contextPriorityClassLoader", Boolean.valueOf(contextPriorityClassLoader));
400
401             webModuleData.setReferencePattern("TransactionContextManager", earContext.getTransactionContextManagerObjectName());
402             webModuleData.setReferencePattern("TrackedConnectionAssociator", earContext.getConnectionTrackerObjectName());
403             webModuleData.setReferencePattern("JettyContainer", jettyContainerObjectName);
404             //stuff that jetty used to do
405
if (webApp.getDisplayNameArray().length > 0) {
406                 webModuleData.setAttribute("displayName", webApp.getDisplayNameArray()[0].getStringValue());
407             }
408
409             ParamValueType[] contextParamArray = webApp.getContextParamArray();
410             Map JavaDoc contextParams = new HashMap JavaDoc();
411             for (int i = 0; i < contextParamArray.length; i++) {
412                 ParamValueType contextParam = contextParamArray[i];
413                 contextParams.put(contextParam.getParamName().getStringValue().trim(), contextParam.getParamValue().getStringValue().trim());
414             }
415             webModuleData.setAttribute("contextParamMap", contextParams);
416
417             ListenerType[] listenerArray = webApp.getListenerArray();
418             Collection JavaDoc listeners = new ArrayList JavaDoc();
419             for (int i = 0; i < listenerArray.length; i++) {
420                 ListenerType listenerType = listenerArray[i];
421                 listeners.add(listenerType.getListenerClass().getStringValue());
422             }
423             webModuleData.setAttribute("listenerClassNames", listeners);
424
425             webModuleData.setAttribute("distributable", webApp.getDistributableArray().length == 1 ? Boolean.TRUE : Boolean.FALSE);
426
427             webModuleData.setAttribute("sessionTimeoutSeconds",
428                     (webApp.getSessionConfigArray().length == 1 && webApp.getSessionConfigArray(0).getSessionTimeout() != null) ?
429                     new Integer JavaDoc(webApp.getSessionConfigArray(0).getSessionTimeout().getBigIntegerValue().intValue() * 60) :
430                     defaultSessionTimeoutSeconds);
431
432             MimeMappingType[] mimeMappingArray = webApp.getMimeMappingArray();
433             Map JavaDoc mimeMappingMap = new HashMap JavaDoc();
434             for (int i = 0; i < mimeMappingArray.length; i++) {
435                 MimeMappingType mimeMappingType = mimeMappingArray[i];
436                 mimeMappingMap.put(mimeMappingType.getExtension().getStringValue(), mimeMappingType.getMimeType().getStringValue());
437             }
438             webModuleData.setAttribute("mimeMap", mimeMappingMap);
439
440             WelcomeFileListType[] welcomeFileArray = webApp.getWelcomeFileListArray();
441             List JavaDoc welcomeFiles;
442             if (welcomeFileArray.length > 0) {
443                 welcomeFiles = new ArrayList JavaDoc();
444                 for (int i = 0; i < welcomeFileArray.length; i++) {
445                     String JavaDoc[] welcomeFileListType = welcomeFileArray[i].getWelcomeFileArray();
446                     for (int j = 0; j < welcomeFileListType.length; j++) {
447                         String JavaDoc welcomeFile = welcomeFileListType[j].trim();
448                         welcomeFiles.add(welcomeFile);
449                     }
450                 }
451             } else {
452                 welcomeFiles = new ArrayList JavaDoc(defaultWelcomeFiles);
453             }
454             webModuleData.setAttribute("welcomeFiles", welcomeFiles.toArray(new String JavaDoc[welcomeFiles.size()]));
455
456             LocaleEncodingMappingListType[] localeEncodingMappingListArray = webApp.getLocaleEncodingMappingListArray();
457             Map JavaDoc localeEncodingMappingMap = new HashMap JavaDoc();
458             for (int i = 0; i < localeEncodingMappingListArray.length; i++) {
459                 LocaleEncodingMappingType[] localeEncodingMappingArray = localeEncodingMappingListArray[i].getLocaleEncodingMappingArray();
460                 for (int j = 0; j < localeEncodingMappingArray.length; j++) {
461                     LocaleEncodingMappingType localeEncodingMapping = localeEncodingMappingArray[j];
462                     localeEncodingMappingMap.put(localeEncodingMapping.getLocale(), localeEncodingMapping.getEncoding());
463                 }
464             }
465             webModuleData.setAttribute("localeEncodingMapping", localeEncodingMappingMap);
466
467             ErrorPageType[] errorPageArray = webApp.getErrorPageArray();
468             Map JavaDoc errorPageMap = new HashMap JavaDoc();
469             for (int i = 0; i < errorPageArray.length; i++) {
470                 ErrorPageType errorPageType = errorPageArray[i];
471                 if (errorPageType.isSetErrorCode()) {
472                     errorPageMap.put(errorPageType.getErrorCode().getStringValue(), errorPageType.getLocation().getStringValue());
473                 } else {
474                     errorPageMap.put(errorPageType.getExceptionType().getStringValue(), errorPageType.getLocation().getStringValue());
475                 }
476             }
477             webModuleData.setAttribute("errorPages", errorPageMap);
478
479             JspConfigType[] jspConfigArray = webApp.getJspConfigArray();
480             if (jspConfigArray.length > 1) {
481                 throw new DeploymentException("At most one jsp-config element, not " + jspConfigArray.length);
482             }
483             Map JavaDoc tagLibMap = new HashMap JavaDoc();
484             for (int i = 0; i < jspConfigArray.length; i++) {
485                 TaglibType[] tagLibArray = jspConfigArray[i].getTaglibArray();
486                 for (int j = 0; j < tagLibArray.length; j++) {
487                     TaglibType taglib = tagLibArray[j];
488                     tagLibMap.put(taglib.getTaglibUri().getStringValue().trim(), taglib.getTaglibLocation().getStringValue().trim());
489                 }
490             }
491             webModuleData.setAttribute("tagLibMap", tagLibMap);
492
493             LoginConfigType[] loginConfigArray = webApp.getLoginConfigArray();
494             if (loginConfigArray.length > 1) {
495                 throw new DeploymentException("At most one login-config element, not " + loginConfigArray.length);
496             }
497             if (loginConfigArray.length == 1) {
498                 LoginConfigType loginConfig = loginConfigArray[0];
499                 if (loginConfig.isSetAuthMethod()) {
500                     String JavaDoc authMethod = loginConfig.getAuthMethod().getStringValue();
501                     if ("BASIC".equals(authMethod)) {
502                         webModuleData.setAttribute("authenticator", new BasicAuthenticator());
503                     } else if ("DIGEST".equals(authMethod)) {
504                         webModuleData.setAttribute("authenticator", new DigestAuthenticator());
505                     } else if ("FORM".equals(authMethod)) {
506
507                         FormAuthenticator formAuthenticator = new FormAuthenticator();
508                         webModuleData.setAttribute("authenticator", formAuthenticator);
509                         if (loginConfig.isSetFormLoginConfig()) {
510                             FormLoginConfigType formLoginConfig = loginConfig.getFormLoginConfig();
511                             formAuthenticator.setLoginPage(formLoginConfig.getFormLoginPage().getStringValue());
512                             formAuthenticator.setErrorPage(formLoginConfig.getFormErrorPage().getStringValue());
513                         }
514                     } else if ("CLIENT-CERT".equals(authMethod)) {
515                         webModuleData.setAttribute("authenticator", new ClientCertAuthenticator());
516                     }
517                 }
518                 if (loginConfig.isSetRealmName()) {
519                     webModuleData.setAttribute("realmName", loginConfig.getRealmName().getStringValue());
520                 }
521
522             }
523             earContext.addGBean(webModuleData);
524
525             //never add a duplicate pattern.
526
Set JavaDoc knownServletMappings = new HashSet JavaDoc();
527
528             ServletMappingType[] servletMappingArray = webApp.getServletMappingArray();
529             Map JavaDoc servletMappings = new HashMap JavaDoc();
530             for (int i = 0; i < servletMappingArray.length; i++) {
531                 ServletMappingType servletMappingType = servletMappingArray[i];
532                 String JavaDoc servletName = servletMappingType.getServletName().getStringValue().trim();
533                 String JavaDoc urlPattern = servletMappingType.getUrlPattern().getStringValue();
534                 if (!knownServletMappings.contains(urlPattern)) {
535                     knownServletMappings.add(urlPattern);
536                     checkString(urlPattern);
537                     Set JavaDoc urlsForServlet = (Set JavaDoc) servletMappings.get(servletName);
538                     if (urlsForServlet == null) {
539                         urlsForServlet = new HashSet JavaDoc();
540                         servletMappings.put(servletName, urlsForServlet);
541                     }
542                     urlsForServlet.add(urlPattern);
543                 }
544             }
545
546             //"previous" filter mapping for linked list to keep dd's ordering.
547
ObjectName JavaDoc previous = null;
548
549             //add default filters
550
if (defaultFilters != null) {
551                 Set JavaDoc defaultFilterNames = kernel.listGBeans(defaultFilters);
552                 for (Iterator JavaDoc iterator = defaultFilterNames.iterator(); iterator.hasNext();) {
553
554                     GBeanData filterGBeanData = kernel.getGBeanData((ObjectName JavaDoc) iterator.next());
555                     String JavaDoc filterName = (String JavaDoc) filterGBeanData.getAttribute("filterName");
556                     ObjectName JavaDoc defaultFilterObjectName = NameFactory.getWebComponentName(null, null, null, null, filterName, NameFactory.WEB_FILTER, moduleJ2eeContext);
557                     filterGBeanData.setName(defaultFilterObjectName);
558                     filterGBeanData.setReferencePattern("JettyServletRegistration", webModuleName);
559                     earContext.addGBean(filterGBeanData);
560                     //add a mapping to /*
561

562                     GBeanData filterMappingGBeanData = new GBeanData(JettyFilterMapping.GBEAN_INFO);
563                     filterMappingGBeanData.setReferencePattern("Previous", previous);
564                     filterMappingGBeanData.setReferencePattern("JettyServletRegistration", webModuleName);
565                     String JavaDoc urlPattern = "/*";
566                     filterMappingGBeanData.setAttribute("urlPattern", urlPattern);
567                     ObjectName JavaDoc filterMappingName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, null, urlPattern, moduleJ2eeContext);
568                     filterMappingGBeanData.setName(filterMappingName);
569                     previous = filterMappingName;
570
571
572                     filterMappingGBeanData.setAttribute("requestDispatch", Boolean.TRUE);
573                     filterMappingGBeanData.setAttribute("forwardDispatch", Boolean.TRUE);
574                     filterMappingGBeanData.setAttribute("includeDispatch", Boolean.TRUE);
575                     filterMappingGBeanData.setAttribute("errorDispatch", Boolean.FALSE);
576                     filterMappingGBeanData.setReferencePattern("Filter", defaultFilterObjectName);
577                     earContext.addGBean(filterMappingGBeanData);
578                 }
579             }
580
581             //add default filtermappings
582
// if (defaultFilterMappings != null) {
583
// Set defaultFilterMappingNames = kernel.listGBeans(defaultFilterMappings);
584
// for (Iterator iterator = defaultFilterMappingNames.iterator(); iterator.hasNext();) {
585
//
586
// GBeanData filterMappingGBeanData = kernel.getGBeanData((ObjectName) iterator.next());
587
// String filterName = (String) filterMappingGBeanData.getAttribute("filterName");
588
// ObjectName defaultFilterMappingObjectName;
589
// if (filterMappingGBeanData.getAttribute("urlPattern") != null) {
590
// String urlPattern = (String) filterMappingGBeanData.getAttribute("urlPattern");
591
// defaultFilterMappingObjectName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, null, urlPattern, moduleJ2eeContext);
592
// } else {
593
// Set servletNames = filterMappingGBeanData.getReferencePatterns("Servlet");
594
// if (servletNames == null || servletNames.size() != 1) {
595
// throw new DeploymentException("Exactly one servlet name must be supplied");
596
// }
597
// ObjectName servletObjectName = (ObjectName) servletNames.iterator().next();
598
// String servletName = servletObjectName.getKeyProperty("name");
599
// defaultFilterMappingObjectName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, servletName, null, moduleJ2eeContext);
600
// }
601
// filterMappingGBeanData.setName(defaultFilterMappingObjectName);
602
// filterMappingGBeanData.setReferencePattern("JettyFilterMappingRegistration", webModuleName);
603
// earContext.addGBean(filterMappingGBeanData);
604
// }
605
// }
606

607             FilterMappingType[] filterMappingArray = webApp.getFilterMappingArray();
608             for (int i = 0; i < filterMappingArray.length; i++) {
609                 FilterMappingType filterMappingType = filterMappingArray[i];
610                 String JavaDoc filterName = filterMappingType.getFilterName().getStringValue().trim();
611                 GBeanData filterMappingData = new GBeanData(JettyFilterMapping.GBEAN_INFO);
612                 filterMappingData.setReferencePattern("Previous", previous);
613                 filterMappingData.setReferencePattern("JettyServletRegistration", webModuleName);
614
615                 ObjectName JavaDoc filterMappingName = null;
616                 if (filterMappingType.isSetUrlPattern()) {
617                     //do not trim!
618
String JavaDoc urlPattern = filterMappingType.getUrlPattern().getStringValue();
619                     filterMappingData.setAttribute("urlPattern", urlPattern);
620                     filterMappingName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, null, urlPattern, moduleJ2eeContext);
621                 }
622                 if (filterMappingType.isSetServletName()) {
623                     String JavaDoc servletName = filterMappingType.getServletName().getStringValue().trim();
624                     ObjectName JavaDoc servletObjectName = NameFactory.getWebComponentName(null, null, null, null, servletName, NameFactory.SERVLET, moduleJ2eeContext);
625                     filterMappingData.setReferencePattern("Servlet", servletObjectName);
626                     filterMappingName = NameFactory.getWebFilterMappingName(null, null, null, null, filterName, servletName, null, moduleJ2eeContext);
627                 }
628                 filterMappingData.setName(filterMappingName);
629                 previous = filterMappingName;
630
631                 boolean request = filterMappingType.getDispatcherArray().length == 0;
632                 boolean forward = false;
633                 boolean include = false;
634                 boolean error = false;
635                 for (int j = 0; j < filterMappingType.getDispatcherArray().length; j++) {
636                     DispatcherType dispatcherType = filterMappingType.getDispatcherArray()[j];
637                     if (dispatcherType.getStringValue().equals("REQUEST")) {
638                         request = true;
639                     } else if (dispatcherType.getStringValue().equals("FORWARD")) {
640                         forward = true;
641                     } else if (dispatcherType.getStringValue().equals("INCLUDE")) {
642                         include = true;
643                     } else if (dispatcherType.getStringValue().equals("ERROR")) {
644                         error = true;
645                     }
646                 }
647                 filterMappingData.setAttribute("requestDispatch", Boolean.valueOf(request));
648                 filterMappingData.setAttribute("forwardDispatch", Boolean.valueOf(forward));
649                 filterMappingData.setAttribute("includeDispatch", Boolean.valueOf(include));
650                 filterMappingData.setAttribute("errorDispatch", Boolean.valueOf(error));
651                 ObjectName JavaDoc filterObjectName = NameFactory.getWebComponentName(null, null, null, null, filterName, NameFactory.WEB_FILTER, moduleJ2eeContext);
652                 filterMappingData.setReferencePattern("Filter", filterObjectName);
653                 earContext.addGBean(filterMappingData);
654             }
655
656             FilterType[] filterArray = webApp.getFilterArray();
657             for (int i = 0; i < filterArray.length; i++) {
658                 FilterType filterType = filterArray[i];
659                 String JavaDoc filterName = filterType.getFilterName().getStringValue().trim();
660                 ObjectName JavaDoc filterObjectName = NameFactory.getWebComponentName(null, null, null, null, filterName, NameFactory.WEB_FILTER, moduleJ2eeContext);
661                 GBeanData filterData = new GBeanData(filterObjectName, JettyFilterHolder.GBEAN_INFO);
662                 filterData.setAttribute("filterName", filterName);
663                 filterData.setAttribute("filterClass", filterType.getFilterClass().getStringValue().trim());
664                 Map JavaDoc initParams = new HashMap JavaDoc();
665                 ParamValueType[] initParamArray = filterType.getInitParamArray();
666                 for (int j = 0; j < initParamArray.length; j++) {
667                     ParamValueType paramValueType = initParamArray[j];
668                     initParams.put(paramValueType.getParamName().getStringValue().trim(), paramValueType.getParamValue().getStringValue().trim());
669                 }
670                 filterData.setAttribute("initParams", initParams);
671                 filterData.setReferencePattern("JettyServletRegistration", webModuleName);
672                 earContext.addGBean(filterData);
673             }
674
675             //add default servlets
676
if (defaultServlets != null) {
677                 Set JavaDoc defaultServletNames = kernel.listGBeans(defaultServlets);
678                 for (Iterator JavaDoc iterator = defaultServletNames.iterator(); iterator.hasNext();) {
679
680                     GBeanData servletGBeanData = kernel.getGBeanData((ObjectName JavaDoc) iterator.next());
681                     ObjectName JavaDoc defaultServletObjectName = NameFactory.getWebComponentName(null, null, null, null, (String JavaDoc) servletGBeanData.getAttribute("servletName"), NameFactory.SERVLET, moduleJ2eeContext);
682                     servletGBeanData.setName(defaultServletObjectName);
683                     servletGBeanData.setReferencePattern("JettyServletRegistration", webModuleName);
684                     Set JavaDoc defaultServletMappings = new HashSet JavaDoc((Collection JavaDoc) servletGBeanData.getAttribute("servletMappings"));
685                     defaultServletMappings.removeAll(knownServletMappings);
686                     servletGBeanData.setAttribute("servletMappings", defaultServletMappings);
687                     earContext.addGBean(servletGBeanData);
688                 }
689             }
690
691             //set up servlet gbeans.
692
ServletType[] servletTypes = webApp.getServletArray();
693             Map JavaDoc portMap = webModule.getPortMap();
694
695             for (int i = 0; i < servletTypes.length; i++) {
696                 ServletType servletType = servletTypes[i];
697                 addServlet(webModuleName, webModule.getModuleFile(), servletType, servletMappings, securityRoles, rolePermissions, portMap, webClassLoader, moduleJ2eeContext, earContext);
698             }
699             if (jettyWebApp.isSetSecurityRealmName()) {
700                 String JavaDoc securityRealmName = jettyWebApp.getSecurityRealmName().trim();
701                 webModuleData.setAttribute("securityRealmName", securityRealmName);
702 // webModuleData.setAttribute("securityConfig", security);
703

704                 /**
705                  * TODO - go back to commented version when possible.
706                  */

707                 String JavaDoc policyContextID = webModuleName.getCanonicalName().replaceAll("[, :]", "_");
708                 //String policyContextID = webModuleName.getCanonicalName();
709
webModuleData.setAttribute("policyContextID", policyContextID);
710 // webModuleData.setAttribute("securityRoles", securityRoles);
711

712                 ComponentPermissions componentPermissions = buildSpecSecurityConfig(webApp, securityRoles, rolePermissions);
713                 webModuleData.setAttribute("excludedPermissions", componentPermissions.getExcludedPermissions());
714                 PermissionCollection JavaDoc checkedPermissions = new Permissions JavaDoc();
715                 for (Iterator JavaDoc iterator = rolePermissions.values().iterator(); iterator.hasNext();) {
716                     PermissionCollection JavaDoc permissionsForRole = (PermissionCollection JavaDoc) iterator.next();
717                     for (Enumeration JavaDoc iterator2 = permissionsForRole.elements(); iterator2.hasMoreElements();) {
718                         Permission JavaDoc permission = (Permission JavaDoc) iterator2.nextElement();
719                         checkedPermissions.add(permission);
720                     }
721                 }
722                 webModuleData.setAttribute("checkedPermissions", checkedPermissions);
723
724                 earContext.addSecurityContext(policyContextID, componentPermissions);
725                 if (jettyWebApp.isSetSecurity()) {
726                     SecurityConfiguration securityConfiguration = SecurityBuilder.buildSecurityConfiguration(jettyWebApp.getSecurity());
727                     earContext.setSecurityConfiguration(securityConfiguration);
728                 }
729                 DefaultPrincipal defaultPrincipal = earContext.getSecurityConfiguration().getDefaultPrincipal();
730                 webModuleData.setAttribute("defaultPrincipal", defaultPrincipal);
731
732                 webModuleData.setReferencePattern("RoleDesignateSource", earContext.getJaccManagerName());
733             }
734         } catch (DeploymentException de) {
735             throw de;
736         } catch (Exception JavaDoc e) {
737             throw new DeploymentException("Unable to initialize webapp GBean", e);
738         }
739     }
740
741     private ClassLoader JavaDoc getWebClassLoader(EARContext earContext, WebModule webModule, ClassLoader JavaDoc cl, boolean contextPriorityClassLoader) throws DeploymentException {
742         getWebClassPath(earContext, webModule);
743         URI JavaDoc[] webClassPath = webModule.getWebClasspath();
744         URI JavaDoc baseUri = earContext.getBaseDir().toURI();
745         URL JavaDoc baseUrl = null;
746         try {
747             baseUrl = baseUri.resolve(webModule.getTargetPathURI()).toURL();
748         } catch (MalformedURLException JavaDoc e) {
749             throw new DeploymentException("Invalid module location: " + webModule.getTargetPathURI() + ", baseUri: " + baseUri);
750         }
751         URL JavaDoc[] webClassPathURLs = new URL JavaDoc[webClassPath.length];
752         for (int i = 0; i < webClassPath.length; i++) {
753             URI JavaDoc path = baseUri.resolve(webClassPath[i]);
754             try {
755                 webClassPathURLs[i] = path.toURL();
756             } catch (MalformedURLException JavaDoc e) {
757                 throw new DeploymentException("Invalid web class path element: path=" + path + ", baseUri=" + baseUri);
758             }
759         }
760
761         ClassLoader JavaDoc webClassLoader = new JettyClassLoader(webClassPathURLs, baseUrl, cl, contextPriorityClassLoader);
762         return webClassLoader;
763     }
764
765     private void addServlet(ObjectName JavaDoc webModuleName,
766                             JarFile JavaDoc moduleFile,
767                             ServletType servletType,
768                             Map JavaDoc servletMappings,
769                             Set JavaDoc securityRoles,
770                             Map JavaDoc rolePermissions, Map JavaDoc portMap,
771                             ClassLoader JavaDoc webClassLoader,
772                             J2eeContext moduleJ2eeContext,
773                             EARContext earContext) throws MalformedObjectNameException JavaDoc, DeploymentException {
774         String JavaDoc servletName = servletType.getServletName().getStringValue().trim();
775         ObjectName JavaDoc servletObjectName = NameFactory.getWebComponentName(null, null, null, null, servletName, NameFactory.SERVLET, moduleJ2eeContext);
776         GBeanData servletData;
777         if (servletType.isSetServletClass()) {
778             String JavaDoc servletClassName = servletType.getServletClass().getStringValue().trim();
779             Class JavaDoc servletClass = null;
780             try {
781                 servletClass = webClassLoader.loadClass(servletClassName);
782             } catch (ClassNotFoundException JavaDoc e) {
783                 throw new DeploymentException("Could not load servlet class " + servletClassName, e);
784             }
785             Class JavaDoc baseServletClass = null;
786             try {
787                 baseServletClass = webClassLoader.loadClass(Servlet JavaDoc.class.getName());
788             } catch (ClassNotFoundException JavaDoc e) {
789                 throw new DeploymentException("Could not load javax.servlet.Servlet in web classloader", e);
790             }
791             if (baseServletClass.isAssignableFrom(servletClass)) {
792                 servletData = new GBeanData(servletObjectName, JettyServletHolder.GBEAN_INFO);
793                 servletData.setAttribute("servletClass", servletClassName);
794             } else {
795                 try {
796                     servletData = kernel.getGBeanData(pojoWebServiceTemplate);
797                 } catch (GBeanNotFoundException e) {
798                     throw new DeploymentException("No POJO web service template gbean found at object name: " + pojoWebServiceTemplate, e);
799                 }
800                 servletData.setName(servletObjectName);
801                 //let the web service builder deal with configuring the gbean with the web service stack
802
Object JavaDoc portInfo = portMap.get(servletName);
803                 if (portInfo == null) {
804                     throw new DeploymentException("No web service deployment info for servlet name " + servletName);
805                 }
806                 webServiceBuilder.configurePOJO(servletData, moduleFile, portInfo, servletClassName, webClassLoader);
807             }
808         } else if (servletType.isSetJspFile()) {
809             servletData = new GBeanData(servletObjectName, JettyServletHolder.GBEAN_INFO);
810             servletData.setAttribute("jspFile", servletType.getJspFile().getStringValue().trim());
811             //TODO MAKE THIS CONFIGURABLE!!! Jetty uses the servlet mapping set up from the default-web.xml
812
servletData.setAttribute("servletClass", "org.apache.jasper.servlet.JspServlet");
813         } else {
814             throw new DeploymentException("Neither servlet class nor jsp file is set for " + servletName);
815         }
816         //TODO in init param setter, add classpath if jspFile is not null.
817
servletData.setReferencePattern("JettyServletRegistration", webModuleName);
818         servletData.setAttribute("servletName", servletName);
819         Map JavaDoc initParams = new HashMap JavaDoc();
820         ParamValueType[] initParamArray = servletType.getInitParamArray();
821         for (int j = 0; j < initParamArray.length; j++) {
822             ParamValueType paramValueType = initParamArray[j];
823             initParams.put(paramValueType.getParamName().getStringValue().trim(), paramValueType.getParamValue().getStringValue().trim());
824         }
825         servletData.setAttribute("initParams", initParams);
826         if (servletType.isSetLoadOnStartup()) {
827             Integer JavaDoc loadOnStartup = new Integer JavaDoc(servletType.getLoadOnStartup().getBigIntegerValue().intValue());
828             servletData.setAttribute("loadOnStartup", loadOnStartup);
829         }
830
831         Set JavaDoc mappings = (Set JavaDoc) servletMappings.get(servletName);
832         servletData.setAttribute("servletMappings", mappings == null ? Collections.EMPTY_SET : mappings);
833
834
835         //WebRoleRefPermissions
836
SecurityRoleRefType[] securityRoleRefTypeArray = servletType.getSecurityRoleRefArray();
837         Set JavaDoc unmappedRoles = new HashSet JavaDoc(securityRoles);
838         for (int j = 0; j < securityRoleRefTypeArray.length; j++) {
839             SecurityRoleRefType securityRoleRefType = securityRoleRefTypeArray[j];
840             String JavaDoc roleName = securityRoleRefType.getRoleName().getStringValue().trim();
841             String JavaDoc roleLink = securityRoleRefType.getRoleLink().getStringValue().trim();
842             //jacc 3.1.3.2
843
/* The name of the WebRoleRefPermission must be the servlet-name in whose
844             * context the security-role-ref is defined. The actions of the WebRoleRefPermission
845             * must be the value of the role-name (that is the reference), appearing in the security-role-ref.
846             * The deployment tools must call the addToRole method on the PolicyConfiguration object to add the
847             * WebRoleRefPermission object resulting from the translation to the role
848             * identified in the role-link appearing in the security-role-ref.
849             */

850             addPermissionToRole(roleLink, new WebRoleRefPermission JavaDoc(servletName, roleName), rolePermissions);
851             unmappedRoles.remove(roleName);
852         }
853         for (Iterator JavaDoc iterator = unmappedRoles.iterator(); iterator.hasNext();) {
854             String JavaDoc roleName = (String JavaDoc) iterator.next();
855             addPermissionToRole(roleName, new WebRoleRefPermission JavaDoc(servletName, roleName), rolePermissions);
856         }
857 // servletData.setAttribute("webRoleRefPermissions", webRoleRefPermissions);
858

859         earContext.addGBean(servletData);
860     }
861
862     private ComponentPermissions buildSpecSecurityConfig(WebAppType webApp, Set JavaDoc securityRoles, Map JavaDoc rolePermissions) {
863         Map JavaDoc uncheckedPatterns = new HashMap JavaDoc();
864         Map JavaDoc uncheckedResourcePatterns = new HashMap JavaDoc();
865         Map JavaDoc uncheckedUserPatterns = new HashMap JavaDoc();
866         Map JavaDoc excludedPatterns = new HashMap JavaDoc();
867         Map JavaDoc rolesPatterns = new HashMap JavaDoc();
868         Set JavaDoc allSet = new HashSet JavaDoc(); // == allMap.values()
869
Map JavaDoc allMap = new HashMap JavaDoc(); //uncheckedPatterns union excludedPatterns union rolesPatterns.
870

871         SecurityConstraintType[] securityConstraintArray = webApp.getSecurityConstraintArray();
872         for (int i = 0; i < securityConstraintArray.length; i++) {
873             SecurityConstraintType securityConstraintType = securityConstraintArray[i];
874             Map JavaDoc currentPatterns;
875             if (securityConstraintType.isSetAuthConstraint()) {
876                 if (securityConstraintType.getAuthConstraint().getRoleNameArray().length == 0) {
877                     currentPatterns = excludedPatterns;
878                 } else {
879                     currentPatterns = rolesPatterns;
880                 }
881             } else {
882                 currentPatterns = uncheckedPatterns;
883             }
884
885             String JavaDoc transport = "";
886             if (securityConstraintType.isSetUserDataConstraint()) {
887                 transport = securityConstraintType.getUserDataConstraint().getTransportGuarantee().getStringValue().trim().toUpperCase();
888             }
889
890             WebResourceCollectionType[] webResourceCollectionTypeArray = securityConstraintType.getWebResourceCollectionArray();
891             for (int j = 0; j < webResourceCollectionTypeArray.length; j++) {
892                 WebResourceCollectionType webResourceCollectionType = webResourceCollectionTypeArray[j];
893                 UrlPatternType[] urlPatternTypeArray = webResourceCollectionType.getUrlPatternArray();
894                 for (int k = 0; k < urlPatternTypeArray.length; k++) {
895                     UrlPatternType urlPatternType = urlPatternTypeArray[k];
896                     //presumably, don't trim
897
String JavaDoc url = urlPatternType.getStringValue();
898                     URLPattern pattern = (URLPattern) currentPatterns.get(url);
899                     if (pattern == null) {
900                         pattern = new URLPattern(url);
901                         currentPatterns.put(url, pattern);
902                     }
903
904                     URLPattern allPattern = (URLPattern) allMap.get(url);
905                     if (allPattern == null) {
906                         allPattern = new URLPattern(url);
907                         allSet.add(allPattern);
908                         allMap.put(url, allPattern);
909                     }
910
911                     HttpMethodType[] httpMethodTypeArray = webResourceCollectionType.getHttpMethodArray();
912                     if (httpMethodTypeArray.length == 0) {
913                         pattern.addMethod("");
914                         allPattern.addMethod("");
915                     } else {
916                         for (int l = 0; l < httpMethodTypeArray.length; l++) {
917                             HttpMethodType httpMethodType = httpMethodTypeArray[l];
918                             //TODO is trim OK?
919
String JavaDoc method = httpMethodType.getStringValue().trim();
920                             pattern.addMethod(method);
921                             allPattern.addMethod(method);
922                         }
923                     }
924                     if (currentPatterns == rolesPatterns) {
925                         RoleNameType[] roleNameTypeArray = securityConstraintType.getAuthConstraint().getRoleNameArray();
926                         for (int l = 0; l < roleNameTypeArray.length; l++) {
927                             RoleNameType roleNameType = roleNameTypeArray[l];
928                             String JavaDoc role = roleNameType.getStringValue().trim();
929                             if (role.equals("*")) {
930                                 pattern.addAllRoles(securityRoles);
931                             } else {
932                                 pattern.addRole(role);
933                             }
934                         }
935                     }
936
937                     pattern.setTransport(transport);
938                 }
939             }
940         }
941
942         PermissionCollection JavaDoc excludedPermissions = new Permissions JavaDoc();
943         PermissionCollection JavaDoc uncheckedPermissions = new Permissions JavaDoc();
944
945         Iterator JavaDoc iter = excludedPatterns.keySet().iterator();
946         while (iter.hasNext()) {
947             URLPattern pattern = (URLPattern) excludedPatterns.get(iter.next());
948             String JavaDoc name = pattern.getQualifiedPattern(allSet);
949             String JavaDoc actions = pattern.getMethods();
950
951             excludedPermissions.add(new WebResourcePermission JavaDoc(name, actions));
952             excludedPermissions.add(new WebUserDataPermission JavaDoc(name, actions));
953         }
954
955         iter = rolesPatterns.keySet().iterator();
956         while (iter.hasNext()) {
957             URLPattern pattern = (URLPattern) rolesPatterns.get(iter.next());
958             String JavaDoc name = pattern.getQualifiedPattern(allSet);
959             String JavaDoc actions = pattern.getMethods();
960             WebResourcePermission JavaDoc permission = new WebResourcePermission JavaDoc(name, actions);
961
962             for (Iterator JavaDoc names = pattern.getRoles().iterator(); names.hasNext();) {
963                 String JavaDoc roleName = (String JavaDoc) names.next();
964                 addPermissionToRole(roleName, permission, rolePermissions);
965             }
966         }
967
968         iter = uncheckedPatterns.keySet().iterator();
969         while (iter.hasNext()) {
970             URLPattern pattern = (URLPattern) uncheckedPatterns.get(iter.next());
971             String JavaDoc name = pattern.getQualifiedPattern(allSet);
972             String JavaDoc actions = pattern.getMethods();
973
974             addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
975         }
976
977         iter = rolesPatterns.keySet().iterator();
978         while (iter.hasNext()) {
979             URLPattern pattern = (URLPattern) rolesPatterns.get(iter.next());
980             String JavaDoc name = pattern.getQualifiedPattern(allSet);
981             String JavaDoc actions = pattern.getMethodsWithTransport();
982
983             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
984         }
985
986         iter = uncheckedPatterns.keySet().iterator();
987         while (iter.hasNext()) {
988             URLPattern pattern = (URLPattern) uncheckedPatterns.get(iter.next());
989             String JavaDoc name = pattern.getQualifiedPattern(allSet);
990             String JavaDoc actions = pattern.getMethodsWithTransport();
991
992             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
993         }
994
995         /**
996          * A <code>WebResourcePermission</code> and a <code>WebUserDataPermission</code> must be instantiated for
997          * each <tt>url-pattern</tt> in the deployment descriptor and the default pattern "/", that is not combined
998          * by the <tt>web-resource-collection</tt> elements of the deployment descriptor with ever HTTP method
999          * value. The permission objects must be contructed using the qualified pattern as their name and with
1000         * actions defined by the subset of the HTTP methods that do not occur in combination with the pattern.
1001         * The resulting permissions that must be added to the unchecked policy statements by calling the
1002         * <code>addToUncheckedPolcy</code> method on the <code>PolicyConfiguration</code> object.
1003         */

1004        iter = allSet.iterator();
1005        while (iter.hasNext()) {
1006            URLPattern pattern = (URLPattern) iter.next();
1007            String JavaDoc name = pattern.getQualifiedPattern(allSet);
1008            String JavaDoc actions = pattern.getComplementedMethods();
1009
1010            if (actions.length() == 0) {
1011                continue;
1012            }
1013
1014            addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
1015            addOrUpdatePattern(uncheckedUserPatterns, name, actions);
1016        }
1017
1018        URLPattern pattern = new URLPattern("/");
1019        if (!allSet.contains(pattern)) {
1020            String JavaDoc name = pattern.getQualifiedPattern(allSet);
1021            String JavaDoc actions = pattern.getComplementedMethods();
1022
1023            addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
1024            addOrUpdatePattern(uncheckedUserPatterns, name, actions);
1025        }
1026
1027        //Create the uncheckedPermissions for WebResourcePermissions
1028
iter = uncheckedResourcePatterns.keySet().iterator();
1029        while (iter.hasNext()) {
1030            UncheckedItem item = (UncheckedItem) iter.next();
1031            String JavaDoc actions = (String JavaDoc) uncheckedResourcePatterns.get(item);
1032
1033            uncheckedPermissions.add(new WebResourcePermission JavaDoc(item.getName(), actions));
1034        }
1035        //Create the uncheckedPermissions for WebUserDataPermissions
1036
iter = uncheckedUserPatterns.keySet().iterator();
1037        while (iter.hasNext()) {
1038            UncheckedItem item = (UncheckedItem) iter.next();
1039            String JavaDoc actions = (String JavaDoc) uncheckedUserPatterns.get(item);
1040
1041            uncheckedPermissions.add(new WebUserDataPermission JavaDoc(item.getName(), actions));
1042        }
1043
1044        ComponentPermissions componentPermissions = new ComponentPermissions(excludedPermissions, uncheckedPermissions, rolePermissions);
1045        return componentPermissions;
1046
1047    }
1048
1049    private void addPermissionToRole(String JavaDoc roleName, Permission JavaDoc permission, Map JavaDoc rolePermissions) {
1050        PermissionCollection JavaDoc permissionsForRole = (PermissionCollection JavaDoc) rolePermissions.get(roleName);
1051        if (permissionsForRole == null) {
1052            permissionsForRole = new Permissions JavaDoc();
1053            rolePermissions.put(roleName, permissionsForRole);
1054        }
1055        permissionsForRole.add(permission);
1056    }
1057
1058    private void addOrUpdatePattern(Map JavaDoc patternMap, String JavaDoc name, String JavaDoc actions) {
1059        UncheckedItem item = new UncheckedItem(name, actions);
1060        String JavaDoc existingActions = (String JavaDoc) patternMap.get(item);
1061        if (existingActions != null) {
1062            patternMap.put(item, actions + "," + existingActions);
1063            return;
1064        }
1065
1066        patternMap.put(item, actions);
1067    }
1068
1069    private static Set JavaDoc collectRoleNames(WebAppType webApp) {
1070        Set JavaDoc roleNames = new HashSet JavaDoc();
1071
1072        SecurityRoleType[] securityRoles = webApp.getSecurityRoleArray();
1073        for (int i = 0; i < securityRoles.length; i++) {
1074            roleNames.add(securityRoles[i].getRoleName().getStringValue().trim());
1075        }
1076
1077        return roleNames;
1078    }
1079
1080    private static void getWebClassPath(EARContext earContext, WebModule webModule) {
1081        File JavaDoc baseDir = earContext.getTargetFile(webModule.getTargetPathURI());
1082        File JavaDoc webInfDir = new File JavaDoc(baseDir, "WEB-INF");
1083
1084        // check for a classes dir
1085
File JavaDoc classesDir = new File JavaDoc(webInfDir, "classes");
1086        if (classesDir.isDirectory()) {
1087            webModule.addToWebClasspath(webModule.getTargetPathURI().resolve(URI.create("WEB-INF/classes/")));
1088        }
1089
1090        // add all of the libs
1091
File JavaDoc libDir = new File JavaDoc(webInfDir, "lib");
1092        if (libDir.isDirectory()) {
1093            File JavaDoc[] libs = libDir.listFiles(new FileFilter JavaDoc() {
1094                public boolean accept(File JavaDoc file) {
1095                    return file.isFile() && file.getName().endsWith(".jar");
1096                }
1097            });
1098
1099            if (libs != null) {
1100                for (int i = 0; i < libs.length; i++) {
1101                    File JavaDoc lib = libs[i];
1102                    webModule.addToWebClasspath(webModule.getTargetPathURI().resolve(URI.create("WEB-INF/lib/" + lib.getName())));
1103                }
1104            }
1105        }
1106    }
1107
1108    private Map JavaDoc buildComponentContext(EARContext earContext, Module webModule, WebAppType webApp, JettyWebAppType jettyWebApp, UserTransaction JavaDoc userTransaction, ClassLoader JavaDoc cl) throws DeploymentException {
1109        return ENCConfigBuilder.buildComponentContext(earContext,
1110                webModule,
1111                userTransaction,
1112                webApp.getEnvEntryArray(),
1113                webApp.getEjbRefArray(), jettyWebApp.getEjbRefArray(),
1114                webApp.getEjbLocalRefArray(), jettyWebApp.getEjbLocalRefArray(),
1115                webApp.getResourceRefArray(), jettyWebApp.getResourceRefArray(),
1116                webApp.getResourceEnvRefArray(), jettyWebApp.getResourceEnvRefArray(),
1117                webApp.getMessageDestinationRefArray(),
1118                webApp.getServiceRefArray(), jettyWebApp.getServiceRefArray(),
1119                cl);
1120    }
1121
1122    private static void check(WebAppType webApp) throws DeploymentException {
1123        checkURLPattern(webApp);
1124        checkMultiplicities(webApp);
1125    }
1126
1127    private static void checkURLPattern(WebAppType webApp) throws DeploymentException {
1128
1129        FilterMappingType[] filterMappings = webApp.getFilterMappingArray();
1130        for (int i = 0; i < filterMappings.length; i++) {
1131            if (filterMappings[i].isSetUrlPattern()) {
1132                checkString(filterMappings[i].getUrlPattern().getStringValue());
1133            }
1134        }
1135
1136        ServletMappingType[] servletMappings = webApp.getServletMappingArray();
1137        for (int i = 0; i < servletMappings.length; i++) {
1138            checkString(servletMappings[i].getUrlPattern().getStringValue());
1139        }
1140
1141        SecurityConstraintType[] constraints = webApp.getSecurityConstraintArray();
1142        for (int i = 0; i < constraints.length; i++) {
1143            WebResourceCollectionType[] collections = constraints[i].getWebResourceCollectionArray();
1144            for (int j = 0; j < collections.length; j++) {
1145                UrlPatternType[] patterns = collections[j].getUrlPatternArray();
1146                for (int k = 0; k < patterns.length; k++) {
1147                    checkString(patterns[k].getStringValue());
1148                }
1149            }
1150        }
1151    }
1152
1153    private static void checkString(String JavaDoc pattern) throws DeploymentException {
1154        //j2ee_1_4.xsd explicitly requires preserving all whitespace. Do not trim.
1155
if (pattern.indexOf(0x0D) >= 0) throw new DeploymentException("<url-pattern> must not contain CR(#xD)");
1156        if (pattern.indexOf(0x0A) >= 0) throw new DeploymentException("<url-pattern> must not contain LF(#xA)");
1157    }
1158
1159    private static void checkMultiplicities(WebAppType webApp) throws DeploymentException {
1160        if (webApp.getSessionConfigArray().length > 1) throw new DeploymentException("Multiple <session-config> elements found");
1161        if (webApp.getJspConfigArray().length > 1) throw new DeploymentException("Multiple <jsp-config> elements found");
1162        if (webApp.getLoginConfigArray().length > 1) throw new DeploymentException("Multiple <login-config> elements found");
1163    }
1164
1165    class UncheckedItem {
1166        final static int NA = 0x00;
1167        final static int INTEGRAL = 0x01;
1168        final static int CONFIDENTIAL = 0x02;
1169
1170        private int transportType = NA;
1171        private String JavaDoc name;
1172
1173        public UncheckedItem(String JavaDoc name, String JavaDoc actions) {
1174            setName(name);
1175            setTransportType(actions);
1176        }
1177
1178        public boolean equals(Object JavaDoc o) {
1179            UncheckedItem item = (UncheckedItem) o;
1180            return item.getKey().equals(this.getKey());
1181        }
1182
1183        public String JavaDoc getKey() {
1184            return (name + transportType);
1185        }
1186
1187        public int hashCode() {
1188            return getKey().hashCode();
1189        }
1190
1191        public String JavaDoc getName() {
1192            return name;
1193        }
1194
1195        public void setName(String JavaDoc name) {
1196            this.name = name;
1197        }
1198
1199        public int getTransportType() {
1200            return transportType;
1201        }
1202
1203        public void setTransportType(String JavaDoc actions) {
1204            String JavaDoc[] tokens = actions.split(":", 2);
1205            if (tokens.length == 2) {
1206                if (tokens[1].equals("INTEGRAL")) {
1207                    this.transportType = INTEGRAL;
1208                } else if (tokens[1].equals("CONFIDENTIAL")) {
1209                    this.transportType = CONFIDENTIAL;
1210                }
1211            }
1212        }
1213    }
1214
1215    public static final GBeanInfo GBEAN_INFO;
1216
1217    static {
1218        GBeanInfoBuilder infoBuilder = new GBeanInfoBuilder(JettyModuleBuilder.class, NameFactory.MODULE_BUILDER);
1219        infoBuilder.addAttribute("defaultParentId", URI JavaDoc.class, true);
1220        infoBuilder.addAttribute("defaultSessionTimeoutSeconds", Integer JavaDoc.class, true);
1221        infoBuilder.addAttribute("defaultWelcomeFiles", List JavaDoc.class, true);
1222        infoBuilder.addAttribute("jettyContainerObjectName", ObjectName JavaDoc.class, true);
1223        infoBuilder.addAttribute("defaultServlets", ObjectName JavaDoc.class, true);
1224        infoBuilder.addAttribute("defaultFilters", ObjectName JavaDoc.class, true);
1225        infoBuilder.addAttribute("defaultFilterMappings", ObjectName JavaDoc.class, true);
1226        infoBuilder.addAttribute("pojoWebServiceTemplate", ObjectName JavaDoc.class, true);
1227        infoBuilder.addReference("WebServiceBuilder", WebServiceBuilder.class, NameFactory.MODULE_BUILDER);
1228        infoBuilder.addReference("Repository", Repository.class, NameFactory.GERONIMO_SERVICE);
1229        infoBuilder.addAttribute("kernel", Kernel.class, false);
1230        infoBuilder.addInterface(ModuleBuilder.class);
1231
1232        infoBuilder.setConstructor(new String JavaDoc[]{
1233            "defaultParentId",
1234            "defaultSessionTimeoutSeconds",
1235            "defaultWelcomeFiles",
1236            "jettyContainerObjectName",
1237            "defaultServlets",
1238            "defaultFilters",
1239            "defaultFilterMappings",
1240            "pojoWebServiceTemplate",
1241            "WebServiceBuilder",
1242            "Repository",
1243            "kernel"});
1244        GBEAN_INFO = infoBuilder.getBeanInfo();
1245    }
1246
1247    public static GBeanInfo getGBeanInfo() {
1248        return GBEAN_INFO;
1249    }
1250
1251}
1252
Popular Tags