Commit f650eed6 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+21 −0
Changes for CompressionFilter/build.properties: 21 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Blank Struts w/ Tiles and Dummy Model Webapp
# 
# Configure this file for your local build/deployment environment.
# In particular, these properties will need tweaking:
#   * webapp.name
#   * tomcat.home

# Generic build properties
build.dir=./build

# Webapp properties for the project
webapp.name=compress
webapp.build.dir=${build.dir}/${webapp.name}
webapp.virtual.host=localhost

# Tomcat properties
tomcat.home=/Users/bryan/Work/Books/HeadFirst/HF-SCWCD/Jakarta/tomcat
tomcat.deployment.dir=${tomcat.home}/webapps
tomcat.context.config.file=${tomcat.home}/conf/Catalina/${webapp.virtual.host}/${webapp.name}.xml
servlet.jar=${tomcat.home}/common/lib/servlet-api.jar
jsp.jar=${tomcat.home}/common/lib/jsp-api.jar
+204 −0
Changes for CompressionFilter/build.xml: 204 added lines, 0 removed lines.
Original line number Diff line number Diff line
<project name="Blank Struts w/Tiles w/Model Webapp" default="webapp" basedir=".">


  <!-- =================== Initialize Property Values ===================== -->
  <property file="build.properties"/>


  <!-- =================== Help: High-Level Targets Documentation ========= -->
  <target name="help">
    <echo>
