You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by sy...@apache.org on 2002/03/21 18:16:34 UTC

cvs commit: xml-cocoon2/src/java/org/apache/cocoon/servlet BootstrapServlet.java

sylvain     02/03/21 09:16:34

  Modified:    .        changes.xml
               src/documentation/xdocs/installing index.xml
  Added:       src/java/org/apache/cocoon/servlet BootstrapServlet.java
  Log:
  New BootstrapServlet to allow Cocoon to run on some non-compliant engines :
  - tested on iPlanet Web Server 4.1.8
  - with some docs ;)
  
  Revision  Changes    Path
  1.126     +7 -1      xml-cocoon2/changes.xml
  
  Index: changes.xml
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/changes.xml,v
  retrieving revision 1.125
  retrieving revision 1.126
  diff -u -r1.125 -r1.126
  --- changes.xml	19 Mar 2002 20:17:57 -0000	1.125
  +++ changes.xml	21 Mar 2002 17:16:33 -0000	1.126
  @@ -4,7 +4,7 @@
   
   <!--
     History of Cocoon changes
  -  $Id: changes.xml,v 1.125 2002/03/19 20:17:57 nicolaken Exp $
  +  $Id: changes.xml,v 1.126 2002/03/21 17:16:33 sylvain Exp $
   -->
   
   <changes title="History of Changes">
  @@ -34,6 +34,12 @@
    </devs>
   
    <release version="@version@" date="@date@">
  +   <action dev="SW" type="add">
  +    New BootstrapServlet to allow Cocoon to run in non-compliant servlet
  +    engines that don't handle correctly servlet contexts. This servlet
  +    builds a class loader with the contents of WEB-INF/classes and
  +    WEB-INF/lib and manages resource resolution.
  +   </action>
      <action dev="NKB" type="update">
       Updated error reporting to add line, column and location
       attributes specified in SAXException and 
  
  
  
  1.16      +56 -8     xml-cocoon2/src/documentation/xdocs/installing/index.xml
  
  Index: index.xml
  ===================================================================
  RCS file: /home/cvs/xml-cocoon2/src/documentation/xdocs/installing/index.xml,v
  retrieving revision 1.15
  retrieving revision 1.16
  diff -u -r1.15 -r1.16
  --- index.xml	19 Mar 2002 14:21:29 -0000	1.15
  +++ index.xml	21 Mar 2002 17:16:33 -0000	1.16
  @@ -13,7 +13,8 @@
         <person name="Carsten Ziegeler" email="cziegeler@apache.org"/>
         <person name="Vadim Gritsenko" email="vgritsenko@apache.org"/>
         <person name="Bernhard Huber" email="berni_huber@a1.net"/>
  -      <person name="Nicola Ken Barozzi" email="nicolaken@apache.org"/>      
  +      <person name="Nicola Ken Barozzi" email="nicolaken@apache.org"/>
  +      <person name="Sylvain Wallez" email="sylvain@apache.org"/>
       </authors>
     </header>
   
  @@ -1047,12 +1048,11 @@
   [path]/JBoss-2.2.2_Tomcat-3.2.2/jboss
   [path]/JBoss-2.2.2_Tomcat-3.2.2/tomcat
        </source>
  -     <p>Subsequently,
  -       <ul>
  -         <li><code>jboss</code> denotes the <code>JBoss-2.2.2_Tomcat-3.2.2/jboss</code> directory</li>
  -         <li><code>Tomcat</code> is short for <code>JBoss-2.2.2_Tomcat-3.2.2/tomcat</code></li><li>and <code>cocoon</code> is the base directory of your Cocoon distribution or CVS checkout.</li>
  -       </ul>
  -     </p>
  +     <p>Subsequently,</p>
  +     <ul>
  +       <li><code>jboss</code> denotes the <code>JBoss-2.2.2_Tomcat-3.2.2/jboss</code> directory</li>
  +       <li><code>Tomcat</code> is short for <code>JBoss-2.2.2_Tomcat-3.2.2/tomcat</code></li><li>and <code>cocoon</code> is the base directory of your Cocoon distribution or CVS checkout.</li>
  +     </ul>
        <p>In order to get Cocoon running you have to install Xerces as default XML parser for JBoss.</p>
        <ul>
          <li>Stop the server if it is running.</li>
  @@ -1128,7 +1128,7 @@
              </li>
              <li>Copy <code>xerces-XXX.jar</code> and <code>xml-apis.jar</code>
                JAR file from <code>xml-cocoon2/lib/core/</code> to
  -             the <code>resin-2.0.x/lib/</code> directory</li>.
  +             the <code>resin-2.0.x/lib/</code> directory.</li>
            </ul>
          </li>
          <li>Copy the <code>xml-cocoon2/build/cocoon/cocoon.war</code> WAR file to <code>resin-2.0.x/webapps</code> directory
  @@ -1243,6 +1243,54 @@
   cocoon.rootdir=/absolute/path/to/jrun/servers/default/cocoon
   cocoon.class={webapp.service-class}
   webapp.mapping./cocoon=cocoon</source>
  +      </s2>
  +
  +      <s2 title="Installing on iPlanet Web Server 4.x and other engines without context management">
  +        <p>
  +          iPlanet Web Server 4.x provides the servlet 2.2 API (<code>javax.servlet.*</code> classes),
  +          but the servlet engine doesn't handle servlet contexts. This means there is no classloader
  +          built with the contents of <code>WEB-INF/classes</code> and <code>WEB-INF/lib</code> and that
  +          resolution of context resources (using <code>ServletContext.getResource()</code>) doesn't give
  +          the expected results.
  +        </p>
  +        <p>
  +          To be able to run on such non-compliant engines, Cocoon provides a bootstrap servlet in
  +          <code>org.apache.cocoon.BootstrapServlet</code>that handles all the servlet context related
  +          behaviours needed for proper functioning.
  +        </p>
  +        <p>
  +          To use this bootstrap servlet, configure your servlet engine as follows (how to do it depends
  +          on the actual engine - see below for iPlanet) :
  +        </p>
  +        <ul>
  +          <li>add cocoon.jar (and only this one) in the engine's classpath,</li>
  +          <li>declare the <code>org.apache.cocoon.servlet.BootstrapServlet</code> servlet,</li>
  +          <li>add a "<code>context-dir</code>" parameter, whose value is the absolute path to Cocoon's
  +              context (e.g. "<code>/path/webapp/cocoon</code>"),</li>
  +          <li>add any other cocoon parameters you want to this servlet (see <code>web.xml</code> for a
  +              description of available parameters),</li>
  +          <li>configure a path translation from "/" to the servlet.</li>
  +        </ul>
  +        <p>For iPlanet Web Server 4.x, this translates to :</p>
  +        <ul>
  +          <li>connect to the administration server of your web server,</li>
  +          <li>in the "Servlet" tabs, select "Configure servlet attributes", and enter the following :
  +            <ul>
  +              <li>Servlet Name : <code>cocoon</code></li>
  +              <li>Servlet Code (class name) : <code>org.apache.cocoon.servlet.BootstrapServlet</code></li>
  +              <li>Servlet Classpath : <code>/path/webapp/cocoon/WEB-INF/lib/cocoon.jar</code></li>
  +              <li>Servlet Args : <code>context-dir=/path/webapp/cocoon</code> (and any other Cocoon
  +                  parameters you want)</li>
  +            </ul>
  +         </li>
  +         <li>select "Configure Servlet Virtual Path Translation" and enter the following :
  +            <ul>
  +              <li>Virtual Path : <code>@/.*</code></li>
  +              <li>Servlet Name : <code>cocoon</code></li>
  +            </ul>
  +         </li>
  +         <li>save and apply your changes, and enjoy the latest Cocoon on an old-fashioned servlet engine !</li>
  +       </ul>
         </s2>
       </s1>
     </body>
  
  
  
  1.1                  xml-cocoon2/src/java/org/apache/cocoon/servlet/BootstrapServlet.java
  
  Index: BootstrapServlet.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <st...@apache.org>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.servlet;
  
  import javax.servlet.*;
  import javax.servlet.http.*;
  
  import java.net.URLClassLoader;
  import java.net.URL;
  import java.net.MalformedURLException;
  
  import java.io.IOException;
  import java.io.File;
  
  import java.util.*;
  import javax.servlet.ServletContext;
  import java.io.InputStream;
  import javax.servlet.RequestDispatcher;
  import javax.servlet.Servlet;
  import javax.servlet.ServletException;
  import java.util.Enumeration;
  
  /**
   * A bootstrap servlet to allow Cocoon to run in servlet engines that aren't fully
   * compliant with the servlet 2.2 spec.
   * <p>
   * This servlet adds a mandatory "context-dir" parameter to those accepted by {@see CocoonServlet},
   * which should point to Cocoon's context directory (e.g. "<code>/path-to-webapp/cocoon</code>").
   * This directory is used to :
   * <ul>
   * <li>build a classloader with the correct class path with the contents of
   *     <code>WEB-INF/classes</code> and <code>WEB-INF/lib</code> (see
   *     {@link ParanoidClassLoader}),</li>
   * <li>resolve paths for context resources.
   * </ul>
   *
   * @author <a href="mailto:sylvain@apache.org">Sylvain Wallez</a>
   * @version CVS $Id: BootstrapServlet.java,v 1.1 2002/03/21 17:16:34 sylvain Exp $
   */
  
  public class BootstrapServlet extends HttpServlet {
      
      /**
       * The name of the actual servlet class.
       */
      public static final String SERVLET_CLASS = "org.apache.cocoon.servlet.CocoonServlet";
      
      protected Servlet servlet;
      
      protected ClassLoader classloader;
      
      protected ServletContext context;
      
      public void init(ServletConfig config) throws ServletException {
          super.init(config);
          
          this.context = config.getServletContext();
          
          this.context.log("getRealPath(\"/\") = " + context.getRealPath("/"));
  
          String contextDirParam = getInitParameter("context-dir");
          if (contextDirParam == null) {
              String msg = "The 'context-dir' parameter must be set to the root of the servlet context";
              this.context.log(msg);
              throw new ServletException(msg);
          }
          
          // Ensure context dir doesn't end with a "/" (servlet spec says that paths for
          // getResource() should start by a "/")
          if (contextDirParam.endsWith("/")) {
              contextDirParam = contextDirParam.substring(0, contextDirParam.length() - 1);
          }
          
          // Ensure context dir exists and is a directory
          File contextDir = new File(contextDirParam);
          if (!contextDir.exists()) {
              String msg = "Context dir '" + contextDir + "' doesn't exist";
              this.context.log(msg);
              throw new ServletException(msg);
          }
  
          if (!contextDir.isDirectory()) {
              String msg = "Context dir '" + contextDir + "' should be a directory";
              this.context.log(msg);
              throw new ServletException(msg);
          }
          
          context.log("Context dir set to " + contextDir);
  
          this.classloader = getClassLoader(contextDirParam);
          
          try {
              Class servletClass = this.classloader.loadClass(SERVLET_CLASS);
              
              this.servlet = (Servlet)servletClass.newInstance();
          } catch(Exception e) {
              context.log("Cannot load servlet", e);
              throw new ServletException(e);
          }
          
          // Always set the context classloader. JAXP uses it to find a ParserFactory,
          // and thus fails if it's not set to the webapp classloader.
          Thread.currentThread().setContextClassLoader(this.classloader);
          
          ServletContext newContext = new ContextWrapper(context, contextDirParam);
          ServletConfig newConfig = new SimpleConfig(config.getServletName(), newContext);
          
          // Inlitialize the actual servlet
          this.servlet.init(newConfig);
          
      }
      
      /**
       * Get the classloader that will be used to create the actual servlet.
       */
      protected ClassLoader getClassLoader(String contextDirParam) throws ServletException {
          List urlList = new ArrayList();
          
          try {
              File classDir = new File(contextDirParam + "/WEB-INF/classes");
              if (classDir.exists()) {
                  if (!classDir.isDirectory()) {
                      String msg = classDir + " exists but is not a directory";
                      this.context.log(msg);
                      throw new ServletException(msg);
                  }
              
                  URL classURL = classDir.toURL();
                  context.log("Adding class directory " + classURL);
                  urlList.add(classURL);
                  
              }
              
              File libDir = new File(contextDirParam + "/WEB-INF/lib");
              File[] libraries = libDir.listFiles();
  
              for (int i = 0; i < libraries.length; i++) {
                  URL lib = libraries[i].toURL();
                  context.log("Adding class library " + lib);
                  urlList.add(lib);
              }
          } catch (MalformedURLException mue) {
              context.log("Malformed url", mue);
              throw new ServletException(mue);
          }
          
          URL[] urls = (URL[])urlList.toArray(new URL[urlList.size()]);
          
          return ParanoidClassLoader.newInstance(urls, this.getClass().getClassLoader());
      }
      
      /**
       * Service the request by delegating the call to the real servlet
       */
      public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {
  
          Thread.currentThread().setContextClassLoader(this.classloader);
          this.servlet.service(request, response);
      }
      
      /**
       * Destroy the actual servlet
       */
      public void destroy() {
  
          super.destroy();
          Thread.currentThread().setContextClassLoader(this.classloader);
          this.servlet.destroy();
      }
  
      //-------------------------------------------------------------------------
      /**
       * Implementation of <code>ServletConfig</code> passed to the actual servlet.
       * It delegates calls to the provided <code>ServletContext</code>.
       */
      public static class SimpleConfig implements ServletConfig {
          String name;
          ServletContext context;
          
          /**
           * Builds a <code>ServletConfig</code> using a servlet name and
           * a <code>ServletContext</code>.
           */
          public SimpleConfig(String name, ServletContext context) {
              this.name = name;
              this.context = context;
          }
          public String getServletName() {
              return this.name;
          }
          
          public Enumeration getInitParameterNames() {
              return this.context.getInitParameterNames();
          }
          
          public ServletContext getServletContext() {
              return this.context;
          }
          
          public String getInitParameter(String name) {
              return context.getInitParameter(name);
          }
      }
  
      //-------------------------------------------------------------------------
      /**
       * Wrapper for the <code>ServletContext</code> passed to the actual servlet.
       * It implements all resource-related methods using the provided context
       * root directory. Other calls are delegated to the wrapped context.
       */
      public static class ContextWrapper implements ServletContext {
          ServletContext context;
          String contextRoot;
          
          /**
           * Builds a wrapper around an existing context, and handle all
           * resource resolution relatively to <code>contextRoot</code>
           */
          public ContextWrapper(ServletContext context, String contextRoot) {
              this.context = context;
              this.contextRoot = contextRoot;
          }
          
          public ServletContext getContext(String param) {
              return this.context.getContext(param);
          }
      
          public int getMajorVersion() {
              return this.context.getMajorVersion();
          }
      
          public int getMinorVersion() {
              return this.context.getMinorVersion();
          }
      
          public String getMimeType(String param) {
              return this.context.getMimeType(param);
          }
  
          /**
           * Returns the resource URL by appending <code>path</code> to the context
           * root. If this doesn't point to an existing file, <code>null</code> is
           * returned.
           */
          public URL getResource(String path) throws MalformedURLException {
              File file = new File(this.contextRoot + path);
              if (file.exists()) {
                  URL result = file.toURL();
                  //this.context.log("getResource(" + path + ") = " + result);
                  return result;
              } else {
                  //this.context.log("getResource(" + path + ") = null");
                  return null;
              }
          }
      
          /**
           * Returns the stream for the result of <code>getResource()</code>, or
           * <code>null</code> if the resource doesn't exist.
           */
          public InputStream getResourceAsStream(String path) {
              try {
                  URL url = getResource(path);
                  return (url == null) ? null : url.openStream();
              } catch(Exception e) {
                  this.context.log("getResourceAsStream(" + path + ") failed", e);
                  return null;
              }
          }
      
          public RequestDispatcher getRequestDispatcher(String param) {
              return this.context.getRequestDispatcher(param);
          }
      
          public RequestDispatcher getNamedDispatcher(String param) {
              return this.context.getNamedDispatcher(param);
          }
      
          public Servlet getServlet(String param) throws ServletException {
              return this.context.getServlet(param);
          }
      
          public Enumeration getServlets() {
              return this.context.getServlets();
          }
      
          public Enumeration getServletNames() {
              return this.context.getServletNames();
          }
      
          public void log(String msg) {
              this.context.log(msg);
          }
      
          public void log(Exception ex, String msg) {
              this.context.log(ex, msg);
          }
      
          public void log(String msg, Throwable thr) {
              this.context.log(msg, thr);
          }
  
          /**
           * Appends <code>path</code> to the context root.
           */
          public String getRealPath(String path) {
              String result = this.contextRoot + path;
              //this.context.log("getRealPath(" + path + ") = " + result);
              return result;
          }
      
          public String getServerInfo() {
              return this.context.getServerInfo();
          }
      
          public String getInitParameter(String param) {
              return this.context.getInitParameter(param);
          }
      
          public Enumeration getInitParameterNames() {
              return this.context.getInitParameterNames();
          }
      
          public Object getAttribute(String param) {
              Object result = this.context.getAttribute(param);
              //this.context.log("getAttribute(" + param + ") = " + result);
              return result;
          }
      
          public Enumeration getAttributeNames() {
              return this.context.getAttributeNames();
          }
      
          public void setAttribute(String name, Object value) {
              this.context.setAttribute(name, value);
          }
      
          public void removeAttribute(String name) {
              this.context.removeAttribute(name);
          }
      }
  }
  
  
  
  

----------------------------------------------------------------------
In case of troubles, e-mail:     webmaster@xml.apache.org
To unsubscribe, e-mail:          cocoon-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: cocoon-cvs-help@xml.apache.org