View Javadoc

    1   // ========================================================================
    2   // Copyright 2003-2005 Mort Bay Consulting Pty. Ltd.
    3   // ------------------------------------------------------------------------
    4   // Licensed under the Apache License, Version 2.0 (the "License");
    5   // you may not use this file except in compliance with the License.
    6   // You may obtain a copy of the License at
    7   // http://www.apache.org/licenses/LICENSE-2.0
    8   // Unless required by applicable law or agreed to in writing, software
    9   // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  // ========================================================================
    14  package org.mortbay.jetty.webapp;
    15
    16  import java.io.File;
    17  import java.io.IOException;
    18  import java.net.MalformedURLException;
    19  import java.net.URL;
    20  import java.util.ArrayList;
    21  import java.util.EventListener;
    22  import java.util.HashMap;
    23  import java.util.Iterator;
    24  import java.util.Map;
    25
    26  import javax.servlet.UnavailableException;
    27
    28  import org.mortbay.jetty.Handler;
    29  import org.mortbay.jetty.handler.ContextHandler;
    30  import org.mortbay.jetty.security.Authenticator;
    31  import org.mortbay.jetty.security.BasicAuthenticator;
    32  import org.mortbay.jetty.security.ClientCertAuthenticator;
    33  import org.mortbay.jetty.security.Constraint;
    34  import org.mortbay.jetty.security.ConstraintMapping;
    35  import org.mortbay.jetty.security.DigestAuthenticator;
    36  import org.mortbay.jetty.security.FormAuthenticator;
    37  import org.mortbay.jetty.security.UserRealm;
    38  import org.mortbay.jetty.servlet.Dispatcher;
    39  import org.mortbay.jetty.servlet.ErrorPageErrorHandler;
    40  import org.mortbay.jetty.servlet.FilterHolder;
    41  import org.mortbay.jetty.servlet.FilterMapping;
    42  import org.mortbay.jetty.servlet.ServletHandler;
    43  import org.mortbay.jetty.servlet.ServletHolder;
    44  import org.mortbay.jetty.servlet.ServletMapping;
    45  import org.mortbay.log.Log;
    46  import org.mortbay.resource.Resource;
    47  import org.mortbay.util.LazyList;
    48  import org.mortbay.util.Loader;
    49  import org.mortbay.xml.XmlParser;
    50  /* ------------------------------------------------------------------------------- */
    51  /**
    52   * Configure by parsing default web.xml and web.xml
    53   *
    54   * @author gregw
    55   */
    56  public class WebXmlConfiguration implements Configuration
    57  {
    58      protected WebAppContext _context;
    59      protected XmlParser _xmlParser;
    60      protected Object _filters;
    61      protected Object _filterMappings;
    62      protected Object _servlets;
    63      protected Object _servletMappings;
    64      protected Object _welcomeFiles;
    65      protected Object _constraintMappings;
    66      protected Object _listeners;
    67      protected Map _errorPages;
    68      protected boolean _hasJSP;
    69      protected String _jspServletName;
    70      protected String _jspServletClass;
    71      protected boolean _defaultWelcomeFileList;
    72      protected ServletHandler _servletHandler;
    73      protected int _version;
    74
    75      public WebXmlConfiguration()
    76      {
    77          // Get parser
    78          _xmlParser=webXmlParser();
    79      }
    80
    81      public static XmlParser webXmlParser()
    82      {
    83          XmlParser xmlParser=new XmlParser();
    84          //set up cache of DTDs and schemas locally
    85          URL dtd22=WebAppContext.class.getResource("/javax/servlet/resources/web-app_2_2.dtd");
    86          URL dtd23=WebAppContext.class.getResource("/javax/servlet/resources/web-app_2_3.dtd");
    87          URL jsp20xsd=WebAppContext.class.getResource("/javax/servlet/resources/jsp_2_0.xsd");
    88          URL jsp21xsd=WebAppContext.class.getResource("/javax/servlet/resources/jsp_2_1.xsd");
    89          URL j2ee14xsd=WebAppContext.class.getResource("/javax/servlet/resources/j2ee_1_4.xsd");
    90          URL webapp24xsd=WebAppContext.class.getResource("/javax/servlet/resources/web-app_2_4.xsd");
    91          URL webapp25xsd=WebAppContext.class.getResource("/javax/servlet/resources/web-app_2_5.xsd");
    92          URL schemadtd=WebAppContext.class.getResource("/javax/servlet/resources/XMLSchema.dtd");
    93          URL xmlxsd=WebAppContext.class.getResource("/javax/servlet/resources/xml.xsd");
    94          URL webservice11xsd=WebAppContext.class.getResource("/javax/servlet/resources/j2ee_web_services_client_1_1.xsd");
    95          URL webservice12xsd=WebAppContext.class.getResource("/javax/servlet/resources/javaee_web_services_client_1_2.xsd");
    96          URL datatypesdtd=WebAppContext.class.getResource("/javax/servlet/resources/datatypes.dtd");
    97          xmlParser.redirectEntity("web-app_2_2.dtd",dtd22);
    98          xmlParser.redirectEntity("-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN",dtd22);
    99          xmlParser.redirectEntity("web.dtd",dtd23);
    100         xmlParser.redirectEntity("web-app_2_3.dtd",dtd23);
    101         xmlParser.redirectEntity("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",dtd23);
    102         xmlParser.redirectEntity("XMLSchema.dtd",schemadtd);
    103         xmlParser.redirectEntity("http://www.w3.org/2001/XMLSchema.dtd",schemadtd);
    104         xmlParser.redirectEntity("-//W3C//DTD XMLSCHEMA 200102//EN",schemadtd);
    105         xmlParser.redirectEntity("jsp_2_0.xsd",jsp20xsd);
    106         xmlParser.redirectEntity("http://java.sun.com/xml/ns/j2ee/jsp_2_0.xsd",jsp20xsd);
    107         xmlParser.redirectEntity("jsp_2_1.xsd",jsp21xsd);
    108         xmlParser.redirectEntity("http://java.sun.com/xml/ns/javaee/jsp_2_1.xsd",jsp21xsd);
    109         xmlParser.redirectEntity("j2ee_1_4.xsd",j2ee14xsd);
    110         xmlParser.redirectEntity("http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd",j2ee14xsd);
    111         xmlParser.redirectEntity("web-app_2_4.xsd",webapp24xsd);
    112         xmlParser.redirectEntity("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd",webapp24xsd);
    113         xmlParser.redirectEntity("web-app_2_5.xsd",webapp25xsd);
    114         xmlParser.redirectEntity("http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd",webapp25xsd);
    115         xmlParser.redirectEntity("xml.xsd",xmlxsd);
    116         xmlParser.redirectEntity("http://www.w3.org/2001/xml.xsd",xmlxsd);
    117         xmlParser.redirectEntity("datatypes.dtd",datatypesdtd);
    118         xmlParser.redirectEntity("http://www.w3.org/2001/datatypes.dtd",datatypesdtd);
    119         xmlParser.redirectEntity("j2ee_web_services_client_1_1.xsd",webservice11xsd);
    120         xmlParser.redirectEntity("http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd",webservice11xsd);
    121         xmlParser.redirectEntity("javaee_web_services_client_1_2.xsd",webservice12xsd);
    122         xmlParser.redirectEntity("http://www.ibm.com/webservices/xsd/javaee_web_services_client_1_2.xsd",webservice12xsd);
    123
    124         return xmlParser;
    125     }
    126
    127     /* ------------------------------------------------------------------------------- */
    128     public void setWebAppContext (WebAppContext context)
    129     {
    130         _context = context;
    131     }
    132
    133     /* ------------------------------------------------------------------------------- */
    134     public WebAppContext getWebAppContext()
    135     {
    136         return _context;
    137     }
    138
    139     /* ------------------------------------------------------------------------------- */
    140     /** Configure ClassPath.
    141      */
    142     public  void configureClassLoader()
    143     throws Exception
    144     {
    145     }
    146
    147     /* ------------------------------------------------------------------------------- */
    148     public void configureDefaults() throws Exception
    149     {
    150         //cannot configure if the context is already started
    151         if (_context.isStarted())
    152         {
    153             if (Log.isDebugEnabled()){Log.debug("Cannot configure webapp after it is started");}
    154             return;
    155         }
    156         String defaultsDescriptor=getWebAppContext().getDefaultsDescriptor();
    157         if(defaultsDescriptor!=null&&defaultsDescriptor.length()>0)
    158         {
    159             Resource dftResource=Resource.newSystemResource(defaultsDescriptor);
    160             if(dftResource==null)
    161                 dftResource=Resource.newResource(defaultsDescriptor);
    162             configure(dftResource.getURL().toString());
    163             _defaultWelcomeFileList=_welcomeFiles!=null;
    164         }
    165     }
    166
    167     /* ------------------------------------------------------------------------------- */
    168     public void configureWebApp() throws Exception
    169     {
    170         //cannot configure if the context is already started
    171         if (_context.isStarted())
    172         {
    173             if (Log.isDebugEnabled())
    174                 Log.debug("Cannot configure webapp after it is started");
    175             return;
    176         }
    177
    178         URL webxml=findWebXml();
    179         if (webxml!=null)
    180             configure(webxml.toString());
    181
    182         String overrideDescriptor=getWebAppContext().getOverrideDescriptor();
    183         if(overrideDescriptor!=null&&overrideDescriptor.length()>0)
    184         {
    185             Resource orideResource=Resource.newSystemResource(overrideDescriptor);
    186             if(orideResource==null)
    187                 orideResource=Resource.newResource(overrideDescriptor);
    188             _xmlParser.setValidating(false);
    189             configure(orideResource.getURL().toString());
    190         }
    191     }
    192
    193     /* ------------------------------------------------------------------------------- */
    194     protected URL findWebXml() throws IOException, MalformedURLException
    195     {
    196         String descriptor=getWebAppContext().getDescriptor();
    197         if (descriptor!=null)
    198         {
    199             Resource web= Resource.newResource(descriptor);
    200             if (web.exists()&& !web.isDirectory())
    201                 return web.getURL();
    202         }
    203
    204         Resource web_inf=getWebAppContext().getWebInf();
    205         if(web_inf!=null && web_inf.isDirectory())
    206         {
    207             // do web.xml file
    208             Resource web=web_inf.addPath("web.xml");
    209             if(web.exists())
    210                 return web.getURL();
    211             Log.debug("No WEB-INF/web.xml in "+getWebAppContext().getWar()
    212                     +". Serving files and default/dynamic servlets only");
    213         }
    214         return null;
    215     }
    216
    217     /* ------------------------------------------------------------------------------- */
    218     public void configure(String webXml) throws Exception
    219     {
    220         XmlParser.Node config=null;
    221         config=_xmlParser.parse(webXml);
    222         initialize(config);
    223     }
    224
    225     /* ------------------------------------------------------------------------------- */
    226     public void deconfigureWebApp() throws Exception
    227     {
    228         // TODO preserve any configuration that pre-existed.
    229
    230         _servletHandler = getWebAppContext().getServletHandler();
    231
    232         _servletHandler.setFilters(null);
    233         _servletHandler.setFilterMappings(null);
    234         _servletHandler.setServlets(null);
    235         _servletHandler.setServletMappings(null);
    236
    237         getWebAppContext().setEventListeners(null);
    238         getWebAppContext().setWelcomeFiles(null);
    239         if (getWebAppContext().getSecurityHandler() != null)
    240             getWebAppContext().getSecurityHandler().setConstraintMappings(null);
    241
    242         if (getWebAppContext().getErrorHandler() instanceof ErrorPageErrorHandler)
    243             ((ErrorPageErrorHandler)getWebAppContext().getErrorHandler()).setErrorPages(null);
    244
    245         // TODO remove classpaths from classloader
    246     }
    247
    248     /* ------------------------------------------------------------ */
    249     protected void initialize(XmlParser.Node config) throws ClassNotFoundException,UnavailableException
    250     {
    251         _servletHandler = getWebAppContext().getServletHandler();
    252         // Get any existing servlets and mappings.
    253         _filters=LazyList.array2List(_servletHandler.getFilters());
    254         _filterMappings=LazyList.array2List(_servletHandler.getFilterMappings());
    255         _servlets=LazyList.array2List(_servletHandler.getServlets());
    256         _servletMappings=LazyList.array2List(_servletHandler.getServletMappings());
    257
    258         _listeners = LazyList.array2List(getWebAppContext().getEventListeners());
    259         _welcomeFiles = LazyList.array2List(getWebAppContext().getWelcomeFiles());
    260         _constraintMappings = LazyList.array2List(getWebAppContext().getSecurityHandler().getConstraintMappings());
    261
    262         _errorPages = getWebAppContext().getErrorHandler() instanceof ErrorPageErrorHandler ?
    263                         ((ErrorPageErrorHandler)getWebAppContext().getErrorHandler()).getErrorPages():null;
    264
    265         String version=config.getAttribute("version","DTD");
    266         if ("2.5".equals(version))
    267             _version=25;
    268         else if ("2.4".equals(version))
    269             _version=24;
    270         else if ("DTD".equals(version))
    271         {
    272             _version=23;
    273             String dtd=_xmlParser.getDTD();
    274             if (dtd!=null && dtd.indexOf("web-app_2_2")>=0)
    275                 _version=22;
    276         }
    277
    278         Iterator iter=config.iterator();
    279         XmlParser.Node node=null;
    280         while(iter.hasNext())
    281         {
    282             try
    283             {
    284                 Object o=iter.next();
    285                 if(!(o instanceof XmlParser.Node))
    286                     continue;
    287                 node=(XmlParser.Node)o;
    288                 String name=node.getTag();
    289                 initWebXmlElement(name,node);
    290             }
    291             catch(ClassNotFoundException e)
    292             {
    293                 throw e;
    294             }
    295             catch(Exception e)
    296             {
    297                 Log.warn("Configuration problem at "+node,e);
    298                 throw new UnavailableException("Configuration problem");
    299             }
    300         }
    301
    302         _servletHandler.setFilters((FilterHolder[])LazyList.toArray(_filters,FilterHolder.class));
    303         _servletHandler.setFilterMappings((FilterMapping[])LazyList.toArray(_filterMappings,FilterMapping.class));
    304         _servletHandler.setServlets((ServletHolder[])LazyList.toArray(_servlets,ServletHolder.class));
    305         _servletHandler.setServletMappings((ServletMapping[])LazyList.toArray(_servletMappings,ServletMapping.class));
    306
    307         getWebAppContext().setEventListeners((EventListener[])LazyList.toArray(_listeners,EventListener.class));
    308         getWebAppContext().setWelcomeFiles((String[])LazyList.toArray(_welcomeFiles,String.class));
    309         getWebAppContext().getSecurityHandler().setConstraintMappings((ConstraintMapping[])LazyList.toArray(_constraintMappings, ConstraintMapping.class));
    310
    311         if (_errorPages!=null && getWebAppContext().getErrorHandler() instanceof ErrorPageErrorHandler)
    312             ((ErrorPageErrorHandler)getWebAppContext().getErrorHandler()).setErrorPages(_errorPages);
    313
    314     }
    315
    316     /* ------------------------------------------------------------ */
    317     /**
    318      * Handle web.xml element. This method is called for each top level element within the web.xml
    319      * file. It may be specialized by derived WebAppHandlers to provide additional
    320      * configuration and handling.
    321      *
    322      * @param element The element name
    323      * @param node The node containing the element.
    324      */
    325     protected void initWebXmlElement(String element,XmlParser.Node node) throws Exception
    326     {
    327         if("display-name".equals(element))
    328             initDisplayName(node);
    329         else if("description".equals(element))
    330         {}
    331         else if("context-param".equals(element))
    332             initContextParam(node);
    333         else if("servlet".equals(element))
    334             initServlet(node);
    335         else if("servlet-mapping".equals(element))
    336             initServletMapping(node);
    337         else if("session-config".equals(element))
    338             initSessionConfig(node);
    339         else if("mime-mapping".equals(element))
    340             initMimeConfig(node);
    341         else if("welcome-file-list".equals(element))
    342             initWelcomeFileList(node);
    343         else if("locale-encoding-mapping-list".equals(element))
    344             initLocaleEncodingList(node);
    345         else if("error-page".equals(element))
    346             initErrorPage(node);
    347         else if("taglib".equals(element))
    348             initTagLib(node);
    349         else if("jsp-config".equals(element))
    350             initJspConfig(node);
    351         else if("resource-ref".equals(element))
    352         {
    353             if(Log.isDebugEnabled())
    354                 Log.debug("No implementation: "+node);
    355         }
    356         else if("security-constraint".equals(element))
    357             initSecurityConstraint(node);
    358         else if("login-config".equals(element))
    359             initLoginConfig(node);
    360         else if("security-role".equals(element))
    361             initSecurityRole(node);
    362         else if("filter".equals(element))
    363             initFilter(node);
    364         else if("filter-mapping".equals(element))
    365             initFilterMapping(node);
    366         else if("listener".equals(element))
    367             initListener(node);
    368         else if("distributable".equals(element))
    369             initDistributable(node);
    370         else
    371         {
    372             if(Log.isDebugEnabled())
    373             {
    374                 Log.debug("Element {} not handled in {}",element,this);
    375                 Log.debug(node.toString());
    376             }
    377         }
    378     }
    379
    380     /* ------------------------------------------------------------ */
    381     protected void initDisplayName(XmlParser.Node node)
    382     {
    383         getWebAppContext().setDisplayName(node.toString(false,true));
    384     }
    385
    386     /* ------------------------------------------------------------ */
    387     protected void initContextParam(XmlParser.Node node)
    388     {
    389         String name=node.getString("param-name",false,true);
    390         String value=node.getString("param-value",false,true);
    391         if(Log.isDebugEnabled())
    392             Log.debug("ContextParam: "+name+"="+value);
    393         getWebAppContext().getInitParams().put(name, value);
    394     }
    395
    396     /* ------------------------------------------------------------ */
    397     protected void initFilter(XmlParser.Node node)
    398     {
    399         String name=node.getString("filter-name",false,true);
    400         FilterHolder holder= _servletHandler.getFilter(name);
    401         if (holder==null)
    402         {
    403             holder=_servletHandler.newFilterHolder();
    404             holder.setName(name);
    405             _filters=LazyList.add(_filters,holder);
    406         }
    407
    408         String filter_class=node.getString("filter-class",false,true);
    409         if (filter_class!=null)
    410             holder.setClassName(filter_class);
    411
    412         Iterator iter=node.iterator("init-param");
    413         while(iter.hasNext())
    414         {
    415             XmlParser.Node paramNode=(XmlParser.Node)iter.next();
    416             String pname=paramNode.getString("param-name",false,true);
    417             String pvalue=paramNode.getString("param-value",false,true);
    418             holder.setInitParameter(pname, pvalue);
    419         }
    420
    421     }
    422
    423     /* ------------------------------------------------------------ */
    424     protected void initFilterMapping(XmlParser.Node node)
    425     {
    426         String filter_name=node.getString("filter-name",false,true);
    427
    428
    429
    430         FilterMapping mapping = new FilterMapping();
    431
    432         mapping.setFilterName(filter_name);
    433
    434         ArrayList paths = new ArrayList();
    435         Iterator iter=node.iterator("url-pattern");
    436         while(iter.hasNext())
    437         {
    438             String p=((XmlParser.Node)iter.next()).toString(false,true);
    439             p=normalizePattern(p);
    440             paths.add(p);
    441         }
    442         mapping.setPathSpecs((String[])paths.toArray(new String[paths.size()]));
    443
    444
    445         ArrayList names = new ArrayList();
    446         iter=node.iterator("servlet-name");
    447         while(iter.hasNext())
    448         {
    449             String n=((XmlParser.Node)iter.next()).toString(false,true);
    450             names.add(n);
    451         }
    452         mapping.setServletNames((String[])names.toArray(new String[names.size()]));
    453
    454
    455         int dispatcher=Handler.DEFAULT;
    456         iter=node.iterator("dispatcher");
    457         while(iter.hasNext())
    458         {
    459             String d=((XmlParser.Node)iter.next()).toString(false,true);
    460             dispatcher|=Dispatcher.type(d);
    461         }
    462         mapping.setDispatches(dispatcher);
    463
    464         _filterMappings=LazyList.add(_filterMappings,mapping);
    465     }
    466
    467     /* ------------------------------------------------------------ */
    468     protected String normalizePattern(String p)
    469     {
    470         if (p!=null && p.length()>0 && !p.startsWith("/") && !p.startsWith("*"))
    471             return "/"+p;
    472         return p;
    473     }
    474
    475     /* ------------------------------------------------------------ */
    476     protected void initServlet(XmlParser.Node node)
    477     {
    478         String id=node.getAttribute("id");
    479
    480         // initialize holder
    481         String servlet_name=node.getString("servlet-name",false,true);
    482         ServletHolder holder = _servletHandler.getServlet(servlet_name);
    483         if (holder==null)
    484         {
    485             holder=_servletHandler.newServletHolder();
    486             holder.setName(servlet_name);
    487             _servlets=LazyList.add(_servlets,holder);
    488         }
    489
    490         // init params
    491         Iterator iParamsIter=node.iterator("init-param");
    492         while(iParamsIter.hasNext())
    493         {
    494             XmlParser.Node paramNode=(XmlParser.Node)iParamsIter.next();
    495             String pname=paramNode.getString("param-name",false,true);
    496             String pvalue=paramNode.getString("param-value",false,true);
    497             holder.setInitParameter(pname,pvalue);
    498         }
    499
    500         String servlet_class=node.getString("servlet-class",false,true);
    501
    502         // Handle JSP
    503         if (id!=null && id.equals("jsp"))
    504         {
    505             _jspServletName=servlet_name;
    506             _jspServletClass=servlet_class;
    507             try
    508             {
    509                 Loader.loadClass(this.getClass(), servlet_class);
    510                 _hasJSP=true;
    511             }
    512             catch(ClassNotFoundException e)
    513             {
    514                 Log.info("NO JSP Support for {}, did not find {}",_context.getContextPath(),servlet_class);
    515                 _hasJSP=false;
    516                 _jspServletClass=servlet_class="org.mortbay.servlet.NoJspServlet";
    517             }
    518             if (holder.getInitParameter("scratchdir")==null)
    519             {
    520                 File tmp=getWebAppContext().getTempDirectory();
    521                 File scratch=new File(tmp,"jsp");
    522                 if (!scratch.exists())
    523                     scratch.mkdir();
    524                 holder.setInitParameter("scratchdir",scratch.getAbsolutePath());
    525
    526                 if ("?".equals(holder.getInitParameter("classpath")))
    527                 {
    528                     String classpath=getWebAppContext().getClassPath();
    529                     Log.debug("classpath="+classpath);
    530                     if (classpath!=null)
    531                         holder.setInitParameter("classpath",classpath);
    532                 }
    533             }
    534         }
    535         if (servlet_class!=null)
    536             holder.setClassName(servlet_class);
    537
    538
    539         // Handler JSP file
    540         String jsp_file=node.getString("jsp-file",false,true);
    541         if (jsp_file!=null)
    542         {
    543             holder.setForcedPath(jsp_file);
    544             holder.setClassName(_jspServletClass);
    545         }
    546
    547         // handle startup
    548         XmlParser.Node startup=node.get("load-on-startup");
    549         if(startup!=null)
    550         {
    551             String s=startup.toString(false,true).toLowerCase();
    552             if(s.startsWith("t"))
    553             {
    554                 Log.warn("Deprecated boolean load-on-startup.  Please use integer");
    555                 holder.setInitOrder(1);
    556             }
    557             else
    558             {
    559                 int order=0;
    560                 try
    561                 {
    562                     if(s!=null&&s.trim().length()>0)
    563                         order=Integer.parseInt(s);
    564                 }
    565                 catch(Exception e)
    566                 {
    567                     Log.warn("Cannot parse load-on-startup "+s+". Please use integer");
    568                     Log.ignore(e);
    569                 }
    570                 holder.setInitOrder(order);
    571             }
    572         }
    573
    574         Iterator sRefsIter=node.iterator("security-role-ref");
    575         while(sRefsIter.hasNext())
    576         {
    577             XmlParser.Node securityRef=(XmlParser.Node)sRefsIter.next();
    578             String roleName=securityRef.getString("role-name",false,true);
    579             String roleLink=securityRef.getString("role-link",false,true);
    580             if(roleName!=null&&roleName.length()>0&&roleLink!=null&&roleLink.length()>0)
    581             {
    582                 if(Log.isDebugEnabled())
    583                     Log.debug("link role "+roleName+" to "+roleLink+" for "+this);
    584                 holder.setUserRoleLink(roleName,roleLink);
    585             }
    586             else
    587             {
    588                 Log.warn("Ignored invalid security-role-ref element: "+"servlet-name="+holder.getName()+", "+securityRef);
    589             }
    590         }
    591
    592         XmlParser.Node run_as=node.get("run-as");
    593         if(run_as!=null)
    594         {
    595             String roleName=run_as.getString("role-name",false,true);
    596             if(roleName!=null)
    597                 holder.setRunAs(roleName);
    598         }
    599
    600     }
    601
    602     /* ------------------------------------------------------------ */
    603     protected void initServletMapping(XmlParser.Node node)
    604     {
    605         String servlet_name = node.getString("servlet-name",false,true);
    606         ServletMapping mapping = new ServletMapping();
    607         mapping.setServletName(servlet_name);
    608
    609         ArrayList paths = new ArrayList();
    610         Iterator iter=node.iterator("url-pattern");
    611         while(iter.hasNext())
    612         {
    613             String p=((XmlParser.Node)iter.next()).toString(false,true);
    614             p=normalizePattern(p);
    615             paths.add(p);
    616         }
    617         mapping.setPathSpecs((String[])paths.toArray(new String[paths.size()]));
    618
    619         _servletMappings=LazyList.add(_servletMappings,mapping);
    620     }
    621
    622     /* ------------------------------------------------------------ */
    623     protected void initListener(XmlParser.Node node)
    624     {
    625         String className=node.getString("listener-class",false,true);
    626         Object listener=null;
    627         try
    628         {
    629             Class listenerClass=getWebAppContext().loadClass(className);
    630             listener=newListenerInstance(listenerClass);
    631             if(!(listener instanceof EventListener))
    632             {
    633                 Log.warn("Not an EventListener: "+listener);
    634                 return;
    635             }
    636             _listeners=LazyList.add(_listeners, listener);
    637         }
    638         catch(Exception e)
    639         {
    640             Log.warn("Could not instantiate listener "+className,e);
    641             return;
    642         }
    643     }
    644
    645     /* ------------------------------------------------------------ */
    646     protected Object newListenerInstance(Class clazz)
    647         throws InstantiationException, IllegalAccessException
    648     {
    649                      return clazz.newInstance();
    650     }
    651
    652     /* ------------------------------------------------------------ */
    653     protected void initDistributable(XmlParser.Node node)
    654     {
    655         // the element has no content, so its simple presence
    656         // indicates that the webapp is distributable...
    657         WebAppContext wac=getWebAppContext();
    658         if (!wac.isDistributable())
    659             wac.setDistributable(true);
    660     }
    661
    662     /* ------------------------------------------------------------ */
    663     protected void initSessionConfig(XmlParser.Node node)
    664     {
    665         XmlParser.Node tNode=node.get("session-timeout");
    666         if(tNode!=null)
    667         {
    668             int timeout=Integer.parseInt(tNode.toString(false,true));
    669             getWebAppContext().getSessionHandler().getSessionManager().setMaxInactiveInterval(timeout*60);
    670         }
    671     }
    672
    673     /* ------------------------------------------------------------ */
    674     protected void initMimeConfig(XmlParser.Node node)
    675     {
    676         String extension=node.getString("extension",false,true);
    677         if(extension!=null&&extension.startsWith("."))
    678             extension=extension.substring(1);
    679         String mimeType=node.getString("mime-type",false,true);
    680         getWebAppContext().getMimeTypes().addMimeMapping(extension, mimeType);
    681     }
    682
    683     /* ------------------------------------------------------------ */
    684     protected void initWelcomeFileList(XmlParser.Node node)
    685     {
    686         if (_defaultWelcomeFileList)
    687             _welcomeFiles=null; // erase welcome files from default web.xml
    688
    689         _defaultWelcomeFileList=false;
    690         Iterator iter=node.iterator("welcome-file");
    691         while(iter.hasNext())
    692         {
    693             XmlParser.Node indexNode=(XmlParser.Node)iter.next();
    694             String welcome=indexNode.toString(false,true);
    695             _welcomeFiles=LazyList.add(_welcomeFiles,welcome);
    696         }
    697     }
    698
    699     /* ------------------------------------------------------------ */
    700     protected void initLocaleEncodingList(XmlParser.Node node)
    701     {
    702         Iterator iter=node.iterator("locale-encoding-mapping");
    703         while(iter.hasNext())
    704         {
    705             XmlParser.Node mapping=(XmlParser.Node)iter.next();
    706             String locale=mapping.getString("locale",false,true);
    707             String encoding=mapping.getString("encoding",false,true);
    708             getWebAppContext().addLocaleEncoding(locale,encoding);
    709         }
    710     }
    711
    712     /* ------------------------------------------------------------ */
    713     protected void initErrorPage(XmlParser.Node node)
    714     {
    715         String error=node.getString("error-code",false,true);
    716         if(error==null||error.length()==0)
    717             error=node.getString("exception-type",false,true);
    718         String location=node.getString("location",false,true);
    719
    720         if (_errorPages==null)
    721             _errorPages=new HashMap();
    722         _errorPages.put(error,location);
    723     }
    724
    725     /* ------------------------------------------------------------ */
    726     protected void initTagLib(XmlParser.Node node)
    727     {
    728         String uri=node.getString("taglib-uri",false,true);
    729         String location=node.getString("taglib-location",false,true);
    730
    731         getWebAppContext().setResourceAlias(uri,location);
    732     }
    733
    734     /* ------------------------------------------------------------ */
    735     protected void initJspConfig(XmlParser.Node node)
    736     {
    737         for (int i=0;i<node.size();i++)
    738         {
    739             Object o=node.get(i);
    740             if (o instanceof XmlParser.Node && "taglib".equals(((XmlParser.Node)o).getTag()))
    741                 initTagLib((XmlParser.Node)o);
    742         }
    743
    744         // Map URLs from jsp property groups to JSP servlet.
    745         // this is more JSP stupidness creaping into the servlet spec
    746         Iterator iter=node.iterator("jsp-property-group");
    747         Object paths=null;
    748         while(iter.hasNext())
    749         {
    750             XmlParser.Node group=(XmlParser.Node)iter.next();
    751             Iterator iter2 = group.iterator("url-pattern");
    752             while (iter2.hasNext())
    753             {
    754                 String url = ((XmlParser.Node) iter2.next()).toString(false, true);
    755                 url=normalizePattern(url);
    756                 paths=LazyList.add(paths,url);
    757             }
    758         }
    759
    760         if (LazyList.size(paths)>0)
    761         {
    762             String jspName=getJSPServletName();
    763             if (jspName!=null)
    764             {
    765                 ServletMapping mapping = new ServletMapping();
    766                 mapping.setServletName(jspName);
    767                 mapping.setPathSpecs(LazyList.toStringArray(paths));
    768                 _servletMappings=LazyList.add(_servletMappings,mapping);
    769             }
    770         }
    771     }
    772
    773     /* ------------------------------------------------------------ */
    774     protected void initSecurityConstraint(XmlParser.Node node)
    775     {
    776         Constraint scBase = new Constraint();
    777
    778         try
    779         {
    780             XmlParser.Node auths = node.get("auth-constraint");
    781
    782             if (auths != null)
    783             {
    784                 scBase.setAuthenticate(true);
    785                 // auth-constraint
    786                 Iterator iter = auths.iterator("role-name");
    787                 Object roles=null;
    788                 while (iter.hasNext())
    789                 {
    790                     String role = ((XmlParser.Node) iter.next()).toString(false, true);
    791                     roles=LazyList.add(roles,role);
    792                 }
    793                 scBase.setRoles(LazyList.toStringArray(roles));
    794             }
    795
    796             XmlParser.Node data = node.get("user-data-constraint");
    797             if (data != null)
    798             {
    799                 data = data.get("transport-guarantee");
    800                 String guarantee = data.toString(false, true).toUpperCase();
    801                 if (guarantee == null || guarantee.length() == 0 || "NONE".equals(guarantee))
    802                     scBase.setDataConstraint(Constraint.DC_NONE);
    803                 else if ("INTEGRAL".equals(guarantee))
    804                     scBase.setDataConstraint(Constraint.DC_INTEGRAL);
    805                 else if ("CONFIDENTIAL".equals(guarantee))
    806                     scBase.setDataConstraint(Constraint.DC_CONFIDENTIAL);
    807                 else
    808                 {
    809                     Log.warn("Unknown user-data-constraint:" + guarantee);
    810                     scBase.setDataConstraint(Constraint.DC_CONFIDENTIAL);
    811                 }
    812             }
    813             Iterator iter = node.iterator("web-resource-collection");
    814             while (iter.hasNext())
    815             {
    816                 XmlParser.Node collection = (XmlParser.Node) iter.next();
    817                 String name = collection.getString("web-resource-name", false, true);
    818                 Constraint sc = (Constraint) scBase.clone();
    819                 sc.setName(name);
    820
    821
    822                 Iterator iter2 = collection.iterator("url-pattern");
    823                 while (iter2.hasNext())
    824                 {
    825                     String url = ((XmlParser.Node) iter2.next()).toString(false, true);
    826                     url=normalizePattern(url);
    827
    828                     Iterator iter3 = collection.iterator("http-method");
    829                     if (iter3.hasNext())
    830                     {
    831                         while (iter3.hasNext())
    832                         {
    833                             String method=((XmlParser.Node) iter3.next()).toString(false, true);
    834                             ConstraintMapping mapping = new ConstraintMapping();
    835                             mapping.setMethod(method);
    836                             mapping.setPathSpec(url);
    837                             mapping.setConstraint(sc);
    838                             _constraintMappings=LazyList.add(_constraintMappings,mapping);
    839                         }
    840                     }
    841                     else
    842                     {
    843                         ConstraintMapping mapping = new ConstraintMapping();
    844                         mapping.setPathSpec(url);
    845                         mapping.setConstraint(sc);
    846                         _constraintMappings=LazyList.add(_constraintMappings,mapping);
    847                     }
    848                 }
    849             }
    850         }
    851         catch (CloneNotSupportedException e)
    852         {
    853             Log.warn(e);
    854         }
    855
    856     }
    857
    858     /* ------------------------------------------------------------ */
    859     protected void initLoginConfig(XmlParser.Node node)
    860     {
    861         XmlParser.Node method=node.get("auth-method");
    862         FormAuthenticator _formAuthenticator=null;
    863         if(method!=null)
    864         {
    865             Authenticator authenticator=null;
    866             String m=method.toString(false,true);
    867             if(Constraint.__FORM_AUTH.equals(m))
    868                 authenticator=_formAuthenticator=new FormAuthenticator();
    869             else if(Constraint.__BASIC_AUTH.equals(m))
    870                 authenticator=new BasicAuthenticator();
    871             else if(Constraint.__DIGEST_AUTH.equals(m))
    872                 authenticator=new DigestAuthenticator();
    873             else if(Constraint.__CERT_AUTH.equals(m))
    874                 authenticator=new ClientCertAuthenticator();
    875             else if(Constraint.__CERT_AUTH2.equals(m))
    876                 authenticator=new ClientCertAuthenticator();
    877             else
    878                 Log.warn("UNKNOWN AUTH METHOD: "+m);
    879             getWebAppContext().getSecurityHandler().setAuthenticator(authenticator);
    880         }
    881         XmlParser.Node name=node.get("realm-name");
    882
    883         UserRealm[] realms=ContextHandler.getCurrentContext().getContextHandler().getServer().getUserRealms();
    884
    885         String realm_name=name==null?"default":name.toString(false,true);
    886
    887         UserRealm realm=getWebAppContext().getSecurityHandler().getUserRealm();
    888         for (int i=0;realm==null && realms!=null && i<realms.length; i++)
    889         {
    890             if (realms[i]!=null && realm_name.equals(realms[i].getName()))
    891                 realm=realms[i];
    892         }
    893
    894         if (realm==null)
    895         {
    896             String msg = "Unknown realm: "+realm_name;
    897             Log.warn(msg);
    898         }
    899         else
    900             getWebAppContext().getSecurityHandler().setUserRealm(realm);
    901
    902
    903         XmlParser.Node formConfig=node.get("form-login-config");
    904         if(formConfig!=null)
    905         {
    906             if(_formAuthenticator==null)
    907                 Log.warn("FORM Authentication miss-configured");
    908             else
    909             {
    910                 XmlParser.Node loginPage=formConfig.get("form-login-page");
    911                 if(loginPage!=null)
    912                     _formAuthenticator.setLoginPage(loginPage.toString(false,true));
    913                 XmlParser.Node errorPage=formConfig.get("form-error-page");
    914                 if(errorPage!=null)
    915                 {
    916                     String ep=errorPage.toString(false,true);
    917                     _formAuthenticator.setErrorPage(ep);
    918                 }
    919             }
    920         }
    921     }
    922
    923     /* ------------------------------------------------------------ */
    924     protected void initSecurityRole(XmlParser.Node node)
    925     {}
    926
    927
    928
    929
    930     /* ------------------------------------------------------------ */
    931     protected String getJSPServletName()
    932     {
    933         if (_jspServletName==null)
    934         {
    935             Map.Entry entry= _context.getServletHandler().getHolderEntry("test.jsp");
    936             if (entry!=null)
    937             {
    938                 ServletHolder holder=(ServletHolder)entry.getValue();
    939                 _jspServletName=holder.getName();
    940             }
    941         }
    942         return _jspServletName;
    943     }
    944 }