KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > web25 > deployment > AbstractWebModuleBuilder


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. 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.web25.deployment;
19
20 import java.io.File JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.net.URI JavaDoc;
23 import java.net.URISyntaxException JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.security.Permission JavaDoc;
26 import java.security.PermissionCollection JavaDoc;
27 import java.security.Permissions JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.util.jar.JarFile JavaDoc;
38 import java.util.zip.ZipEntry JavaDoc;
39
40 import javax.security.jacc.WebResourcePermission JavaDoc;
41 import javax.security.jacc.WebRoleRefPermission JavaDoc;
42 import javax.security.jacc.WebUserDataPermission JavaDoc;
43 import javax.xml.namespace.QName JavaDoc;
44
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47 import org.apache.geronimo.common.DeploymentException;
48 import org.apache.geronimo.deployment.util.DeploymentUtil;
49 import org.apache.geronimo.deployment.ModuleIDBuilder;
50 import org.apache.geronimo.deployment.NamespaceDrivenBuilderCollection;
51 import org.apache.geronimo.deployment.xmlbeans.XmlBeansUtil;
52 import org.apache.geronimo.deployment.xbeans.ServiceDocument;
53 import org.apache.geronimo.gbean.AbstractName;
54 import org.apache.geronimo.gbean.AbstractNameQuery;
55 import org.apache.geronimo.j2ee.deployment.EARContext;
56 import org.apache.geronimo.j2ee.deployment.Module;
57 import org.apache.geronimo.j2ee.deployment.ModuleBuilder;
58 import org.apache.geronimo.j2ee.deployment.NamingBuilder;
59 import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
60 import org.apache.geronimo.kernel.Kernel;
61 import org.apache.geronimo.kernel.Naming;
62 import org.apache.geronimo.kernel.config.ConfigurationModuleType;
63 import org.apache.geronimo.kernel.config.ConfigurationStore;
64 import org.apache.geronimo.kernel.repository.Artifact;
65 import org.apache.geronimo.kernel.repository.Environment;
66 import org.apache.geronimo.kernel.repository.ImportType;
67 import org.apache.geronimo.naming.deployment.ResourceEnvironmentSetter;
68 import org.apache.geronimo.security.jacc.ComponentPermissions;
69 import org.apache.geronimo.security.util.URLPattern;
70 import org.apache.geronimo.xbeans.javaee.FilterMappingType;
71 import org.apache.geronimo.xbeans.javaee.RoleNameType;
72 import org.apache.geronimo.xbeans.javaee.SecurityConstraintType;
73 import org.apache.geronimo.xbeans.javaee.SecurityRoleRefType;
74 import org.apache.geronimo.xbeans.javaee.SecurityRoleType;
75 import org.apache.geronimo.xbeans.javaee.ServletMappingType;
76 import org.apache.geronimo.xbeans.javaee.ServletType;
77 import org.apache.geronimo.xbeans.javaee.UrlPatternType;
78 import org.apache.geronimo.xbeans.javaee.WebAppType;
79 import org.apache.geronimo.xbeans.javaee.WebResourceCollectionType;
80 import org.apache.geronimo.xbeans.javaee.WebAppDocument;
81 import org.apache.geronimo.xbeans.geronimo.j2ee.GerSecurityDocument;
82 import org.apache.geronimo.schema.SchemaConversionUtils;
83 import org.apache.xmlbeans.XmlObject;
84 import org.apache.xmlbeans.XmlException;
85 import org.apache.xmlbeans.XmlCursor;
86 import org.apache.xmlbeans.XmlDocumentProperties;
87
88 /**
89  * @version $Rev: 482336 $ $Date: 2006-12-04 15:12:19 -0500 (Mon, 04 Dec 2006) $
90  */

