You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by cr...@apache.org on 2002/08/04 03:04:16 UTC

cvs commit: jakarta-commons-sandbox/filters/src/java/org/apache/commons/filters RequestDumperFilter.java SetCharacterEncodingFilter.java

craigmcc    2002/08/03 18:04:16

  Added:       filters  build.xml
               filters/src/conf MANIFEST.MF
               filters/src/java/org/apache/commons/filters
                        RequestDumperFilter.java
                        SetCharacterEncodingFilter.java
  Log:
  Add a couple of filters from the Tomcat example application to seed the
  library of simple, reusable, filters.
  
  Revision  Changes    Path
  1.1                  jakarta-commons-sandbox/filters/build.xml
  
  Index: build.xml
  ===================================================================
  <project name="Filters" default="compile" basedir=".">
  
  
  <!--
          "Filters" component of the Jakarta Commons Subproject
          $Id: build.xml,v 1.1 2002/08/04 01:04:16 craigmcc Exp $
  -->
  
  
  <!-- ========== Initialize Properties ===================================== -->
  
  
    <property file="build.properties"/>                <!-- Component local   -->
    <property file="../build.properties"/>             <!-- Commons local     -->
    <property file="${user.home}/build.properties"/>   <!-- User local        -->
  
  
  <!-- ========== External Dependencies ===================================== -->
  
    <property name="commons-logging.jar"     value="/usr/local/commons-logging-1.0/commons-logging.jar"/>
    <property name="junit.jar"               value="/usr/local/junit3.7/junit.jar"/>
    <property name="servlet.jar"             value="/usr/local/servletapi/servlet.jar"/>
  
  
  <!-- ========== Component Declarations ==================================== -->
  
  
    <!-- The name of this component -->
    <property name="component.name"          value="filters"/>
  
    <!-- The primary package name of this component -->
    <property name="component.package"       value="org.apache.commons.filters"/>
  
    <!-- The title of this component -->
    <property name="component.title"         value="Simple Filters Library"/>
  
    <!-- The current version number of this component -->
    <property name="component.version"       value="0.1-dev"/>
  
    <!-- The base directory for compilation targets -->
    <property name="build.home"              value="target"/>
  
    <!-- The base directory for component configuration files -->
    <property name="conf.home"               value="src/conf"/>
  
    <!-- The base directory for distribution targets -->
    <property name="dist.home"               value="dist"/>
  
    <!-- The base directory for component sources -->
    <property name="source.home"             value="src/java"/>
  
    <!-- The base directory for unit test sources -->
    <property name="test.home"               value="src/test"/>
  
  
  <!-- ========== Compiler Defaults ========================================= -->
  
  
    <!-- Should Java compilations set the 'debug' compiler option? -->
    <property name="compile.debug"           value="true"/>
  
    <!-- Should Java compilations set the 'deprecation' compiler option? -->
    <property name="compile.deprecation"     value="false"/>
  
    <!-- Should Java compilations set the 'optimize' compiler option? -->
    <property name="compile.optimize"        value="true"/>
  
    <!-- Construct compile classpath -->
    <path id="compile.classpath">
      <pathelement location="${build.home}/classes"/>
      <pathelement location="${commons-logging.jar}"/>
      <pathelement location="${servlet.jar}"/>
    </path>
  
  
  <!-- ========== Test Execution Defaults =================================== -->
  
  
    <!-- Construct unit test classpath -->
    <path id="test.classpath">
      <pathelement location="${build.home}/classes"/>
      <pathelement location="${build.home}/tests"/>
      <pathelement location="${commons-logging.jar}"/>
      <pathelement location="${junit.jar}"/>
      <pathelement location="${servlet.jar}"/>
    </path>
  
    <!-- Should all tests fail if one does? -->
    <property name="test.failonerror"        value="true"/>
  
    <!-- The test runner to execute -->
    <property name="test.runner"             value="junit.textui.TestRunner"/>
  
  
  <!-- ========== Executable Targets ======================================== -->
  
  
    <target name="init"
     description="Initialize and evaluate conditionals">
      <echo message="-------- ${component.name} ${component.version} --------"/>
      <filter  token="name"                  value="${component.package}"/>
      <filter  token="version"               value="${component.version}"/>
    </target>
  
  
    <target name="prepare" depends="init"
     description="Prepare build directory">
      <mkdir dir="${build.home}"/>
      <mkdir dir="${build.home}/classes"/>
      <mkdir dir="${build.home}/conf"/>
      <mkdir dir="${build.home}/tests"/>
    </target>
  
  
    <target name="static" depends="prepare"
     description="Copy static files to build directory">
      <tstamp/>
      <copy  todir="${build.home}/conf" filtering="on">
        <fileset dir="${conf.home}" includes="*.MF"/>
      </copy>
    </target>
  
  
    <target name="compile" depends="static"
     description="Compile shareable components">
      <javac  srcdir="${source.home}"
             destdir="${build.home}/classes"
               debug="${compile.debug}"
         deprecation="${compile.deprecation}"
            optimize="${compile.optimize}">
        <classpath refid="compile.classpath"/>
      </javac>
      <copy    todir="${build.home}/classes" filtering="on">
        <fileset dir="${source.home}" excludes="**/*.java"/>
      </copy>
    </target>
  
  
    <target name="compile.tests" depends="compile"
     description="Compile unit test cases">
      <javac  srcdir="${test.home}"
             destdir="${build.home}/tests"
               debug="${compile.debug}"
         deprecation="${compile.deprecation}"
            optimize="${compile.optimize}">
        <classpath refid="test.classpath"/>
      </javac>
      <copy    todir="${build.home}/tests" filtering="on">
        <fileset dir="${test.home}" excludes="**/*.java"/>
      </copy>
    </target>
  
  
    <target name="clean"
     description="Clean build and distribution directories">
      <delete    dir="${build.home}"/>
      <delete    dir="${dist.home}"/>
    </target>
  
  
    <target name="all" depends="clean,compile"
     description="Clean and compile all components"/>
  
  
    <target name="javadoc" depends="compile"
     description="Create component Javadoc documentation">
      <mkdir      dir="${dist.home}"/>
      <mkdir      dir="${dist.home}/docs"/>
      <mkdir      dir="${dist.home}/docs/api"/>
      <javadoc sourcepath="${source.home}"
                  destdir="${dist.home}/docs/api"
             packagenames="org.apache.commons.*"
                   author="true"
                  private="true"
                  version="true"
                 overview="src/java/overview.html"
                 doctitle="&lt;h1&gt;${component.title} (Version ${component.version})&lt;/h1&gt;"
              windowtitle="${component.title} (Version ${component.version})"
                   bottom="Copyright (c) 2001-2002 - Apache Software Foundation">
        <classpath  refid="compile.classpath"/>
      </javadoc>
    </target>
  
  
    <target name="dist" depends="compile,javadoc"
     description="Create binary distribution">
      <mkdir      dir="${dist.home}"/>
      <copy      file="../LICENSE"
                todir="${dist.home}"/>
      <mkdir      dir="${build.home}/classes/META-INF"/>
      <copy      file="../LICENSE"
               tofile="${build.home}/classes/META-INF/LICENSE.txt"/>
  <!--
      <copy      file="RELEASE-NOTES.txt"
                todir="${dist.home}"/>
  -->
      <jar    jarfile="${dist.home}/commons-${component.name}.jar"
              basedir="${build.home}/classes"
             manifest="${build.home}/conf/MANIFEST.MF"/>
    </target>
  
  
  <!-- ========== Unit Test Targets ========================================= -->
  
  <!--
    <target name="test" depends="compile.tests,
                                 test.digester,
                                 test.matching,
                                 test.matching.extended,
                                 test.rule,
                                 test.bpsr,
                                 test.xmlrules
                                "
     description="Run all unit test cases">
    </target>
  
  
    <target name="test.xmlrules" depends="compile.tests"
     description="Run tests for loading Digester rules from XML ...">
      <echo message="Running xmlrules tests ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.xmlrules.DigesterLoaderTestSuite"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  
  
    <target name="test.bpsr" depends="compile.tests"
     description="Run tests for BeanPropertySetterRule ...">
      <echo message="Running BeanPropertySetterRule tests ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.BeanPropertySetterRuleTestCase"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  
  
    <target name="test.digester" depends="compile.tests"
     description="Run basic Digester unit tests ...">
      <echo message="Running basic Digester tests ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.DigesterTestCase"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  
  
    <target name="test.matching" depends="compile.tests"
     description="Run rule Digester test cases">
      <echo message="Running rule Digester tests ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.RulesBaseTestCase"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  
  
    <target name="test.matching.extended" depends="compile.tests"
     description="Run rule Digester extended test cases">
      <echo message="Running rule Digester tests for ExtendedBaseRules ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.EBRTestCase"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  
  
    <target name="test.rss" depends="compile.tests"
     description="Run RSSDigester test cases">
      <echo message="Running RSSDigester tests ..."/>
      <java classname="org.apache.commons.digester.rss.RSSDigester"
                 fork="yes">
        <classpath refid="rss.classpath"/>
      </java>
    </target>
  
  
    <target name="test.rule" depends="compile.tests"
     description="Run rule Digester unit tests ...">
      <echo message="Running Rule tests ..."/>
      <java classname="${test.runner}" fork="yes"
          failonerror="${test.failonerror}">
        <arg value="org.apache.commons.digester.RuleTestCase"/>
        <classpath refid="test.classpath"/>
      </java>
    </target>
  -->
  
  
  </project>
  
  
  
  1.1                  jakarta-commons-sandbox/filters/src/conf/MANIFEST.MF
  
  Index: MANIFEST.MF
  ===================================================================
  Extension-Name: @name@
  Specification-Vendor: Apache Software Foundation
  Specification-Version: 1.0
  Implementation-Vendor: Apache Software Foundation
  Implementation-Version: @version@
  
  
  
  
  1.1                  jakarta-commons-sandbox/filters/src/java/org/apache/commons/filters/RequestDumperFilter.java
  
  Index: RequestDumperFilter.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/filters/src/java/org/apache/commons/filters/RequestDumperFilter.java,v 1.1 2002/08/04 01:04:16 craigmcc Exp $
   * $Revision: 1.1 $
   * $Date: 2002/08/04 01:04:16 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, 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 acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", 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 names without prior written
   *    permission of the Apache Group.
   *
   * 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 (INCLUDING, 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.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  
  package org.apache.commons.filters;
  
  
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.io.StringWriter;
  import java.sql.Timestamp;
  import java.util.Enumeration;
  import java.util.Locale;
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.ServletContext;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  
  
  /**
   * <p>Example filter that dumps interesting state information about a request
   * to the associated servlet context log file, before allowing the servlet
   * to process the request in the usual way.  This can be installed as needed
   * to assist in debugging problems.</p>
   *
   * @author Craig McClanahan
   * @version $Revision: 1.1 $ $Date: 2002/08/04 01:04:16 $
   */
  
  public final class RequestDumperFilter implements Filter {
  
  
      // ----------------------------------------------------- Instance Variables
  
  
      /**
       * The filter configuration object we are associated with.  If this value
       * is null, this filter instance is not currently configured.
       */
      private FilterConfig filterConfig = null;
  
  
      // --------------------------------------------------------- Public Methods
  
  
      /**
       * Take this filter out of service.
       */
      public void destroy() {
  
          this.filterConfig = null;
  
      }
  
  
      /**
       * Time the processing that is performed by all subsequent filters in the
       * current filter stack, including the ultimately invoked servlet.
       *
       * @param request The servlet request we are processing
       * @param result The servlet response we are creating
       * @param chain The filter chain we are processing
       *
       * @exception IOException if an input/output error occurs
       * @exception ServletException if a servlet error occurs
       */
      public void doFilter(ServletRequest request, ServletResponse response,
                           FilterChain chain)
  	throws IOException, ServletException {
  
          if (filterConfig == null)
  	    return;
  
  	// Render the generic servlet request properties
  	StringWriter sw = new StringWriter();
  	PrintWriter writer = new PrintWriter(sw);
  	writer.println("Request Received at " +
  		       (new Timestamp(System.currentTimeMillis())));
  	writer.println(" characterEncoding=" + request.getCharacterEncoding());
  	writer.println("     contentLength=" + request.getContentLength());
  	writer.println("       contentType=" + request.getContentType());
  	writer.println("            locale=" + request.getLocale());
  	writer.print("           locales=");
  	Enumeration locales = request.getLocales();
  	boolean first = true;
  	while (locales.hasMoreElements()) {
  	    Locale locale = (Locale) locales.nextElement();
  	    if (first)
  	        first = false;
  	    else
  	        writer.print(", ");
  	    writer.print(locale.toString());
  	}
  	writer.println();
  	Enumeration names = request.getParameterNames();
  	while (names.hasMoreElements()) {
  	    String name = (String) names.nextElement();
  	    writer.print("         parameter=" + name + "=");
  	    String values[] = request.getParameterValues(name);
  	    for (int i = 0; i < values.length; i++) {
  	        if (i > 0)
  		    writer.print(", ");
  		writer.print(values[i]);
  	    }
  	    writer.println();
  	}
  	writer.println("          protocol=" + request.getProtocol());
  	writer.println("        remoteAddr=" + request.getRemoteAddr());
  	writer.println("        remoteHost=" + request.getRemoteHost());
  	writer.println("            scheme=" + request.getScheme());
  	writer.println("        serverName=" + request.getServerName());
  	writer.println("        serverPort=" + request.getServerPort());
  	writer.println("          isSecure=" + request.isSecure());
  
  	// Render the HTTP servlet request properties
  	if (request instanceof HttpServletRequest) {
  	    writer.println("---------------------------------------------");
  	    HttpServletRequest hrequest = (HttpServletRequest) request;
  	    writer.println("       contextPath=" + hrequest.getContextPath());
  	    Cookie cookies[] = hrequest.getCookies();
              if (cookies == null)
                  cookies = new Cookie[0];
  	    for (int i = 0; i < cookies.length; i++) {
  	        writer.println("            cookie=" + cookies[i].getName() +
  			       "=" + cookies[i].getValue());
  	    }
  	    names = hrequest.getHeaderNames();
  	    while (names.hasMoreElements()) {
  	        String name = (String) names.nextElement();
  		String value = hrequest.getHeader(name);
  	        writer.println("            header=" + name + "=" + value);
  	    }
  	    writer.println("            method=" + hrequest.getMethod());
  	    writer.println("          pathInfo=" + hrequest.getPathInfo());
  	    writer.println("       queryString=" + hrequest.getQueryString());
  	    writer.println("        remoteUser=" + hrequest.getRemoteUser());
  	    writer.println("requestedSessionId=" +
  			   hrequest.getRequestedSessionId());
  	    writer.println("        requestURI=" + hrequest.getRequestURI());
  	    writer.println("       servletPath=" + hrequest.getServletPath());
  	}
  	writer.println("=============================================");
  
  	// Log the resulting string
  	writer.flush();
  	filterConfig.getServletContext().log(sw.getBuffer().toString());
  
  	// Pass control on to the next filter
          chain.doFilter(request, response);
  
      }
  
  
      /**
       * Place this filter into service.
       *
       * @param filterConfig The filter configuration object
       */
      public void init(FilterConfig filterConfig) throws ServletException {
  
  	this.filterConfig = filterConfig;
  
      }
  
  
      /**
       * Return a String representation of this object.
       */
      public String toString() {
  
  	if (filterConfig == null)
  	    return ("RequestDumperFilter()");
  	StringBuffer sb = new StringBuffer("RequestDumperFilter(");
  	sb.append(filterConfig);
  	sb.append(")");
  	return (sb.toString());
  
      }
  
  
  }
  
  
  
  
  1.1                  jakarta-commons-sandbox/filters/src/java/org/apache/commons/filters/SetCharacterEncodingFilter.java
  
  Index: SetCharacterEncodingFilter.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons-sandbox/filters/src/java/org/apache/commons/filters/SetCharacterEncodingFilter.java,v 1.1 2002/08/04 01:04:16 craigmcc Exp $
   * $Revision: 1.1 $
   * $Date: 2002/08/04 01:04:16 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, 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 acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", 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 names without prior written
   *    permission of the Apache Group.
   *
   * 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 (INCLUDING, 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.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  
  package org.apache.commons.filters;
  
  
  import java.io.IOException;
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.UnavailableException;
  
  
  /**
   * <p>Example filter that sets the character encoding to be used in parsing the
   * incoming request, either unconditionally or only if the client did not
   * specify a character encoding.  Configuration of this filter is based on
   * the following initialization parameters:</p>
   * <ul>
   * <li><strong>encoding</strong> - The character encoding to be configured
   *     for this request, either conditionally or unconditionally based on
   *     the <code>ignore</code> initialization parameter.  This parameter
   *     is required, so there is no default.</li>
   * <li><strong>ignore</strong> - If set to "true", any character encoding
   *     specified by the client is ignored, and the value returned by the
   *     <code>selectEncoding()</code> method is set.  If set to "false,
   *     <code>selectEncoding()</code> is called <strong>only</strong> if the
   *     client has not already specified an encoding.  By default, this
   *     parameter is set to "true".</li>
   * </ul>
   *
   * <p>Although this filter can be used unchanged, it is also easy to
   * subclass it and make the <code>selectEncoding()</code> method more
   * intelligent about what encoding to choose, based on characteristics of
   * the incoming request (such as the values of the <code>Accept-Language</code>
   * and <code>User-Agent</code> headers, or a value stashed in the current
   * user's session.</p>
   *
   * @author Craig McClanahan
   * @version $Revision: 1.1 $ $Date: 2002/08/04 01:04:16 $
   */
  
  public class SetCharacterEncodingFilter implements Filter {
  
  
      // ----------------------------------------------------- Instance Variables
  
  
      /**
       * The default character encoding to set for requests that pass through
       * this filter.
       */
      protected String encoding = null;
  
  
      /**
       * The filter configuration object we are associated with.  If this value
       * is null, this filter instance is not currently configured.
       */
      protected FilterConfig filterConfig = null;
  
  
      /**
       * Should a character encoding specified by the client be ignored?
       */
      protected boolean ignore = true;
  
  
      // --------------------------------------------------------- Public Methods
  
  
      /**
       * Take this filter out of service.
       */
      public void destroy() {
  
          this.encoding = null;
          this.filterConfig = null;
  
      }
  
  
      /**
       * Select and set (if specified) the character encoding to be used to
       * interpret request parameters for this request.
       *
       * @param request The servlet request we are processing
       * @param result The servlet response we are creating
       * @param chain The filter chain we are processing
       *
       * @exception IOException if an input/output error occurs
       * @exception ServletException if a servlet error occurs
       */
      public void doFilter(ServletRequest request, ServletResponse response,
                           FilterChain chain)
  	throws IOException, ServletException {
  
          // Conditionally select and set the character encoding to be used
          if (ignore || (request.getCharacterEncoding() == null)) {
              String encoding = selectEncoding(request);
              if (encoding != null)
                  request.setCharacterEncoding(encoding);
          }
  
  	// Pass control on to the next filter
          chain.doFilter(request, response);
  
      }
  
  
      /**
       * Place this filter into service.
       *
       * @param filterConfig The filter configuration object
       */
      public void init(FilterConfig filterConfig) throws ServletException {
  
  	this.filterConfig = filterConfig;
          this.encoding = filterConfig.getInitParameter("encoding");
          String value = filterConfig.getInitParameter("ignore");
          if (value == null)
              this.ignore = true;
          else if (value.equalsIgnoreCase("true"))
              this.ignore = true;
          else if (value.equalsIgnoreCase("yes"))
              this.ignore = true;
          else
              this.ignore = false;
  
      }
  
  
      // ------------------------------------------------------ Protected Methods
  
  
      /**
       * Select an appropriate character encoding to be used, based on the
       * characteristics of the current request and/or filter initialization
       * parameters.  If no character encoding should be set, return
       * <code>null</code>.
       * <p>
       * The default implementation unconditionally returns the value configured
       * by the <strong>encoding</strong> initialization parameter for this
       * filter.
       *
       * @param request The servlet request we are processing
       */
      protected String selectEncoding(ServletRequest request) {
  
          return (this.encoding);
  
      }
  
  
  }
  
  
  

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>