KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > web > deployers > AbstractWarDeployment


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2006, Red Hat Middleware LLC, and individual contributors
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.web.deployers;
23
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.net.URLClassLoader JavaDoc;
27 import java.security.Policy JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import javax.management.MBeanServer JavaDoc;
34 import javax.management.ObjectName JavaDoc;
35 import javax.naming.Context JavaDoc;
36 import javax.naming.InitialContext JavaDoc;
37 import javax.naming.LinkRef JavaDoc;
38 import javax.naming.NamingException JavaDoc;
39 import javax.security.jacc.PolicyConfiguration JavaDoc;
40 import javax.security.jacc.PolicyConfigurationFactory JavaDoc;
41 import javax.security.jacc.PolicyContextException JavaDoc;
42
43 import org.jboss.deployers.spi.deployer.DeploymentUnit;
44 import org.jboss.deployers.spi.structure.DeploymentContext;
45 import org.jboss.ejb.EjbUtil50;
46 import org.jboss.logging.Logger;
47 import org.jboss.metadata.EjbLocalRefMetaData;
48 import org.jboss.metadata.EjbRefMetaData;
49 import org.jboss.metadata.EnvEntryMetaData;
50 import org.jboss.metadata.MessageDestinationMetaData;
51 import org.jboss.metadata.MessageDestinationRefMetaData;
52 import org.jboss.metadata.ResourceEnvRefMetaData;
53 import org.jboss.metadata.ResourceRefMetaData;
54 import org.jboss.metadata.WebMetaData;
55 import org.jboss.mx.loading.LoaderRepositoryFactory;
56 import org.jboss.naming.NonSerializableFactory;
57 import org.jboss.naming.Util;
58 import org.jboss.security.AuthorizationManager;
59 import org.jboss.security.authorization.PolicyRegistration;
60 import org.jboss.web.WebApplication;
61 import org.jboss.web.WebPermissionMapping;
62 import org.omg.CORBA.ORB JavaDoc;
63
64 /**
65 An abstract web app deployment bean. Subclasses implement:
66
67 - init(Object) to initialize from the deployment configuration java bean passed
68 in from the AbstractWarDeployer instance.
69 - performDeploy(WebApplication webApp, String warUrl) to translate the
70 WebApplication data into a running web application. This is called when the
71 AbstractWarDeployment is started.
72 - performUndeploy(WebApplication webApp, String warUrl) to remove the application
73 corresponding to the WebApplication data. This is called when the
74 AbstractWarDeployment is stopped.
75  
76 The one thing to be aware of is the relationship between the thread context
77 class loader and the JNDI ENC context. Any method that attempts to access
78 the JNDI ENC context must have the ClassLoader in the WebApplication returned
79 from the {@link #performDeploy(WebApplication, String, WebDescriptorParser) performDeploy} as its thread
80 context ClassLoader or else the lookup for java:comp/env will fail with a
81 name not found exception, or worse, it will receive some other web application
82 ENC context.
83 TODO: the enc should be managed outside of the container without relying
84 on the TCL behavior.
85
86 @author Scott.Stark@jboss.org
87 @version $Revision: 57455 $
88 */

