Servlet Filter Compression Zip File project

Click here to download eclipse supported ZIP file




 

    

package com.cv.servlet.filter.compression;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class GZIPFilter implements Filter {
  
  private static final Logger LOGGER = Logger.getLogger(GZIPFilter.class);

  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chainthrows IOException, ServletException {
    
    LOGGER.info(
        "LOGGER : doFilter(ServletRequest, ServletResponse , FilterChain chain)" );

      if (req instanceof HttpServletRequest) {
      HttpServletRequest request = (HttpServletRequestreq;

      HttpServletResponse response = (HttpServletResponseres;
      String ae = request.getHeader("accept-encoding");
      if (ae != null && ae.indexOf("gzip"!= -1) {
        GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
        chain.doFilter(req, wrappedResponse);
        wrappedResponse.finishResponse();
        return;
      }
      chain.doFilter(req, res);
    }
  }

  public void init(FilterConfig filterConfig) {
    // noop
  }

  public void destroy() {
    // noop
  }
}


 

    
/*
 * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
 * http://www.jspbook.com. You may freely use the code both commercially
 * and non-commercially. If you like the code, please pick up a copy of
 * the book and help support the authors, development of more free code,
 * and the JSP/Servlet/J2EE community.
 */
package com.cv.servlet.filter.compression;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class GZIPResponseStream extends ServletOutputStream {
  
  private static final Logger LOGGER = Logger.getLogger(GZIPResponseStream.class);
  protected ByteArrayOutputStream baos = null;
  protected GZIPOutputStream gzipstream = null;
  protected boolean closed = false;
  protected HttpServletResponse response = null;
  protected ServletOutputStream output = null;

  public GZIPResponseStream(HttpServletResponse responsethrows IOException {
    super();
    closed = false;
    this.response = response;
    this.output = response.getOutputStream();
    baos = new ByteArrayOutputStream();
    gzipstream = new GZIPOutputStream(baos);
  }

  public void close() throws IOException {
    if (closed) {
      LOGGER.error(
          "LOGGER : This output stream has already been closed" );

      throw new IOException("This output stream has already been closed");
    }
    gzipstream.finish();

    byte[] bytes = baos.toByteArray();

    response.addHeader("Content-Length", Integer.toString(bytes.length));
    response.addHeader("Content-Encoding""gzip");
    output.write(bytes);
    output.flush();
    output.close();
    closed = true;
  }

  public void flush() throws IOException {
    if (closed) {
      LOGGER.error(
          "LOGGER : Cannot flush a closed output stream" );

      throw new IOException("Cannot flush a closed output stream");
    }
    gzipstream.flush();
  }

  public void write(int bthrows IOException {
    if (closed) {
      LOGGER.error(
          "LOGGER : Cannot write to a closed output stream" );

      throw new IOException("Cannot write to a closed output stream");
    }
    gzipstream.write((byteb);
  }

  public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
  }

  public void write(byte b[]int off, int lenthrows IOException {
    if (closed) {
      LOGGER.error(
          "LOGGER : Cannot write to a closed output stream" );

      throw new IOException("Cannot write to a closed output stream");
    }
    gzipstream.write(b, off, len);
  }

  public boolean closed() {
    return (this.closed);
  }

  public void reset() {
  }
  
}


 

    
package com.cv.servlet.filter.compression;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.log4j.Logger;

public class GZIPResponseWrapper extends HttpServletResponseWrapper {
  private static final Logger LOGGER = Logger.getLogger(GZIPResponseWrapper.class);
  protected HttpServletResponse origResponse = null;
  protected ServletOutputStream stream = null;
  protected PrintWriter writer = null;

  public GZIPResponseWrapper(HttpServletResponse response) {
    super(response);
    origResponse = response;
  }

  public ServletOutputStream createOutputStream() throws IOException {
    return (new GZIPResponseStream(origResponse));
  }

  public void finishResponse() {
    try {
      if (writer != null) {
        writer.close();
      else {
        if (stream != null) {
          stream.close();
        }
      }
    catch (IOException e) {}
  }

  public void flushBuffer() throws IOException {
    stream.flush();
  }

  public ServletOutputStream getOutputStream() throws IOException {
    if (writer != null) {
      
      LOGGER.error(
        "LOGGER : getWriter() has already been called!" );

      throw new IllegalStateException("getWriter() has already been called!");
    }

    if (stream == null)
      stream = createOutputStream();
    return (stream);
  }

  public PrintWriter getWriter() throws IOException {
    if (writer != null) {
      return (writer);
    }

    if (stream != null) {
      LOGGER.error(
        "LOGGER : getWriter() has already been called!" );

      throw new IllegalStateException("getOutputStream() has already been called!");
    }

   stream = createOutputStream();
   writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
   return (writer);
  }

  public void setContentLength(int length) {}
}


 

    
package com.cv.servlet.filter.compression;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class HttpServletImpl extends HttpServlet {
  private static final Logger LOGGER = Logger.getLogger(HttpServletImpl.class);
   private boolean isMultipart;
   private String storagePath;
   private int maxFileSize = 9690567;
   private int maxMemSize = 1024;
   private File file ;

   @Override
  public void init() throws ServletException {
    // process only if its multipart content
    File file = new File("C:\\files");
    if (!file.exists()) {
      file.mkdir();
      storagePath = file.getPath()+"\\";
      LOGGER.info("LOGGER : Folder has been created successfully : " + storagePath);
    else {
      storagePath = file.getPath()+"\\";
      LOGGER.info("LOGGER : Folder already exist : " + storagePath);
    }

  }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
    LOGGER.info(
        "LOGGER : Entered into doGet(HttpServletRequest ,HttpServletResponse ) of HttpServletImpl class... ");

      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if!isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>")
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMaxmaxFileSize );

      try
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
  
      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      while i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            String nameFile = null;
            iffileName.lastIndexOf("\\">= ){
              nameFile = fileName.substringfileName.lastIndexOf("\\"));
               file = new FilestoragePath + nameFile;
            }else{
              nameFile = fileName.substring(fileName.lastIndexOf("\\")+1);
               file = new FilestoragePath + nameFile;
            }
            fi.writefile ;
            out.println("Uploaded file from: " + fileName + "<br><br>");
            
            out.println("Uploaded file to: " + storagePath+nameFile + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
    LOGGER.info(
        "LOGGER : Entered into doPost(HttpServletRequest ,HttpServletResponse ) of HttpServletImpl class... ");

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   
}



<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
<center>
<form method="post" action="HttpServletImpl"
enctype="multipart/form-data">
<table>
<tr>
<td>Select file to upload:</td>
<td><input type="file" name="uploadFile"/</td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n




<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>ServletFilterCompressionZipFile</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <log4j.version>1.2.16</log4j.version> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <groupId>com.cv.servlet.filter.compression</groupId> </project>




 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>HttpServletImpl</servlet-name> <servlet-class>com.cv.servlet.filter.compression.HttpServletImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>HttpServletImpl</servlet-name> <url-pattern>/HttpServletImpl</url-pattern> </servlet-mapping> <filter> <filter-name>TestFilter</filter-name> <filter-class>com.cv.servlet.filter.compression.GZIPFilter</filter-class> </filter> <filter-mapping> <filter-name>TestFilter</filter-name> <url-pattern>/HttpServletImpl</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> </web-app>


No comments:

Post a Comment