Build structure of the Web Application
Toplevel targets:

   help     -- this message

   all      -- cleans and then builds/deploys this Web app.

   webapp   -- (re)builds and deploys this Web app. to Tomcat
     * deployWebapp -- Deploys the WAR file to Tomcat
     * undeployWebapp -- Undeploys the WAR file
     * deployStaticFiles -- Copies the webapp files to the deployment area
     * buildWebapp -- Builds the WAR file from the webapp build area
     * compileWebapp -- Compiles the source code into the webapp build area
     * staticWebapp -- Copies the webapp files into the webapp build area
     * prepareWebapp -- Creates the webapp build area

   database    -- THIS IS NOT A TARGET
     * createDatabase -- This creates a new database and populates the schema
     * destroyDatabase -- This destroys the database (CAUTION: loss of data)
     * createSchema -- This creates the tables, indexes, etc. for the schema
     * destroySchema -- This drops the tables, etc (CAUTION: loss of data)
     * populateInitData -- This populates the tables (CAUTION: possible corruption of data)

   clean    -- Cleans the whole build structure
     * cleanWebapp -- Cleans only the webapp part of the build structure
     * cleanTmpFiles -- Cleans the build area of temporary files
    </echo>
  </target>


  <!-- =================== Convenient Synonyms ============================ -->
  <target name="all" depends="clean,webapp" />
  <target name="webapp" depends="deployWebapp" />


  <!-- =================== CLEAN: All ===================================== -->
  <target name="clean" depends="cleanWebapp,cleanTmpFiles" >
    <delete dir="${build.dir}" />
  </target>
  <!-- =================== CLEAN: WebApp Directory ======================== -->
  <target name="cleanWebapp">
    <delete dir="${webapp.build.dir}" />
  </target>
  <!-- =================== CLEAN: Backup Files ============================ -->
  <target name="cleanTmpFiles">
    <delete>
      <fileset dir="." defaultExcludes="no" includes="**/*~"/>
    </delete>
  </target>


  <!-- =================== WEBAPP: Deploy to Tomcat ======================== -->
  <target name="deployWebapp" depends="undeployWebapp,buildWebapp" >

    <!-- Copy the newly built WAR file into the deployment directory -->
    <copy file="${build.dir}/${webapp.name}.war" todir="${tomcat.deployment.dir}" />

  </target>

  <!-- =================== WEBAPP: Undeploy  ======================== -->
  <target name="undeployWebapp" >

    <!-- Delete the deployment directory -->
    <delete dir="${tomcat.deployment.dir}/${webapp.name}" />
    <delete file="${tomcat.deployment.dir}/${webapp.name}.war" />

  </target>

  <!-- =================== WEBAPP: Build WAR File ========================= -->
  <target name="buildWebapp" depends="compileWebapp">
    <jar jarfile="${build.dir}/${webapp.name}.war" basedir="${webapp.build.dir}" />
  </target>

  <!-- =================== WEBAPP: Compile Web Components ================= -->
  <target name="compileWebapp" depends="staticWebapp">
    <javac   srcdir="src"
             destdir="${webapp.build.dir}/WEB-INF/classes/"
             deprecation="on" debug="on" optimize="off">

      <classpath>

	<!-- Include all JAR files in my local library -->
        <fileset dir="lib">
          <include name="*.jar"/>
        </fileset>

	<!-- Include all common libraries in Tomcat -->
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>

      </classpath>

    </javac>
  </target>

  <!-- =================== WEBAPP: Copy Static Web Files ================== -->
  <target name="staticWebapp" depends="prepareWebapp">

    <!-- Copy web files to the Tomcat webapp -->
    <copy todir="${webapp.build.dir}/">
      <fileset dir="web" />
    </copy>

    <!-- Copy webapp configuration files -->
    <copy todir="${webapp.build.dir}/WEB-INF/">
      <fileset dir="etc" />
    </copy>

    <!-- Copy library files -->
    <copy todir="${webapp.build.dir}/WEB-INF/lib/">
      <fileset dir="lib" />
    </copy>

  </target>

  <!-- =================== WEBAPP: Create WebApp Directories ============== -->
  <target name="prepareWebapp">
    <mkdir dir="${webapp.build.dir}" />
    <mkdir dir="${webapp.build.dir}/WEB-INF" />
    <mkdir dir="${webapp.build.dir}/WEB-INF/lib" />
    <mkdir dir="${webapp.build.dir}/WEB-INF/classes" />
  </target>

  <!-- =================== WEBAPP: Send Static Web Files to Deployment area -->
  <target name="deployStaticFiles" >

    <!-- Copy web files to the Tomcat webapp -->
    <copy todir="${tomcat.deployment.dir}/${webapp.name}/">
      <fileset dir="web" />
    </copy>

    <!-- Copy hidden JSP pages -->
    <copy todir="${tomcat.deployment.dir}/${webapp.name}/WEB-INF/web">
      <fileset dir="etc/web" />
    </copy>

  </target>


  <!-- =================== DATABASE: All ================================== -->
  <target name="database">
    <echo>This 'database' is not a target.  Please choose from:
     * createDatabase -- This creates a new database and populates the schema
     * destroyDatabase -- This destroys the database (CAUTION: loss of data)
     * createSchema -- This creates the tables, indexes, etc. for the schema
     * destroySchema -- This drops the tables, etc (CAUTION: loss of data)
     * populateInitData -- This populates the tables (CAUTION: possible corruption of data)
    </echo>
  </target>

  <!-- =================== DATABASE: Create Database ======================= -->
  <target name="createDatabase" >
    <sql driver="${database.driver}" classpath="${database.client.jar}"
	 url="${database.url.new}" userid="${database.user}" password="${database.password}"
	 src="${database.create.file}"
	 print="true" output="output/${database.create.file}"
	 onerror="continue" caching="true" />
  </target>

  <!-- =================== DATABASE: Destroy Database ====================== -->
  <target name="destroyDatabase" >
    <echo>This target is not yet implemented.</echo>
  </target>

  <!-- =================== DATABASE: Create Schema ======================== -->
  <target name="createSchema">
    <sql driver="${database.driver}" classpath="${database.client.jar}"
	 url="${database.url}" userid="${database.user}" password="${database.password}"
	 src="${database.create.file}"
	 print="true" output="output/${database.create.file}"
	 onerror="continue" caching="true" />
  </target>

  <!-- =================== DATABASE: Destroy Schema ======================== -->
  <target name="destroySchema">
    <sql driver="${database.driver}" classpath="${database.client.jar}"
	 url="${database.url}" userid="${database.user}" password="${database.password}"
	 src="${database.destroy.file}"
	 print="true" output="output/${database.destroy.file}"
	 onerror="continue" caching="true" />
  </target>

  <!-- =================== DATABASE: Populate Schema ====================== -->
  <target name="populateInitData" >
    <sql driver="${database.driver}" classpath="${database.client.jar}"
	 url="${database.url}" userid="${database.user}" password="${database.password}"
	 src="${database.initData.file}"
	 print="true" output="output/${database.initData.file}"
	 onerror="continue" caching="true" />
  </target>