91 public abstract class AbstractWebModuleBuilder implements ModuleBuilder {
92     private static final Log log = LogFactory.getLog(AbstractWebModuleBuilder.class);
93
94     private static final QName JavaDoc TAGLIB = new QName JavaDoc(SchemaConversionUtils.JAVAEE_NAMESPACE, "taglib");
95
96     private static final String JavaDoc LINE_SEP = System.getProperty("line.separator");
97
98     protected static final AbstractNameQuery MANAGED_CONNECTION_FACTORY_PATTERN;
99     private static final AbstractNameQuery ADMIN_OBJECT_PATTERN;
100     protected static final AbstractNameQuery STATELESS_SESSION_BEAN_PATTERN;
101     protected static final AbstractNameQuery STATEFUL_SESSION_BEAN_PATTERN;
102     protected static final AbstractNameQuery ENTITY_BEAN_PATTERN;
103     protected final Kernel kernel;
104     protected final NamespaceDrivenBuilderCollection securityBuilders;
105     protected final NamespaceDrivenBuilderCollection serviceBuilders;
106     protected final ResourceEnvironmentSetter resourceEnvironmentSetter;
107
108     protected final NamingBuilder namingBuilders;
109
110     private static final QName JavaDoc SECURITY_QNAME = GerSecurityDocument.type.getDocumentElementName();
111     private static final QName JavaDoc SERVICE_QNAME = ServiceDocument.type.getDocumentElementName();
112
113     /**
114      * Manifest classpath entries in a war configuration must be resolved relative to the war configuration, not the
115      * enclosing ear configuration. Resolving relative to he war configuration using this offset produces the same
116      * effect as URI.create(module.targetPath()).resolve(mcpEntry) executed in the ear configuration.
117      */

118     private static final URI JavaDoc RELATIVE_MODULE_BASE_URI = URI.create("../");
119
120     protected AbstractWebModuleBuilder(Kernel kernel, Collection JavaDoc securityBuilders, Collection JavaDoc serviceBuilders, NamingBuilder namingBuilders, ResourceEnvironmentSetter resourceEnvironmentSetter) {
121         this.kernel = kernel;
122         this.securityBuilders = new NamespaceDrivenBuilderCollection(securityBuilders, SECURITY_QNAME);
123         this.serviceBuilders = new NamespaceDrivenBuilderCollection(serviceBuilders, SERVICE_QNAME);
124         this.namingBuilders = namingBuilders;
125         this.resourceEnvironmentSetter = resourceEnvironmentSetter;
126     }
127
128     static {
129         MANAGED_CONNECTION_FACTORY_PATTERN = new AbstractNameQuery(null, Collections.singletonMap(NameFactory.J2EE_TYPE, NameFactory.JCA_MANAGED_CONNECTION_FACTORY));
130         ADMIN_OBJECT_PATTERN = new AbstractNameQuery(null, Collections.singletonMap(NameFactory.J2EE_TYPE, NameFactory.JCA_ADMIN_OBJECT));
131         STATELESS_SESSION_BEAN_PATTERN = new AbstractNameQuery(null, Collections.singletonMap(NameFactory.J2EE_TYPE, NameFactory.STATELESS_SESSION_BEAN));
132         STATEFUL_SESSION_BEAN_PATTERN = new AbstractNameQuery(null, Collections.singletonMap(NameFactory.J2EE_TYPE, NameFactory.STATEFUL_SESSION_BEAN));
133         ENTITY_BEAN_PATTERN = new AbstractNameQuery(null, Collections.singletonMap(NameFactory.J2EE_TYPE, NameFactory.ENTITY_BEAN));
134
135     }
136
137     public NamingBuilder getNamingBuilders() {
138         return namingBuilders;
139     }
140
141     //TODO configid these need to be converted to ReferencePatterns
142
protected Set JavaDoc findGBeanDependencies(EARContext earContext) {
143         Set JavaDoc dependencies = new HashSet JavaDoc();
144         dependencies.addAll(earContext.listGBeans(MANAGED_CONNECTION_FACTORY_PATTERN));
145         dependencies.addAll(earContext.listGBeans(ADMIN_OBJECT_PATTERN));
146         dependencies.addAll(earContext.listGBeans(STATELESS_SESSION_BEAN_PATTERN));
147         dependencies.addAll(earContext.listGBeans(STATEFUL_SESSION_BEAN_PATTERN));
148         dependencies.addAll(earContext.listGBeans(ENTITY_BEAN_PATTERN));
149         return dependencies;
150     }
151
152     public Module createModule(File JavaDoc plan, JarFile JavaDoc moduleFile, Naming naming, ModuleIDBuilder idBuilder) throws DeploymentException {
153         return createModule(plan, moduleFile, ".", null, true, null, null, naming, idBuilder);
154     }
155
156     public Module createModule(Object JavaDoc plan, JarFile JavaDoc moduleFile, String JavaDoc targetPath, URL JavaDoc specDDUrl, Environment environment, Object JavaDoc moduleContextInfo, AbstractName earName, Naming naming, ModuleIDBuilder idBuilder) throws DeploymentException {
157         return createModule(plan, moduleFile, targetPath, specDDUrl, false, (String JavaDoc) moduleContextInfo, earName, naming, idBuilder);
158     }
159
160     protected abstract Module createModule(Object JavaDoc plan, JarFile JavaDoc moduleFile, String JavaDoc targetPath, URL JavaDoc specDDUrl, boolean standAlone, String JavaDoc contextRoot, AbstractName earName, Naming naming, ModuleIDBuilder idBuilder) throws DeploymentException;
161
162     /**
163      * Some servlets will have multiple url patterns. However, webservice servlets
164      * will only have one, which is what this method is intended for.
165      *
166      * @param webApp
167      * @param contextRoot
168      * @return map of servlet names to path mapped to them. Possibly inaccurate except for web services.
169      */

170     protected Map JavaDoc buildServletNameToPathMap(WebAppType webApp, String JavaDoc contextRoot) {
171         contextRoot = "/" + contextRoot;
172         Map JavaDoc map = new HashMap JavaDoc();
173         ServletMappingType[] servletMappings = webApp.getServletMappingArray();
174         for (int j = 0; j < servletMappings.length; j++) {
175             ServletMappingType servletMapping = servletMappings[j];
176             String JavaDoc servletName = servletMapping.getServletName().getStringValue().trim();
177             UrlPatternType[] urlPatterns = servletMapping.getUrlPatternArray();
178
179             for (int i=0; urlPatterns != null && (i < urlPatterns.length); i++) {
180                 map.put(servletName, contextRoot +urlPatterns[i].getStringValue().trim());
181             }
182         }
183         return map;
184     }
185
186     protected String JavaDoc determineDefaultContextRoot(WebAppType webApp, boolean isStandAlone, JarFile JavaDoc moduleFile, String JavaDoc targetPath) {
187
188         if (webApp != null && webApp.getId() != null) {
189             return webApp.getId();
190         }
191
192         if (isStandAlone) {
193             // default configId is based on the moduleFile name
194
return "/" + trimPath(new File JavaDoc(moduleFile.getName()).getName());
195         }
196
197         // default configId is based on the module uri from the application.xml
198
return trimPath(targetPath);
199     }
200
201     private String JavaDoc trimPath(String JavaDoc path) {
202
203         if (path == null) {
204             return null;
205         }
206
207         if (path.endsWith(".war")) {
208             path = path.substring(0, path.length() - 4);
209         }
210         if (path.endsWith("/")) {
211             path = path.substring(0, path.length() - 1);
212         }
213
214         return path;
215     }
216
217     public void installModule(JarFile JavaDoc earFile, EARContext earContext, Module module, Collection JavaDoc configurationStores, ConfigurationStore targetConfigurationStore, Collection JavaDoc repositories) throws DeploymentException {
218         EARContext moduleContext;
219         if (module.isStandAlone()) {
220             moduleContext = earContext;
221         } else {
222             Environment environment = module.getEnvironment();
223             Artifact earConfigId = earContext.getConfigID();
224             Artifact configId = new Artifact(earConfigId.getGroupId(), earConfigId.getArtifactId() + "_" + module.getTargetPath(), earConfigId.getVersion(), "car");
225             environment.setConfigId(configId);
226             environment.addDependency(earConfigId, ImportType.ALL);
227             File JavaDoc configurationDir = new File JavaDoc(earContext.getBaseDir(), module.getTargetPath());
228             configurationDir.mkdirs();
229
230             // construct the web app deployment context... this is the same class used by the ear context
231
try {
232                 File JavaDoc inPlaceConfigurationDir = null;
233                 if (null != earContext.getInPlaceConfigurationDir()) {
234                     inPlaceConfigurationDir = new File JavaDoc(earContext.getInPlaceConfigurationDir(), module.getTargetPath());
235                 }
236                 moduleContext = new EARContext(configurationDir,
237                         inPlaceConfigurationDir,
238                         environment,
239                         ConfigurationModuleType.WAR,
240                         module.getModuleName(),
241                         earContext);
242             } catch (DeploymentException e) {
243                 cleanupConfigurationDir(configurationDir);
244                 throw e;
245             }
246         }
247         module.setEarContext(moduleContext);
248         module.setRootEarContext(earContext);
249
250         try {
251             // add the warfile's content to the configuration
252
JarFile JavaDoc warFile = module.getModuleFile();
253             Enumeration JavaDoc entries = warFile.entries();
254             while (entries.hasMoreElements()) {
255                 ZipEntry JavaDoc entry = (ZipEntry JavaDoc) entries.nextElement();
256                 URI JavaDoc targetPath = new URI JavaDoc(null, entry.getName(), null);
257                 if (entry.getName().equals("WEB-INF/web.xml")) {
258                     moduleContext.addFile(targetPath, module.getOriginalSpecDD());
259                 } else if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().endsWith(".jar")) {
260                     moduleContext.addInclude(targetPath, warFile, entry);
261                 } else {
262                     moduleContext.addFile(targetPath, warFile, entry);
263                 }
264             }
265
266             //always add WEB-INF/classes to the classpath regardless of whether
267
//any classes exist
268
moduleContext.getConfiguration().addToClassPath("WEB-INF/classes/");
269
270             // add the manifest classpath entries declared in the war to the class loader
271
// we have to explicitly add these since we are unpacking the web module
272
// and the url class loader will not pick up a manifest from an unpacked dir
273
moduleContext.addManifestClassPath(warFile, RELATIVE_MODULE_BASE_URI);
274
275         } catch (IOException JavaDoc e) {
276             throw new DeploymentException("Problem deploying war", e);
277         } catch (URISyntaxException JavaDoc e) {
278             throw new DeploymentException("Could not construct URI for location of war entry", e);
279         } finally {
280             if (!module.isStandAlone()) {
281                 try {
282                     moduleContext.flush();
283                 } catch (IOException JavaDoc e) {
284                     throw new DeploymentException("Problem closing war context", e);
285                 }
286             }
287         }
288     }
289
290     protected WebAppDocument convertToServletSchema(XmlObject xmlObject) throws XmlException {
291
292         String JavaDoc schemaLocationURL = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd";
293         String JavaDoc version = "2.5";
294         XmlCursor cursor = xmlObject.newCursor();
295         try {
296             cursor.toStartDoc();
297             cursor.toFirstChild();
298             if ("http://java.sun.com/xml/ns/j2ee".equals(cursor.getName().getNamespaceURI())) {
299                 SchemaConversionUtils.convertSchemaVersion(cursor, SchemaConversionUtils.JAVAEE_NAMESPACE, schemaLocationURL, version);
300                 XmlObject result = xmlObject.changeType(WebAppDocument.type);
301                 XmlBeansUtil.validateDD(result);
302                 return (WebAppDocument) result;
303             }
304
305             if ("http://java.sun.com/xml/ns/javaee".equals(cursor.getName().getNamespaceURI())) {
306                 SchemaConversionUtils.convertSchemaVersion(cursor, SchemaConversionUtils.JAVAEE_NAMESPACE, schemaLocationURL, version);
307                 XmlObject result = xmlObject.changeType(WebAppDocument.type);
308                 XmlBeansUtil.validateDD(result);
309                 return (WebAppDocument) result;
310             }
311
312             //otherwise assume DTD
313
XmlDocumentProperties xmlDocumentProperties = cursor.documentProperties();
314             String JavaDoc publicId = xmlDocumentProperties.getDoctypePublicId();
315             if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(publicId) ||
316                     "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN".equals(publicId)) {
317                 XmlCursor moveable = xmlObject.newCursor();
318                 try {
319                     moveable.toStartDoc();
320                     moveable.toFirstChild();
321
322                     SchemaConversionUtils.convertToSchema(cursor, SchemaConversionUtils.JAVAEE_NAMESPACE, schemaLocationURL, version);
323                     cursor.toStartDoc();
324                     cursor.toChild(SchemaConversionUtils.JAVAEE_NAMESPACE, "web-app");
325                     cursor.toFirstChild();
326                     SchemaConversionUtils.convertToDescriptionGroup(SchemaConversionUtils.JAVAEE_NAMESPACE, cursor, moveable);
327                     SchemaConversionUtils.convertToJNDIEnvironmentRefsGroup(SchemaConversionUtils.JAVAEE_NAMESPACE, cursor, moveable);
328                     cursor.push();
329                     if (cursor.toNextSibling(TAGLIB)) {
330                         cursor.toPrevSibling();
331                         moveable.toCursor(cursor);
332                         cursor.beginElement("jsp-config", SchemaConversionUtils.JAVAEE_NAMESPACE);
333                         while (moveable.toNextSibling(TAGLIB)) {
334                             moveable.moveXml(cursor);
335                         }
336                     }
337                     cursor.pop();
338                     do {
339                         String JavaDoc name = cursor.getName().getLocalPart();
340                         if ("filter".equals(name) || "servlet".equals(name) || "context-param".equals(name)) {
341                             cursor.push();
342                             cursor.toFirstChild();
343                             SchemaConversionUtils.convertToDescriptionGroup(SchemaConversionUtils.JAVAEE_NAMESPACE, cursor, moveable);
344                             while (cursor.toNextSibling(SchemaConversionUtils.JAVAEE_NAMESPACE, "init-param")) {
345                                 cursor.push();
346                                 cursor.toFirstChild();
347                                 SchemaConversionUtils.convertToDescriptionGroup(SchemaConversionUtils.JAVAEE_NAMESPACE, cursor, moveable);
348                                 cursor.pop();
349                             }
350                             cursor.pop();
351                         }
352                     } while (cursor.toNextSibling());
353                 } finally {
354                     moveable.dispose();
355                 }
356             }
357         } finally {
358             cursor.dispose();
359         }
360         XmlObject result = xmlObject.changeType(WebAppDocument.type);
361         if (result != null) {
362             XmlBeansUtil.validateDD(result);
363             return (WebAppDocument) result;
364         }
365         XmlBeansUtil.validateDD(xmlObject);
366         return (WebAppDocument) xmlObject;
367     }
368
369
370     protected void addUnmappedJSPPermissions(Set JavaDoc securityRoles, Map JavaDoc rolePermissions) {
371         for (Iterator JavaDoc iter = securityRoles.iterator(); iter.hasNext();) {
372             String JavaDoc roleName = (String JavaDoc) iter.next();
373             addPermissionToRole(roleName, new WebRoleRefPermission JavaDoc("", roleName), rolePermissions);
374         }
375     }
376
377     protected ComponentPermissions buildSpecSecurityConfig(WebAppType webApp, Set JavaDoc securityRoles, Map JavaDoc rolePermissions) {
378         Map JavaDoc uncheckedPatterns = new HashMap JavaDoc();
379         Map JavaDoc uncheckedResourcePatterns = new HashMap JavaDoc();
380         Map JavaDoc uncheckedUserPatterns = new HashMap JavaDoc();
381         Map JavaDoc excludedPatterns = new HashMap JavaDoc();
382         Map JavaDoc rolesPatterns = new HashMap JavaDoc();
383         Set JavaDoc allSet = new HashSet JavaDoc(); // == allMap.values()
384
Map JavaDoc allMap = new HashMap JavaDoc(); //uncheckedPatterns union excludedPatterns union rolesPatterns.
385

386         SecurityConstraintType[] securityConstraintArray = webApp.getSecurityConstraintArray();
387         for (int i = 0; i < securityConstraintArray.length; i++) {
388             SecurityConstraintType securityConstraintType = securityConstraintArray[i];
389             Map JavaDoc currentPatterns;
390             if (securityConstraintType.isSetAuthConstraint()) {
391                 if (securityConstraintType.getAuthConstraint().getRoleNameArray().length == 0) {
392                     currentPatterns = excludedPatterns;
393                 } else {
394                     currentPatterns = rolesPatterns;
395                 }
396             } else {
397                 currentPatterns = uncheckedPatterns;
398             }
399
400             String JavaDoc transport = "";
401             if (securityConstraintType.isSetUserDataConstraint()) {
402                 transport = securityConstraintType.getUserDataConstraint().getTransportGuarantee().getStringValue().trim().toUpperCase();
403             }
404
405             WebResourceCollectionType[] webResourceCollectionTypeArray = securityConstraintType.getWebResourceCollectionArray();
406             for (int j = 0; j < webResourceCollectionTypeArray.length; j++) {
407                 WebResourceCollectionType webResourceCollectionType = webResourceCollectionTypeArray[j];
408                 UrlPatternType[] urlPatternTypeArray = webResourceCollectionType.getUrlPatternArray();
409                 for (int k = 0; k < urlPatternTypeArray.length; k++) {
410                     UrlPatternType urlPatternType = urlPatternTypeArray[k];
411                     String JavaDoc url = urlPatternType.getStringValue().trim();
412                     URLPattern pattern = (URLPattern) currentPatterns.get(url);
413                     if (pattern == null) {
414                         pattern = new URLPattern(url);
415                         currentPatterns.put(url, pattern);
416                     }
417
418                     URLPattern allPattern = (URLPattern) allMap.get(url);
419                     if (allPattern == null) {
420                         allPattern = new URLPattern(url);
421                         allSet.add(allPattern);
422                         allMap.put(url, allPattern);
423                     }
424
425                     String JavaDoc[] httpMethodTypeArray = webResourceCollectionType.getHttpMethodArray();
426                     if (httpMethodTypeArray.length == 0) {
427                         pattern.addMethod("");
428                         allPattern.addMethod("");
429                     } else {
430                         for (int l = 0; l < httpMethodTypeArray.length; l++) {
431                             //TODO is trim OK?
432
String JavaDoc method = (httpMethodTypeArray[l]==null?null:httpMethodTypeArray[l].trim());
433                             if (method != null) {
434                                 pattern.addMethod(method);
435                                 allPattern.addMethod(method);
436                             }
437                         }
438                     }
439                     if (currentPatterns == rolesPatterns) {
440                         RoleNameType[] roleNameTypeArray = securityConstraintType.getAuthConstraint().getRoleNameArray();
441                         for (int l = 0; l < roleNameTypeArray.length; l++) {
442                             RoleNameType roleNameType = roleNameTypeArray[l];
443                             String JavaDoc role = roleNameType.getStringValue().trim();
444                             if (role.equals("*")) {
445                                 pattern.addAllRoles(securityRoles);
446                             } else {
447                                 pattern.addRole(role);
448                             }
449                         }
450                     }
451
452                     pattern.setTransport(transport);
453                 }
454             }
455         }
456
457         PermissionCollection JavaDoc excludedPermissions = new Permissions JavaDoc();
458         PermissionCollection JavaDoc uncheckedPermissions = new Permissions JavaDoc();
459
460         Iterator JavaDoc iter = excludedPatterns.keySet().iterator();
461         while (iter.hasNext()) {
462             URLPattern pattern = (URLPattern) excludedPatterns.get(iter.next());
463             String JavaDoc name = pattern.getQualifiedPattern(allSet);
464             String JavaDoc actions = pattern.getMethods();
465
466             excludedPermissions.add(new WebResourcePermission JavaDoc(name, actions));
467             excludedPermissions.add(new WebUserDataPermission JavaDoc(name, actions));
468         }
469
470         iter = rolesPatterns.keySet().iterator();
471         while (iter.hasNext()) {
472             URLPattern pattern = (URLPattern) rolesPatterns.get(iter.next());
473             String JavaDoc name = pattern.getQualifiedPattern(allSet);
474             String JavaDoc actions = pattern.getMethods();
475             WebResourcePermission JavaDoc permission = new WebResourcePermission JavaDoc(name, actions);
476
477             for (Iterator JavaDoc names = pattern.getRoles().iterator(); names.hasNext();) {
478                 String JavaDoc roleName = (String JavaDoc) names.next();
479                 addPermissionToRole(roleName, permission, rolePermissions);
480             }
481         }
482
483         iter = uncheckedPatterns.keySet().iterator();
484         while (iter.hasNext()) {
485             URLPattern pattern = (URLPattern) uncheckedPatterns.get(iter.next());
486             String JavaDoc name = pattern.getQualifiedPattern(allSet);
487             String JavaDoc actions = pattern.getMethods();
488
489             addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
490         }
491
492         iter = rolesPatterns.keySet().iterator();
493         while (iter.hasNext()) {
494             URLPattern pattern = (URLPattern) rolesPatterns.get(iter.next());
495             String JavaDoc name = pattern.getQualifiedPattern(allSet);
496             String JavaDoc actions = pattern.getMethodsWithTransport();
497
498             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
499         }
500
501         iter = uncheckedPatterns.keySet().iterator();
502         while (iter.hasNext()) {
503             URLPattern pattern = (URLPattern) uncheckedPatterns.get(iter.next());
504             String JavaDoc name = pattern.getQualifiedPattern(allSet);
505             String JavaDoc actions = pattern.getMethodsWithTransport();
506
507             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
508         }
509
510         /**
511          * A <code>WebResourcePermission</code> and a <code>WebUserDataPermission</code> must be instantiated for
512          * each <tt>url-pattern</tt> in the deployment descriptor and the default pattern "/", that is not combined
513          * by the <tt>web-resource-collection</tt> elements of the deployment descriptor with ever HTTP method
514          * value. The permission objects must be contructed using the qualified pattern as their name and with
515          * actions defined by the subset of the HTTP methods that do not occur in combination with the pattern.
516          * The resulting permissions that must be added to the unchecked policy statements by calling the
517          * <code>addToUncheckedPolcy</code> method on the <code>PolicyConfiguration</code> object.
518          */

519         iter = allSet.iterator();
520         while (iter.hasNext()) {
521             URLPattern pattern = (URLPattern) iter.next();
522             String JavaDoc name = pattern.getQualifiedPattern(allSet);
523             String JavaDoc actions = pattern.getComplementedMethods();
524
525             if (actions.length() == 0) {
526                 continue;
527             }
528
529             addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
530             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
531         }
532
533         URLPattern pattern = new URLPattern("/");
534         if (!allSet.contains(pattern)) {
535             String JavaDoc name = pattern.getQualifiedPattern(allSet);
536             String JavaDoc actions = pattern.getComplementedMethods();
537
538             addOrUpdatePattern(uncheckedResourcePatterns, name, actions);
539             addOrUpdatePattern(uncheckedUserPatterns, name, actions);
540         }
541
542         //Create the uncheckedPermissions for WebResourcePermissions
543
iter = uncheckedResourcePatterns.keySet().iterator();
544         while (iter.hasNext()) {
545             UncheckedItem item = (UncheckedItem) iter.next();
546             String JavaDoc actions = (String JavaDoc) uncheckedResourcePatterns.get(item);
547
548             uncheckedPermissions.add(new WebResourcePermission JavaDoc(item.getName(), actions));
549         }
550         //Create the uncheckedPermissions for WebUserDataPermissions
551
iter = uncheckedUserPatterns.keySet().iterator();
552         while (iter.hasNext()) {
553             UncheckedItem item = (UncheckedItem) iter.next();
554             String JavaDoc actions = (String JavaDoc) uncheckedUserPatterns.get(item);
555
556             uncheckedPermissions.add(new WebUserDataPermission JavaDoc(item.getName(), actions));
557         }
558
559         return new ComponentPermissions(excludedPermissions, uncheckedPermissions, rolePermissions);
560
561     }
562
563     protected void addPermissionToRole(String JavaDoc roleName, Permission JavaDoc permission, Map JavaDoc rolePermissions) {
564         PermissionCollection JavaDoc permissionsForRole = (PermissionCollection JavaDoc) rolePermissions.get(roleName);
565         if (permissionsForRole == null) {
566             permissionsForRole = new Permissions JavaDoc();
567             rolePermissions.put(roleName, permissionsForRole);
568         }
569         permissionsForRole.add(permission);
570     }
571
572     private void addOrUpdatePattern(Map JavaDoc patternMap, String JavaDoc name, String JavaDoc actions) {
573         UncheckedItem item = new UncheckedItem(name, actions);
574         String JavaDoc existingActions = (String JavaDoc) patternMap.get(item);
575         if (existingActions != null) {
576             patternMap.put(item, actions + "," + existingActions);
577             return;
578         }
579
580         patternMap.put(item, actions);
581     }
582
583     protected static Set JavaDoc collectRoleNames(WebAppType webApp) {
584         Set JavaDoc roleNames = new HashSet JavaDoc();
585
586         SecurityRoleType[] securityRoles = webApp.getSecurityRoleArray();
587         for (int i = 0; i < securityRoles.length; i++) {
588             roleNames.add(securityRoles[i].getRoleName().getStringValue().trim());
589         }
590
591         return roleNames;
592     }
593
594     protected static void check(WebAppType webApp) throws DeploymentException {
595         checkURLPattern(webApp);
596         checkMultiplicities(webApp);
597     }
598
599     private static void checkURLPattern(WebAppType webApp) throws DeploymentException {
600
601         FilterMappingType[] filterMappings = webApp.getFilterMappingArray();
602         for (int i = 0; i < filterMappings.length; i++) {
603              UrlPatternType[] urlPatterns = filterMappings[i].getUrlPatternArray();
604             for (int j=0; (urlPatterns != null) && (j < urlPatterns.length); j++) {
605                 checkString(urlPatterns[j].getStringValue().trim());
606             }
607         }
608
609         ServletMappingType[] servletMappings = webApp.getServletMappingArray();
610         for (int i = 0; i < servletMappings.length; i++) {
611             UrlPatternType[] urlPatterns = servletMappings[i].getUrlPatternArray();
612             for (int j=0; (urlPatterns != null) && (j < urlPatterns.length); j++) {
613                 checkString(urlPatterns[j].getStringValue().trim());
614             }
615         }
616
617         SecurityConstraintType[] constraints = webApp.getSecurityConstraintArray();
618         for (int i = 0; i < constraints.length; i++) {
619             WebResourceCollectionType[] collections = constraints[i].getWebResourceCollectionArray();
620             for (int j = 0; j < collections.length; j++) {
621                 UrlPatternType[] patterns = collections[j].getUrlPatternArray();
622                 for (int k = 0; k < patterns.length; k++) {
623                     checkString(patterns[k].getStringValue().trim());
624                 }
625             }
626         }
627     }
628
629     protected static void checkString(String JavaDoc pattern) throws DeploymentException {
630         //j2ee_1_4.xsd explicitly requires preserving all whitespace. Do not trim.
631
if (pattern.indexOf(0x0D) >= 0) throw new DeploymentException("<url-pattern> must not contain CR(#xD)");
632         if (pattern.indexOf(0x0A) >= 0) throw new DeploymentException("<url-pattern> must not contain LF(#xA)");
633     }
634
635     private static void checkMultiplicities(WebAppType webApp) throws DeploymentException {
636         if (webApp.getSessionConfigArray().length > 1) throw new DeploymentException("Multiple <session-config> elements found");
637         if (webApp.getJspConfigArray().length > 1) throw new DeploymentException("Multiple <jsp-config> elements found");
638         if (webApp.getLoginConfigArray().length > 1) throw new DeploymentException("Multiple <login-config> elements found");
639     }
640
641     private boolean cleanupConfigurationDir(File JavaDoc configurationDir)
642     {
643         LinkedList JavaDoc cannotBeDeletedList = new LinkedList JavaDoc();
644
645         if (!DeploymentUtil.recursiveDelete(configurationDir,cannotBeDeletedList)) {
646             // Output a message to help user track down file problem
647
log.warn("Unable to delete " + cannotBeDeletedList.size() +
648                     " files while recursively deleting directory "
649                     + configurationDir + LINE_SEP +
650                     "The first file that could not be deleted was:" + LINE_SEP + " "+
651                     ( !cannotBeDeletedList.isEmpty() ? cannotBeDeletedList.getFirst() : "") );
652             return false;
653         }
654         return true;
655     }
656
657     protected void processRoleRefPermissions(ServletType servletType, Set JavaDoc securityRoles, Map JavaDoc rolePermissions) {
658         String JavaDoc servletName = servletType.getServletName().getStringValue().trim();
659         //WebRoleRefPermissions
660
SecurityRoleRefType[] securityRoleRefTypeArray = servletType.getSecurityRoleRefArray();
661         Set JavaDoc unmappedRoles = new HashSet JavaDoc(securityRoles);
662         for (int j = 0; j < securityRoleRefTypeArray.length; j++) {
663             SecurityRoleRefType securityRoleRefType = securityRoleRefTypeArray[j];
664             String JavaDoc roleName = securityRoleRefType.getRoleName().getStringValue().trim();
665             String JavaDoc roleLink = securityRoleRefType.getRoleLink().getStringValue().trim();
666             //jacc 3.1.3.2
667
/* The name of the WebRoleRefPermission must be the servlet-name in whose
668             * context the security-role-ref is defined. The actions of the WebRoleRefPermission
669             * must be the value of the role-name (that is the reference), appearing in the security-role-ref.
670             * The deployment tools must call the addToRole method on the PolicyConfiguration object to add the
671             * WebRoleRefPermission object resulting from the translation to the role
672             * identified in the role-link appearing in the security-role-ref.
673             */

674             addPermissionToRole(roleLink, new WebRoleRefPermission JavaDoc(servletName, roleName), rolePermissions);
675             unmappedRoles.remove(roleName);
676         }
677         for (Iterator JavaDoc iterator = unmappedRoles.iterator(); iterator.hasNext();) {
678             String JavaDoc roleName = (String JavaDoc) iterator.next();
679             addPermissionToRole(roleName, new WebRoleRefPermission JavaDoc(servletName, roleName), rolePermissions);
680         }
681 // servletData.setAttribute("webRoleRefPermissions", webRoleRefPermissions);
682
}
683
684     protected void buildSubstitutionGroups(XmlObject gerWebApp, boolean hasSecurityRealmName, Module module, EARContext earContext) throws DeploymentException {
685         XmlObject[] securityElements = XmlBeansUtil.selectSubstitutionGroupElements(SECURITY_QNAME, gerWebApp);
686         if (securityElements.length > 0 && !hasSecurityRealmName) {
687             throw new DeploymentException("You have supplied a security configuration for web app " + module.getName() + " but no security-realm-name to allow login");
688         }
689         securityBuilders.build(gerWebApp, earContext, module.getEarContext());
690         serviceBuilders.build(gerWebApp, earContext, module.getEarContext());
691     }
692
693     class UncheckedItem {
694         final static int NA = 0x00;
695         final static int INTEGRAL = 0x01;
696         final static int CONFIDENTIAL = 0x02;
697
698         private int transportType = NA;
699         private String JavaDoc name;
700
701         public UncheckedItem(String JavaDoc name, String JavaDoc actions) {
702             setName(name);
703             setTransportType(actions);
704         }
705
706         public boolean equals(Object JavaDoc o) {
707             UncheckedItem item = (UncheckedItem) o;
708             return item.getKey().equals(this.getKey());
709         }
710
711         public String JavaDoc getKey() {
712             return (name + transportType);
713         }
714
715         public int hashCode() {
716             return getKey().hashCode();
717         }
718
719         public String JavaDoc getName() {
720             return name;
721         }
722
723         public void setName(String JavaDoc name) {
724             this.name = name;
725         }
726
727         public int getTransportType() {
728             return transportType;
729         }
730
731         public void setTransportType(String JavaDoc actions) {
732             String JavaDoc[] tokens = actions.split(":", 2);
733             if (tokens.length == 2) {
734                 if (tokens[1].equals("INTEGRAL")) {
735                     this.transportType = INTEGRAL;
736                 } else if (tokens[1].equals("CONFIDENTIAL")) {
737                     this.transportType = CONFIDENTIAL;
738                 }
739             }
740         }
741     }
742 }
743
Popular Tags