89 public abstract class AbstractWarDeployment
90 {
91    public static final String JavaDoc ERROR = "org.jboss.web.AbstractWebContainer.error";
92    protected Logger log;
93
94    protected MBeanServer JavaDoc server;
95    /**
96     * The parent class loader first model flag
97     */

98    protected boolean java2ClassLoadingCompliance = false;
99    /**
100     * A flag indicating if war archives should be unpacked
101     */

102    protected boolean unpackWars = true;
103    /**
104     * If true, ejb-links that don't resolve don't cause an error (fallback to
105     * jndi-name)
106     */

107    protected boolean lenientEjbLink = false;
108
109    /**
110     * The default security-domain name to use
111     */

112    protected String JavaDoc defaultSecurityDomain;
113
114    public AbstractWarDeployment()
115    {
116       log = Logger.getLogger(getClass());
117    }
118
119    /**
120     * A utility method that takes a deployment unit name and strips it down to the base war
121     * name without the .war suffix.
122     * @param name - the DeploymentUnit name.
123     */

124    public static String JavaDoc shortNameFromDeploymentName(String JavaDoc name)
125    {
126       String JavaDoc shortName = name.trim();
127       String JavaDoc[] parts = name.split("/|\\.|\\!");
128       if( parts.length > 1 )
129       {
130          // If it ends in .war, use the previous part
131
if( parts[parts.length-1].equals("war") )
132             shortName = parts[parts.length-2];
133          // else use the last part
134
else
135             shortName = parts[parts.length-1];
136       }
137       return shortName;
138    }
139    /**
140     * Utility method that builds a string url based on the ServerConfig.SERVER_HOME_URL system
141     * property and the input url. If the input url is under the SERVER_HOME_URL, the SERVER_HOME_URL
142     * prefix is replaced with ".../".
143     * @param warUrl
144     * @return the possibly shorted war url string.
145     */

146    public static String JavaDoc shortWarUrlFromServerHome(String JavaDoc warUrl)
147    {
148        String JavaDoc serverHomeUrl = System.getProperty(org.jboss.system.server.ServerConfig.SERVER_HOME_URL);
149
150        if (warUrl == null || serverHomeUrl == null)
151            return warUrl;
152
153        if (warUrl.startsWith(serverHomeUrl))
154          return ".../" + warUrl.substring(serverHomeUrl.length());
155        else
156          return warUrl;
157    }
158
159    /**
160     * Initialize the deployment using an instance specific configuration object.
161     * @param containerConfig
162     * @throws Exception
163     */

164    public abstract void init(Object JavaDoc containerConfig) throws Exception JavaDoc;
165
166    public MBeanServer JavaDoc getServer()
167    {
168       return server;
169    }
170
171    public void setServer(MBeanServer JavaDoc server)
172    {
173       this.server = server;
174    }
175
176    /**
177     * Get the flag indicating if the normal Java2 parent first class loading
178     * model should be used over the servlet 2.3 web container first model.
179     * @return true for parent first, false for the servlet 2.3 model
180     * @jmx.managed-attribute
181     */

182    public boolean getJava2ClassLoadingCompliance()
183    {
184       return java2ClassLoadingCompliance;
185    }
186
187    /**
188     * Set the flag indicating if the normal Java2 parent first class loading
189     * model should be used over the servlet 2.3 web container first model.
190     * @param flag true for parent first, false for the servlet 2.3 model
191     * @jmx.managed-attribute
192     */

193    public void setJava2ClassLoadingCompliance(boolean flag)
194    {
195       java2ClassLoadingCompliance = flag;
196    }
197
198    /**
199     * Get the flag indicating if war archives should be unpacked. This may need
200     * to be set to false as long extraction paths under deploy can show up as
201     * deployment failures on some platforms.
202     * @return true is war archives should be unpacked
203     * @jmx.managed-attribute
204     */

205    public boolean getUnpackWars()
206    {
207       return unpackWars;
208    }
209
210    /**
211     * Get the flag indicating if war archives should be unpacked. This may need
212     * to be set to false as long extraction paths under deploy can show up as
213     * deployment failures on some platforms.
214     * @param flag , true is war archives should be unpacked
215     * @jmx.managed-attribute
216     */

217    public void setUnpackWars(boolean flag)
218    {
219       this.unpackWars = flag;
220    }
221
222    /**
223     * Get the flag indicating if ejb-link errors should be ignored in favour of
224     * trying the jndi-name in jboss-web.xml
225     * @return a <code>boolean</code> value
226     * @jmx.managed-attribute
227     */

228    public boolean getLenientEjbLink()
229    {
230       return lenientEjbLink;
231    }
232
233    /**
234     * Set the flag indicating if ejb-link errors should be ignored in favour of
235     * trying the jndi-name in jboss-web.xml
236     * @jmx.managed-attribute
237     */

238    public void setLenientEjbLink(boolean flag)
239    {
240       lenientEjbLink = flag;
241    }
242
243    /**
244     * Get the default security domain implementation to use if a war does not
245     * declare a security-domain.
246     * @return jndi name of the security domain binding to use.
247     * @jmx.managed-attribute
248     */

249    public String JavaDoc getDefaultSecurityDomain()
250    {
251       if(defaultSecurityDomain == null)
252           throw new IllegalStateException JavaDoc("Default Security Domain is null");
253       return defaultSecurityDomain;
254    }
255
256    /**
257     * Set the default security domain implementation to use if a war does not
258     * declare a security-domain.
259     * @param defaultSecurityDomain - jndi name of the security domain binding to
260     * use.
261     * @jmx.managed-attribute
262     */

263    public void setDefaultSecurityDomain(String JavaDoc defaultSecurityDomain)
264    {
265       this.defaultSecurityDomain = defaultSecurityDomain;
266    }
267
268    /**
269     * A template pattern implementation of the deploy() method. This method
270     * calls the {@link #performDeploy(WebApplication, String,
271       * WebDescriptorParser) performDeploy()} method to perform the container
272     * specific deployment steps and registers the returned WebApplication in the
273     * deployment map. The steps performed are:
274     *
275     * ClassLoader appClassLoader = thread.getContextClassLoader();
276     * URLClassLoader warLoader = URLClassLoader.newInstance(empty,
277     * appClassLoader); thread.setContextClassLoader(warLoader);
278     * WebDescriptorParser webAppParser = ...; WebMetaData metaData =
279     * di.metaData; // Create JACC permissions, contextID, etc. ...
280     * WebApplication warInfo = new WebApplication(metaData);
281     * performDeploy(warInfo, warUrl, webAppParser); deploymentMap.put(warUrl,
282     * warInfo); thread.setContextClassLoader(appClassLoader);
283     *
284     * The subclass performDeploy() implementation needs to invoke
285     * processEnc(loader, warInfo) to have the JNDI
286     * java:comp/env namespace setup before any web app component can access this
287     * namespace.
288     *
289     * Also, an MBean for each servlet deployed should be created and its JMX
290     * ObjectName placed into the DeploymentInfo.mbeans list so that the JSR77
291     * layer can create the approriate model view. The servlet MBean needs to
292     * provide access to the min, max and total time in milliseconds. Expose this
293     * information via MinServiceTime, MaxServiceTime and TotalServiceTime
294     * attributes to integrate seemlessly with the JSR77 factory layer.
295     * @param di The deployment info that contains the context-root element value
296     * from the J2EE application/module/web application.xml descriptor. This may
297     * be null if war was is not being deployed as part of an enterprise
298     * application. It also contains the URL of the web application war.
299     */

300    public synchronized WebApplication start(DeploymentUnit di, WebMetaData metaData)
301       throws Exception JavaDoc
302    {
303       Thread JavaDoc thread = Thread.currentThread();
304       ClassLoader JavaDoc appClassLoader = thread.getContextClassLoader();
305       WebApplication webApp = null;
306       try
307       {
308          // Create a classloader for the war to ensure a unique ENC
309
URL JavaDoc[] empty = {};
310          URLClassLoader JavaDoc warLoader = URLClassLoader.newInstance(empty, di.getClassLoader());
311          thread.setContextClassLoader(warLoader);
312          String JavaDoc webContext = metaData.getContextRoot();
313    
314          // Get the war URL
315
// FIXME: JBAS-3812 - TomcatDeployment should use modified WebMetaData
316
URL JavaDoc warURL = di.getAttachment("org.jboss.web.expandedWarURL", URL JavaDoc.class);
317          if( warURL == null )
318             warURL = di.getAttachment("jbossws.expanded.war.url", URL JavaDoc.class);
319          if (warURL == null)
320             warURL = di.getDeploymentContext().getRoot().toURL();
321
322          // Strip any jar: url syntax. This should be be handled by the vfs
323
String JavaDoc warURLString = warURL.toString();
324          if( warURLString.startsWith("jar:") )
325             warURLString = warURLString.substring(4, warURLString.length()-2);
326          
327          log.debug("webContext: " + webContext);
328          log.debug("warURL: " + warURLString);
329    
330          // Register the permissions with the JACC layer
331
String JavaDoc contextID = metaData.getJaccContextID();
332          if( contextID == null )
333             contextID = shortNameFromDeploymentName(di.getName());
334          metaData.setJaccContextID(contextID);
335          PolicyConfigurationFactory JavaDoc pcFactory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
336          PolicyConfiguration JavaDoc pc = pcFactory.getPolicyConfiguration(contextID, true);
337          createPermissions(metaData, pc);
338          // Link this to the parent PC
339
DeploymentContext current = di.getDeploymentContext();
340          while (current.getParent() != null)
341             current = current.getParent();
342          PolicyConfiguration JavaDoc parentPC =
343             current.getTransientAttachments().getAttachment(PolicyConfiguration JavaDoc.class);
344          if (parentPC != null && parentPC != pc)
345             parentPC.linkConfiguration(pc);
346    
347          // Commit the policy configuration
348
pc.commit();
349          // Allow the policy to incorporate the policy configs
350
Policy.getPolicy().refresh();
351    
352          webApp = new WebApplication(metaData);
353          webApp.setClassLoader(warLoader);
354          webApp.setDeploymentUnit(di);
355          performDeploy(webApp, warURLString);
356       }
357       finally
358       {
359          thread.setContextClassLoader(appClassLoader);
360       }
361       return webApp;
362    }
363
364    /**
365     * A template pattern implementation of the undeploy() method. This method
366     * calls the {@link #performUndeploy(String, WebApplication)
367     * performUndeploy()} method to perform the container specific undeployment
368     * steps and unregisters the the warUrl from the deployment map.
369     */

370    public synchronized void stop(DeploymentUnit di, WebApplication webApp)
371       throws Exception JavaDoc
372    {
373       URL JavaDoc warURL = webApp.getURL();
374       String JavaDoc warUrl = warURL.toString();
375       performUndeploy(webApp, warUrl);
376       // Unregister the permissions with the JACC layer
377
WebMetaData metaData = webApp.getMetaData();
378       String JavaDoc contextID = metaData.getJaccContextID();
379       PolicyConfigurationFactory JavaDoc pcFactory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
380       PolicyConfiguration JavaDoc pc = pcFactory.getPolicyConfiguration(contextID, true);
381       pc.delete();
382       //Unregister any xacml policies
383
String JavaDoc prefixedSecurityDomain = webApp.getMetaData().getSecurityDomain();
384       if(prefixedSecurityDomain != null)
385       {
386          AuthorizationManager authzmgr =
387              org.jboss.security.Util.getAuthorizationManager(prefixedSecurityDomain);
388          if(authzmgr instanceof PolicyRegistration)
389          {
390             PolicyRegistration xam = (PolicyRegistration)authzmgr;
391             xam.deRegisterPolicy(contextID);
392          }
393       }
394    }
395
396    /**
397     * This method is called by the start() method template and must be
398     * overriden by subclasses to perform the web container specific deployment
399     * steps.
400     * @param webApp The web application information context. This contains the
401     * metadata such as the context-root element value from the J2EE
402     * application/module/web application.xml descriptor and virtual-host.
403     * @param warUrl The string for the URL of the web application war.
404     */

405    protected abstract void performDeploy(WebApplication webApp, String JavaDoc warUrl) throws Exception JavaDoc;
406    /**
407     * Called as part of the stop() method template to ask the subclass for
408     * perform the web container specific undeployment steps.
409     * @param webApp The web application information context. This contains the
410     * metadata such as the context-root element value from the J2EE
411     * application/module/web application.xml descriptor and virtual-host.
412     * @param warUrl The string for the URL of the web application war.
413     */

414    protected abstract void performUndeploy(WebApplication webApp, String JavaDoc warUrl)
415       throws Exception JavaDoc;
416
417    /**
418     * This method is invoked from within subclass performDeploy() method
419     * implementations when they invoke WebDescriptorParser.parseWebAppDescriptors().
420     * @param loader the ClassLoader for the web application. May not be null.
421     * @param metaData the WebMetaData from the WebApplication object passed to
422     * the performDeploy method.
423     */

424    protected void processEnc(ClassLoader JavaDoc loader, WebApplication webApp)
425       throws Exception JavaDoc
426    {
427       if(loader == null)
428           throw new IllegalArgumentException JavaDoc("Classloader passed to process ENC refs is null");
429       log.debug("AbstractWebContainer.parseWebAppDescriptors, Begin");
430       InitialContext JavaDoc iniCtx = new InitialContext JavaDoc();
431       Context JavaDoc envCtx = null;
432       Thread JavaDoc currentThread = Thread.currentThread();
433       ClassLoader JavaDoc currentLoader = currentThread.getContextClassLoader();
434       WebMetaData metaData = webApp.getMetaData();
435       try
436       {
437          // Create a java:comp/env environment unique for the web application
438
log.debug("Creating ENC using ClassLoader: " + loader);
439          ClassLoader JavaDoc parent = loader.getParent();
440          while (parent != null)
441          {
442             log.debug(".." + parent);
443             parent = parent.getParent();
444          }
445          // TODO: The enc should be an input?
446
currentThread.setContextClassLoader(loader);
447          metaData.setENCLoader(loader);
448          envCtx = (Context JavaDoc) iniCtx.lookup("java:comp");
449
450          // TODO: inject the ORB
451
ORB JavaDoc orb = null;
452          try
453          {
454             ObjectName JavaDoc ORB_NAME = new ObjectName JavaDoc("jboss:service=CorbaORB");
455             orb = (ORB JavaDoc) server.getAttribute(ORB_NAME, "ORB");
456             // Bind the orb
457
if (orb != null)
458             {
459                NonSerializableFactory.rebind(envCtx, "ORB", orb);
460                log.debug("Bound java:comp/ORB");
461             }
462          }
463          catch (Throwable JavaDoc t)
464          {
465             log.debug("Unable to retrieve orb" + t.toString());
466          }
467
468          // TODO: injection, Add a link to the global transaction manager
469
envCtx.bind("UserTransaction", new LinkRef JavaDoc("UserTransaction"));
470          log.debug("Linked java:comp/UserTransaction to JNDI name: UserTransaction");
471          envCtx = envCtx.createSubcontext("env");
472          processEncReferences(webApp, envCtx);
473       }
474       finally
475       {
476          currentThread.setContextClassLoader(currentLoader);
477       }
478
479       String JavaDoc securityDomain = metaData.getSecurityDomain();
480       log.debug("linkSecurityDomain");
481       linkSecurityDomain(securityDomain, envCtx);
482       log.debug("AbstractWebContainer.parseWebAppDescriptors, End");
483    }
484
485    protected void processEncReferences(WebApplication webApp, Context JavaDoc envCtx)
486            throws ClassNotFoundException JavaDoc, NamingException JavaDoc
487    {
488       DeploymentUnit unit = webApp.getDeploymentUnit();
489       WebMetaData metaData = webApp.getMetaData();
490       Iterator JavaDoc envEntries = metaData.getEnvironmentEntries();
491       log.debug("addEnvEntries");
492       addEnvEntries(envEntries, envCtx);
493       Iterator JavaDoc resourceEnvRefs = metaData.getResourceEnvReferences();
494       log.debug("linkResourceEnvRefs");
495       linkResourceEnvRefs(resourceEnvRefs, envCtx);
496       Iterator JavaDoc resourceRefs = metaData.getResourceReferences();
497       log.debug("linkResourceRefs");
498       linkResourceRefs(resourceRefs, envCtx);
499       log.debug("linkMessageDestinationRefs");
500       linkMessageDestinationRefs(unit, metaData, envCtx);
501       Iterator JavaDoc ejbRefs = metaData.getEjbReferences();
502       log.debug("linkEjbRefs");
503       linkEjbRefs(unit, ejbRefs, envCtx);
504       Iterator JavaDoc ejbLocalRefs = metaData.getEjbLocalReferences();
505       log.debug("linkEjbLocalRefs");
506       linkEjbLocalRefs(unit, ejbLocalRefs, envCtx);
507       Iterator JavaDoc serviceRefs = metaData.getServiceReferences();
508       log.debug("linkServiceRefs");
509       //WebServiceClientHandler.setupServiceRefEnvironment(envCtx, serviceRefs);
510
}
511
512    protected void addEnvEntries(Iterator JavaDoc envEntries, Context JavaDoc envCtx)
513       throws ClassNotFoundException JavaDoc, NamingException JavaDoc
514    {
515       while (envEntries.hasNext())
516       {
517          EnvEntryMetaData entry = (EnvEntryMetaData) envEntries.next();
518          log.debug("Binding env-entry: " + entry.getName() + " of type: " +
519             entry.getType() + " to value:" + entry.getValue());
520          EnvEntryMetaData.bindEnvEntry(envCtx, entry);
521       }
522    }
523
524    protected void linkResourceEnvRefs(Iterator JavaDoc resourceEnvRefs, Context JavaDoc envCtx)
525       throws NamingException JavaDoc
526    {
527       while (resourceEnvRefs.hasNext())
528       {
529          ResourceEnvRefMetaData ref = (ResourceEnvRefMetaData) resourceEnvRefs.next();
530          String JavaDoc resourceName = ref.getJndiName();
531          String JavaDoc refName = ref.getRefName();
532          if (ref.getType().equals("java.net.URL"))
533          {
534             try
535             {
536                log.debug("Binding '" + refName + "' to URL: " + resourceName);
537                URL JavaDoc url = new URL JavaDoc(resourceName);
538                Util.bind(envCtx, refName, url);
539             }
540             catch (MalformedURLException JavaDoc e)
541             {
542                throw new NamingException JavaDoc("Malformed URL:" + e.getMessage());
543             }
544          }
545          else if (resourceName != null)
546          {
547             log.debug("Linking '" + refName + "' to JNDI name: " + resourceName);
548             Util.bind(envCtx, refName, new LinkRef JavaDoc(resourceName));
549          }
550          else
551          {
552             throw new NamingException JavaDoc("resource-env-ref: " + refName
553                + " has no valid JNDI binding. Check the jboss-web/resource-env-ref.");
554          }
555       }
556    }
557
558    protected void linkResourceRefs(Iterator JavaDoc resourceRefs, Context JavaDoc envCtx)
559       throws NamingException JavaDoc
560    {
561       while (resourceRefs.hasNext())
562       {
563          ResourceRefMetaData ref = (ResourceRefMetaData) resourceRefs.next();
564          String JavaDoc jndiName = ref.getJndiName();
565          String JavaDoc refName = ref.getRefName();
566          if (ref.getType().equals("java.net.URL"))
567          {
568             try
569             {
570                String JavaDoc resURL = ref.getResURL();
571                if (ref.getResURL() != null)
572                {
573                   log.debug("Binding '" + refName + "' to URL: " + resURL);
574                   URL JavaDoc url = new URL JavaDoc(resURL);
575                   Util.bind(envCtx, refName, url);
576                }
577                else
578                {
579                   log.debug("Linking '" + refName + "' to URL: " + resURL);
580                   LinkRef JavaDoc urlLink = new LinkRef JavaDoc(jndiName);
581                   Util.bind(envCtx, refName, urlLink);
582                }
583             }
584             catch (MalformedURLException JavaDoc e)
585             {
586                throw new NamingException JavaDoc("Malformed URL:" + e.getMessage());
587             }
588          }
589          else if (jndiName != null)
590          {
591             log.debug("Linking '" + refName + "' to JNDI name: " + jndiName);
592             Util.bind(envCtx, refName, new LinkRef JavaDoc(jndiName));
593          }
594          else
595          {
596             throw new NamingException JavaDoc("resource-ref: " + refName
597                + " has no valid JNDI binding. Check the jboss-web/resource-ref.");
598          }
599       }
600    }
601
602    protected void linkMessageDestinationRefs(DeploymentUnit unit, WebMetaData metaData, Context JavaDoc envCtx)
603       throws NamingException JavaDoc
604    {
605       Iterator JavaDoc i = metaData.getMessageDestinationReferences();
606
607       while (i.hasNext())
608       {
609          MessageDestinationRefMetaData ref = (MessageDestinationRefMetaData) i.next();
610
611          String JavaDoc refName = ref.getRefName();
612          String JavaDoc jndiName = ref.getJNDIName();
613          String JavaDoc link = ref.getLink();
614          if (link != null)
615          {
616             if (jndiName == null)
617             {
618                MessageDestinationMetaData messageDestination = EjbUtil50.findMessageDestination(server, unit, link);
619                if (messageDestination == null)
620                   throw new NamingException JavaDoc("message-destination-ref '" + refName +
621                      "' message-destination-link '" + link + "' not found and no jndi-name in jboss-web.xml");
622                else
623                {
624                   String JavaDoc linkJNDIName = messageDestination.getJNDIName();
625                   if (linkJNDIName == null)
626                      log.warn("message-destination '" + link + "' has no jndi-name in jboss-web.xml");
627                   else
628                      jndiName = linkJNDIName;
629                }
630             }
631             else
632                log.warn("message-destination-ref '" + refName +
633                   "' ignoring message-destination-link '" + link + "' because it has a jndi-name in jboss-web.xml");
634          }
635          else if (jndiName == null)
636             throw new NamingException JavaDoc("message-destination-ref '" + refName +
637                "' has no message-destination-link in web.xml and no jndi-name in jboss-web.xml");
638          Util.bind(envCtx, refName, new LinkRef JavaDoc(jndiName));
639       }
640    }
641
642    protected void linkEjbRefs(DeploymentUnit unit, Iterator JavaDoc ejbRefs, Context JavaDoc envCtx)
643       throws NamingException JavaDoc
644    {
645       while (ejbRefs.hasNext())
646       {
647          EjbRefMetaData ejb = (EjbRefMetaData) ejbRefs.next();
648          String JavaDoc name = ejb.getName();
649          String JavaDoc linkName = ejb.getLink();
650          String JavaDoc jndiName = null;
651          
652          //use ejb-link if it is specified
653
if (linkName != null)
654          {
655             jndiName = EjbUtil50.findEjbLink(server, unit, linkName);
656              
657             //if flag does not allow misconfigured ejb-links, it is an error
658
if ((jndiName == null) && !(getLenientEjbLink()))
659                throw new NamingException JavaDoc("ejb-ref: " + name + ", no ejb-link match");
660          }
661
662          
663          //fall through to the jndiName
664
if (jndiName == null)
665          {
666             jndiName = ejb.getJndiName();
667             if (jndiName == null)
668                throw new NamingException JavaDoc("ejb-ref: " + name + ", no ejb-link in web.xml and no jndi-name in jboss-web.xml");
669          }
670
671          log.debug("Linking ejb-ref: " + name + " to JNDI name: " + jndiName);
672          Util.bind(envCtx, name, new LinkRef JavaDoc(jndiName));
673       }
674    }
675
676    protected void linkEjbLocalRefs(DeploymentUnit unit, Iterator JavaDoc ejbRefs, Context JavaDoc envCtx)
677       throws NamingException JavaDoc
678    {
679       while (ejbRefs.hasNext())
680       {
681          EjbLocalRefMetaData ejb = (EjbLocalRefMetaData) ejbRefs.next();
682          String JavaDoc name = ejb.getName();
683          String JavaDoc linkName = ejb.getLink();
684          String JavaDoc jndiName = null;
685
686          //use the ejb-link field if it is specified
687
if (linkName != null)
688          {
689             jndiName = EjbUtil50.findLocalEjbLink(server, unit, linkName);
690              
691             //if flag does not allow misconfigured ejb-links, it is an error
692
if ((jndiName == null) && !(getLenientEjbLink()))
693                throw new NamingException JavaDoc("ejb-ref: " + name + ", no ejb-link match");
694          }
695
696
697          if (jndiName == null)
698          {
699             jndiName = ejb.getJndiName();
700             if (jndiName == null)
701             {
702                String JavaDoc msg = null;
703                if (linkName == null)
704                {
705                   msg = "ejb-local-ref: '" + name + "', no ejb-link in web.xml and "
706                      + "no local-jndi-name in jboss-web.xml";
707                }
708                else
709                {
710                   msg = "ejb-local-ref: '" + name + "', with web.xml ejb-link: '"
711                      + linkName + "' failed to resolve to an ejb with a LocalHome";
712                }
713                throw new NamingException JavaDoc(msg);
714             }
715          }
716
717          log.debug("Linking ejb-local-ref: " + name + " to JNDI name: " + jndiName);
718          Util.bind(envCtx, name, new LinkRef JavaDoc(jndiName));
719       }
720    }
721
722    /**
723     * This creates a java:comp/env/security context that contains a securityMgr
724     * binding pointing to an AuthenticationManager implementation and a
725     * realmMapping binding pointing to a RealmMapping implementation. If the
726     * jboss-web.xml descriptor contained a security-domain element then the
727     * bindings are LinkRefs to the jndi name specified by the security-domain
728     * element. If there was no security-domain element then the bindings are to
729     * NullSecurityManager instance which simply allows all access.
730     */

731    protected void linkSecurityDomain(String JavaDoc securityDomain, Context JavaDoc envCtx)
732       throws NamingException JavaDoc
733    {
734       if (securityDomain == null)
735       {
736          securityDomain = getDefaultSecurityDomain();
737          log.debug("No security-domain given, using default: " + securityDomain);
738       }
739       log.debug("Linking security/securityMgr to JNDI name: " + securityDomain);
740       Util.bind(envCtx, "security/securityMgr", new LinkRef JavaDoc(securityDomain));
741       Util.bind(envCtx, "security/realmMapping", new LinkRef JavaDoc(securityDomain+"/realmMapping"));
742       Util.bind(envCtx, "security/authorizationMgr", new LinkRef JavaDoc(securityDomain+"/authorizationMgr"));
743       Util.bind(envCtx, "security/security-domain", new LinkRef JavaDoc(securityDomain));
744       Util.bind(envCtx, "security/subject", new LinkRef JavaDoc(securityDomain + "/subject"));
745    }
746
747    /**
748     * A utility method that searches the given loader for the resources:
749     * "javax/servlet/resources/web-app_2_3.dtd", "org/apache/jasper/resources/jsp12.dtd",
750     * and "javax/ejb/EJBHome.class" and returns an array of URL strings. Any
751     * jar: urls are reduced to the underlying <url> portion of the
752     * 'jar:<url>!/{entry}' construct.
753     */

754    public String JavaDoc[] getStandardCompileClasspath(ClassLoader JavaDoc loader)
755    {
756       String JavaDoc[] jspResources = {
757          "javax/servlet/resources/web-app_2_3.dtd",
758          "org/apache/jasper/resources/jsp12.dtd",
759          "javax/ejb/EJBHome.class"
760       };
761       ArrayList JavaDoc tmp = new ArrayList JavaDoc();
762       for (int j = 0; j < jspResources.length; j++)
763       {
764          URL JavaDoc rsrcURL = loader.getResource(jspResources[j]);
765          if (rsrcURL != null)
766          {
767             String JavaDoc url = rsrcURL.toExternalForm();
768             if (rsrcURL.getProtocol().equals("jar"))
769             {
770                // Parse the jar:<url>!/{entry} URL
771
url = url.substring(4);
772                int seperator = url.indexOf('!');
773                url = url.substring(0, seperator);
774             }
775             tmp.add(url);
776          }
777          else
778          {
779             log.warn("Failed to fin jsp rsrc: " + jspResources[j]);
780          }
781       }
782       log.trace("JSP StandardCompileClasspath: " + tmp);
783       String JavaDoc[] cp = new String JavaDoc[tmp.size()];
784       tmp.toArray(cp);
785       return cp;
786    }
787
788    /**
789     * A utility method that walks up the ClassLoader chain starting at the given
790     * loader and queries each ClassLoader for a 'URL[] getURLs()' method from
791     * which a complete classpath of URL strings is built.
792     */

793    public String JavaDoc[] getCompileClasspath(ClassLoader JavaDoc loader)
794    {
795       HashSet JavaDoc tmp = new HashSet JavaDoc();
796       ClassLoader JavaDoc cl = loader;
797       while (cl != null)
798       {
799          URL JavaDoc[] urls = AbstractWarDeployer.getClassLoaderURLs(cl);
800          addURLs(tmp, urls);
801          cl = cl.getParent();
802       }
803       try
804       {
805          URL JavaDoc[] globalUrls = (URL JavaDoc[]) server.getAttribute(LoaderRepositoryFactory.DEFAULT_LOADER_REPOSITORY,
806             "URLs");
807          addURLs(tmp, globalUrls);
808       }
809       catch (Exception JavaDoc e)
810       {
811          log.warn("Could not get global URL[] from default loader repository!", e);
812       } // end of try-catch
813
log.trace("JSP CompileClasspath: " + tmp);
814       String JavaDoc[] cp = new String JavaDoc[tmp.size()];
815       tmp.toArray(cp);
816       return cp;
817    }
818
819    private void addURLs(Set JavaDoc urlSet, URL JavaDoc[] urls)
820    {
821       for (int u = 0; u < urls.length; u++)
822       {
823          URL JavaDoc url = urls[u];
824          urlSet.add(url.toExternalForm());
825       }
826    }
827
828    /**
829     * Create the JACC permission based on the security constraints obtained from
830     * the web.xml metadata.
831     * @param metaData
832     * @param pc
833     * @throws PolicyContextException
834     */

835    protected void createPermissions(WebMetaData metaData, PolicyConfiguration JavaDoc pc)
836       throws PolicyContextException JavaDoc
837    {
838       WebPermissionMapping.createPermissions(metaData, pc);
839    }
840
841 }
842
Popular Tags