</project>
+28 −0
Changes for CompressionFilter/etc/web.xml: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <display-name>HF-SCWCD: Tests</display-name>
    <description>
        Test the compression filter.
    </description>

   <filter>
     <filter-name>Compression Filter</filter-name>
     <filter-class>com.example.CompressionFilter</filter-class>
   </filter>

   <filter-mapping>
     <filter-name>Compression Filter</filter-name> 
     <url-pattern>*.html</url-pattern> 
   </filter-mapping>

   <filter-mapping>
     <filter-name>Compression Filter</filter-name> 
     <url-pattern>*.jsp</url-pattern> 
   </filter-mapping>

</web-app>
+78 −0
Changes for CompressionFilter/src/CompressionFilter.java: 78 added lines, 0 removed lines.
Original line number Diff line number Diff line
package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * This filter provides a mechanism to compress the response body content.
 * This type of filter would common be applied to any text content, such as
 * HTML, but not to most media formats, such as PNG or MPEG, because these
 * are already compressed.
 */
public class CompressionFilter implements Filter {

  private ServletContext ctx;
  private FilterConfig cfg;

    /**
     * The init method saves the config object and a quick reference to the
     * servlet context object (for logging purposes).
     */
  public void init(FilterConfig cfg) 
	 throws ServletException {
    this.cfg = cfg;
    ctx = cfg.getServletContext();
    ctx.log(cfg.getFilterName() + " initialized.");
  }

    /**
     * The heart of this filter wraps the response object with a Decorator
     * that wraps the output stream with a compression I/O stream.
     * Compression of the output stream is only performed if and only if
     * the client includes an Accept-Encoding header (specifically, for gzip).
     */
  public void doFilter(ServletRequest req,
		       ServletResponse resp,
		       FilterChain fc)
	 throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // Dose the client accept GZIP compression?
    String valid_encodings = request.getHeader("Accept-Encoding");
    if ( (valid_encodings != null) && (valid_encodings.indexOf("gzip") > -1) ) {

      // Then wrap the response object with a compression wrapper
      // We'll look at this class in a minute.
      CompressionResponseWrapper wrappedResp
	= new CompressionResponseWrapper(response);

      // Declare that the response content is being GZIP encoded.
      wrappedResp.setHeader("Content-Encoding", "gzip");

      // Chain to the next component (thus processing the request)
      fc.doFilter(request, wrappedResp);

      // A GZIP compression stream must be "finished" which also
      // flushes the GZIP stream buffer which sends all of its
      // data to the original response stream.
      GZIPOutputStream gzos = wrappedResp.getGZIPOutputStream();
      gzos.finish();
      // The container handles the rest of the work.

      ctx.log(cfg.getFilterName() + ": finished the request.");

    } else {
      fc.doFilter(request, response);
      ctx.log(cfg.getFilterName() + ": no encoding performed.");
    }
  }

  public void destroy() {
      // nulling out my instance variables
      cfg = null;
      ctx = null;
  }
}
+136 −0
Changes for CompressionFilter/src/CompressionResponseWrapper.java: 136 added lines, 0 removed lines.
Original line number Diff line number Diff line
package com.example;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * This response wrapper decorates the original response object by add a
 * compression decorator on the original servlet output stream.
 */
