ZIP Servlet

Click here to download eclipse supported ZIP file




 

    
package com.cv.servlet.zip;

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;
/**
 @author Chandra Vardhan
 *
 */
public class CompressionFilter implements Filter {

  private static final Logger LOGGER = Logger.getLogger(CompressionFilter.class);

  public void destroy() {
    LOGGER.info("Entered into destroy(---) of CompressionFilter class... ");
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequestrequest;
    HttpServletResponse httpResponse = (HttpServletResponseresponse;
    String acceptEncoding = httpRequest.getHeader("Accept-Encoding");
    LOGGER.info("Entered into doFilter(---) of CompressionFilter class... ");
    LOGGER.info("Accept-Encoding formats : "+acceptEncoding);
    if (acceptEncoding != null) {
      if (acceptEncoding.indexOf("gzip">= 0) {
        GZIPHttpServletResponseWrapper gzipResponse = new GZIPHttpServletResponseWrapper(httpResponse);
        chain.doFilter(request, gzipResponse);
        // ServletResponseGZIPOutputStream
        // gZIPHttpServletResponseWrapper
        // =gzipResponse.getOutputStream();
        gzipResponse.finish();
        return;
      }
    }
    chain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfigthrows ServletException {
    
    LOGGER.info("Entered into init(---) of CompressionFilter class... ");
  }

}


 

    
package com.cv.servlet.zip;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
 @author Chandra Vardhan
 *
 */
public class CompressionResponseStream extends ServletOutputStream {

  public CompressionResponseStream(HttpServletResponse origResponse) {
  }

  public void setDebugLevel(int debug) {
    
  }

  public void setBuffer(int threshold) {
    
  }

  @Override
  public void write(int bthrows IOException {
    
  }

}


 

    
package com.cv.servlet.zip;

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;
/**
 @author Chandra Vardhan
 *
 */
public class CompressionServletResponseWrapper extends HttpServletResponseWrapper {

    // ----------------------------------------------------- Constructor

    /**
     * Calls the parent constructor which creates a ServletResponse adaptor
     * wrapping the given response object.
     */

    public CompressionServletResponseWrapper(HttpServletResponse response) {
        super(response);
        origResponse = response;
        if (debug > 1) {
            System.out.println("CompressionServletResponseWrapper constructor gets called");
        }
    }


    // ----------------------------------------------------- Instance Variables

    /**
     * Original response
     */

    protected HttpServletResponse origResponse = null;

    /**
     * Descriptive information about this Response implementation.
     */

    protected static final String info = "CompressionServletResponseWrapper";

    /**
     * The ServletOutputStream that has been returned by
     <code>getOutputStream()</code>, if any.
     */

    protected ServletOutputStream stream = null;


    /**
     * The PrintWriter that has been returned by
     <code>getWriter()</code>, if any.
     */

    protected PrintWriter writer = null;

    /**
     * The threshold number to compress
     */
    protected int threshold = 0;

    /**
     * Debug level
     */
    private int debug = 0;

    /**
     * Content type
     */
    protected String contentType = null;

    // --------------------------------------------------------- Public Methods


    /**
     * Set content type
     */
    public void setContentType(String contentType) {
        if (debug > 1) {
            System.out.println("setContentType to "+contentType);
        }
        this.contentType = contentType;
        origResponse.setContentType(contentType);
    }


    /**
     * Set threshold number
     */
    public void setCompressionThreshold(int threshold) {
        if (debug > 1) {
            System.out.println("setCompressionThreshold to " + threshold);
        }
        this.threshold = threshold;
    }


    /**
     * Set debug level
     */
    public void setDebugLevel(int debug) {
        this.debug = debug;
    }


    /**
     * Create and return a ServletOutputStream to write the content
     * associated with this Response.
     *
     @exception IOException if an input/output error occurs
     */
    public ServletOutputStream createOutputStream() throws IOException {
        if (debug > 1) {
            System.out.println("createOutputStream gets called");
        }

        CompressionResponseStream stream = new CompressionResponseStream(origResponse);
        stream.setDebugLevel(debug);
        stream.setBuffer(threshold);

        return stream;

    }


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


    // ------------------------------------------------ ServletResponse Methods


    /**
     * Flush the buffer and commit this response.
     *
     @exception IOException if an input/output error occurs
     */
    public void flushBuffer() throws IOException {
        if (debug > 1) {
            System.out.println("flush buffer @ CompressionServletResponseWrapper");
        }
        ((CompressionResponseStream)stream).flush();

    }

    /**
     * Return the servlet output stream associated with this Response.
     *
     @exception IllegalStateException if <code>getWriter</code> has
     *  already been called for this response
     @exception IOException if an input/output error occurs
     */
    public ServletOutputStream getOutputStream() throws IOException {

        if (writer != null)
            throw new IllegalStateException("getWriter() has already been called for this response");

        if (stream == null)
            stream = createOutputStream();
        if (debug > 1) {
            System.out.println("stream is set to "+stream+" in getOutputStream");
        }

        return (stream);

    }

    /**
     * Return the writer associated with this Response.
     *
     @exception IllegalStateException if <code>getOutputStream</code> has
     *  already been called for this response
     @exception IOException if an input/output error occurs
     */
    public PrintWriter getWriter() throws IOException {

        if (writer != null)
            return (writer);

        if (stream != null)
            throw new IllegalStateException("getOutputStream() has already been called for this response");

        stream = createOutputStream();
        if (debug > 1) {
            System.out.println("stream is set to "+stream+" in getWriter");
        }
        //String charset = getCharsetFromContentType(contentType);
        String charEnc = origResponse.getCharacterEncoding();
        if (debug > 1) {
            System.out.println("character encoding is " + charEnc);
        }
        // HttpServletResponse.getCharacterEncoding() shouldn't return null
        // according the spec, so feel free to remove that "if"
        if (charEnc != null) {
            writer = new PrintWriter(new OutputStreamWriter(stream, charEnc));
        else {
            writer = new PrintWriter(stream);
        }
        
        return (writer);

    }


    public void setContentLength(int length) {
    }


    /**
     * Returns character from content type. This method was taken from tomcat.
     @author rajo
     */
    private static String getCharsetFromContentType(String type) {

        if (type == null) {
            return null;
        }
        int semi = type.indexOf(";");
        if (semi == -1) {
            return null;
        }
        String afterSemi = type.substring(semi + 1);
        int charsetLocation = afterSemi.indexOf("charset=");
        if(charsetLocation == -1) {
            return null;
        else {
            String afterCharset = afterSemi.substring(charsetLocation + 8);
            String encoding = afterCharset.trim();
            return encoding;
        }
    }

}


 

    
package com.cv.servlet.zip;

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;

/**
 @author Chandra Vardhan
 *
 */
public class GZIPHttpServletResponseWrapper extends HttpServletResponseWrapper {

  private static final Logger LOGGER = Logger.getLogger(GZIPHttpServletResponseWrapper.class);
  private ServletResponseGZIPOutputStream gzipStream;
  private ServletOutputStream outputStream;
  private PrintWriter printWriter;

  public GZIPHttpServletResponseWrapper(HttpServletResponse responsethrows IOException {
    super(response);
    LOGGER.info("Entered into GZIPHttpServletResponseWrapper(-) constructor of GZIPHttpServletResponseWrapper class... ");
    response.addHeader("Content-Encoding""gzip");
  }

  public void finish() throws IOException {

    LOGGER.info("Entered into finish(---) of GZIPHttpServletResponseWrapper class... ");
    if (printWriter != null) {
      printWriter.close();
    }
    if (outputStream != null) {
      outputStream.close();
    }
    if (gzipStream != null) {
      gzipStream.close();
    }
  }

  @Override
  public void flushBuffer() throws IOException {
    LOGGER.info("Entered into flushBuffer(---) of GZIPHttpServletResponseWrapper class... ");
    if (printWriter != null) {
      printWriter.flush();
    }
    if (outputStream != null) {
      outputStream.flush();
    }
    super.flushBuffer();
  }

  @Override
  public ServletOutputStream getOutputStream() throws IOException {
    LOGGER.info("Entered into getOutputStream(---) of GZIPHttpServletResponseWrapper class... ");
    if (printWriter != null) {
      throw new IllegalStateException("printWriter already defined");
    }
    if (outputStream == null) {
      initGzip();
      outputStream = gzipStream;
    }
    return outputStream;
  }

  @Override
  public PrintWriter getWriter() throws IOException {
    LOGGER.info("Entered into getWriter(---) of GZIPHttpServletResponseWrapper class... ");
    if (outputStream != null) {
      throw new IllegalStateException("printWriter already defined");
    }
    if (printWriter == null) {
      initGzip();
      printWriter = new PrintWriter(new OutputStreamWriter(gzipStream, getResponse().getCharacterEncoding()));
    }
    return printWriter;
  }

  @Override
  public void setContentLength(int len) {
  }

  private void initGzip() throws IOException {
    LOGGER.info("Entered into initGzip(---) of GZIPHttpServletResponseWrapper class... ");
    
    gzipStream = new ServletResponseGZIPOutputStream(getResponse().getOutputStream());
  }

}


 

    
package com.cv.servlet.zip;

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

import javax.servlet.ServletOutputStream;
/**
 @author Chandra Vardhan
 *
 */
public class GZIPServletOutputStream2 extends ServletOutputStream {  
    protected GZIPOutputStream internalGzipOS;  
      
    public GZIPServletOutputStream2(ServletOutputStream outthrows IOException {  
        this.internalGzipOS = new GZIPOutputStream(out);  
    }  
      
    @Override  
    public void write(int bthrows IOException {  
        internalGzipOS.write(b);  
    }  
  
}  


 

    
package com.cv.servlet.zip;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletOutputStream;

import org.apache.log4j.Logger;
/**
 @author Chandra Vardhan
 *
 */
public class ServletResponseGZIPOutputStream extends ServletOutputStream {

  
  private static final Logger LOGGER = Logger.getLogger(ServletResponseGZIPOutputStream.class);
    GZIPOutputStream gzipStream;
    final AtomicBoolean open = new AtomicBoolean(true);
    OutputStream output;

    public ServletResponseGZIPOutputStream(OutputStream outputthrows IOException {
      LOGGER.info("Entered into ServletResponseGZIPOutputStream(-) constructor of ServletResponseGZIPOutputStream class... ");
        this.output = output;
        gzipStream = new GZIPOutputStream(output);
    }

    @Override
    public void close() throws IOException {
      LOGGER.info("Entered into close(-) of ServletResponseGZIPOutputStream class... ");
        if (open.compareAndSet(true, false)) {
            gzipStream.close();
        }
    }

    @Override
    public void flush() throws IOException {
      LOGGER.info("Entered into flush(-) of ServletResponseGZIPOutputStream class... ");
        gzipStream.flush();
    }

    @Override
    public void write(byte b[]) throws IOException {
      LOGGER.info("Entered into write(byte[]) of ServletResponseGZIPOutputStream class... ");
        write(b, 0, b.length);
    }

    @Override
    public void write(byte b[]int off, int lenthrows IOException {
      LOGGER.info("Entered into write(byte,int,int) of ServletResponseGZIPOutputStream class... ");
        if (!open.get()) {
            throw new IOException("Stream closed!");
        }
        gzipStream.write(b, off, len);
    }

    @Override
    public void write(int bthrows IOException {
      LOGGER.info("Entered into write(int) of ServletResponseGZIPOutputStream class... ");
        if (!open.get()) {
            throw new IOException("Stream closed!");
        }
        gzipStream.write(b);
    }

}


 

    
package com.cv.servlet.zip;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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;

/**
 * Servlet implementation class ZipServlet
 
 @author Chandra Vardhan
 *
 */
public class ZipServlet extends HttpServlet {

      private static final long serialVersionUID = 1L;
       
      // location to store file uploaded
      private static final String UPLOAD_DIRECTORY = "upload";
   
      // upload settings
      private static final int MEMORY_THRESHOLD   = 1024 1024 3;  // 3MB
      private static final int MAX_FILE_SIZE      = 1024 1024 40// 40MB
      private static final int MAX_REQUEST_SIZE   = 1024 1024 50// 50MB
   
      /**
       * Upon receiving file upload submission, parses the request to read
       * upload data and saves the file on disk.
       */
      protected void doPost(HttpServletRequest request,
              HttpServletResponse responsethrows ServletException, IOException {
          // checks if the request actually contains upload file
          if (!ServletFileUpload.isMultipartContent(request)) {
              // if not, we stop here
              PrintWriter writer = response.getWriter();
              writer.println("Error: Form must has enctype=multipart/form-data.");
              writer.flush();
              return;
          }
   
          // configures upload settings
          DiskFileItemFactory factory = new DiskFileItemFactory();
          // sets memory threshold - beyond which files are stored in disk
          factory.setSizeThreshold(MEMORY_THRESHOLD);
          // sets temporary location to store files
          factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
   
          ServletFileUpload upload = new ServletFileUpload(factory);
           
          // sets maximum size of upload file
          upload.setFileSizeMax(MAX_FILE_SIZE);
           
          // sets maximum size of request (include file + form data)
          upload.setSizeMax(MAX_REQUEST_SIZE);
   
          // constructs the directory path to store upload file
          // this path is relative to application's directory
          String uploadPath = getServletContext().getRealPath("")
                  + File.separator + UPLOAD_DIRECTORY;
           
          // creates the directory if it does not exist
          File uploadDir = new File(uploadPath);
          if (!uploadDir.exists()) {
              uploadDir.mkdir();
          }
   
          try {
              // parses the request's content to extract file data
              @SuppressWarnings("unchecked")
              List<FileItem> formItems = upload.parseRequest(request);
   
              if (formItems != null && formItems.size() 0) {
                  // iterates over form's fields
                  for (FileItem item : formItems) {
                      // processes only fields that are not form fields
                      if (!item.isFormField()) {
                          String fileName = new File(item.getName()).getName();
                          String filePath = uploadPath + File.separator + fileName;
                          File storeFile = new File(filePath);
   
                          // saves the file on disk
                          item.write(storeFile);
                          request.setAttribute("message",
                              "Upload has been done successfully!");
                      }
                  }
              }
          catch (Exception ex) {
              request.setAttribute("message",
                      "There was an error: " + ex.getMessage());
          }
          // redirects client to message page
          getServletContext().getRequestDispatcher("/message.jsp").forward(
                  request, response);
      }
  }



<%@ 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>Upload Result</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>



<%@ 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="uploadFile" enctype="multipart/form-data">
Select file to upload: <input type="file" name="uploadFile" /> <br />
<br /> <input type="submit" value="Upload" />
</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>zipServlet</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.zip</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>FileUploadServlet</servlet-name> <servlet-class>com.cv.servlet.zip.ZipServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/uploadFile</url-pattern> </servlet-mapping> <filter> <filter-name>CompressionFilter</filter-name> <filter-class>com.cv.servlet.zip.CompressionFilter</filter-class> </filter> <filter-mapping> <filter-name>CompressionFilter</filter-name> <url-pattern>/uploadFile</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> </web-app>


No comments:

Post a Comment