class CompressionResponseWrapper extends HttpServletResponseWrapper {

  /** the compressed output stream for the servlet response */
  private GZIPServletOutputStream servletGzipOS = null;

  /** the PrintWriter object to the compressed output stream */
  private PrintWriter pw = null;

  /**
   * The constructor performs the Decorator responsibility of storing
   * a reference to the object being decorated, in this case the HTTP
   * response object.
   */
  CompressionResponseWrapper(HttpServletResponse resp) {
    super(resp);
  }

  //
  // Override HttpServletResponse methods to use our stream objects
  //

  /**
   * This state variable holds the first stream object created.
   */
  private Object streamUsed = null;

  /**
   * Provide access to a decorated servlet output stream.
   */
  public ServletOutputStream getOutputStream() throws IOException {
      // Allow the servlet to access a servlet output stream (SOS)
      // only if the servlet has not already accessed the print writer.
    if ( (streamUsed != null) && (streamUsed != servletGzipOS) ) {
      throw new IllegalStateException();
    }
    // Wrap the original servlet output stream with our compression SOS.
    // We'll look at this class in a minute.
    if ( servletGzipOS == null ) {
      servletGzipOS
	  = new GZIPServletOutputStream(getResponse()
					.getOutputStream());
      streamUsed = servletGzipOS;
    }
    return servletGzipOS;
  }

  /**
   *  Provide access to a decorated print writer.
   */
  public PrintWriter getWriter() throws IOException {
    // Allow the servlet to access a print writer only if the
    // servlet has not already accessed the servlet output stream.
    if ( (streamUsed != null) && (streamUsed != pw) ) {
      throw new IllegalStateException();
    }
    // To make a print writer, we have to first wrap the servlet output stream
    // and then wrap the compression SOS in two additional OS decorators:
    // OutputStreamWriter which converts characters into bytes, and then a
    // PrintWriter on top of the OSWriter object.
    if ( pw == null ) {
      servletGzipOS
	  = new GZIPServletOutputStream(getResponse().getOutputStream());
      // Use the response charset to create the OSWriter
      OutputStreamWriter osw
	  = new OutputStreamWriter(servletGzipOS,
				   getResponse().getCharacterEncoding());
      // Wrap the OSWriter in the PrintWriter
      pw = new PrintWriter(osw);
      streamUsed = pw;
    }
    return pw;
  }

  /**
   * Ignore this method, because the real output will be compressed.
   */
  public void setContentLength(int len) { }

  //
  // Decorator methods (used by the Filter)
  //

  /**
   * This gives the compression filter a handle on the GZIP output stream
   * so that it (the filter) can "finish" and flush the GZIP stream.
   */
  public GZIPOutputStream getGZIPOutputStream() {
    return this.servletGzipOS.internalGzipOS;
  }
}


/**
 * This helper class is a Decorator on the ServletOutputStream abstract
 * class which delegates the real work of compressing the generated content
 * using a standard GZIP output stream.
 * 
 * There is only one abstract method in the SOS class which this Decorator
 * must implement: write(int).  This is where all of the delegation magic
 * occurs.
 */
class GZIPServletOutputStream extends ServletOutputStream {

  /**
   * Keep a reference to raw GZIP stream.
   * This instance variable is package-private to allow the compression
   * response wrapper access to this variable.
   */
  GZIPOutputStream internalGzipOS;

  /** Decorator constructor */
  GZIPServletOutputStream(ServletOutputStream sos) throws IOException {
    this.internalGzipOS = new GZIPOutputStream(sos);
  }

  /**
   * This method implements the compression decoration by delegating the
   * write() call to the GZIP compression stream, which is wrapping the
   * original servlet output stream, which is (ultimately) wrapping the
   * TCP network output stream to the client.
   */
  public void write(int param) throws java.io.IOException {
    internalGzipOS.write(param);
  }
}
Loading