FileDocCategorySizeDatePackage
SendFilter.javaAPI DocExample2381Mon May 05 15:12:28 BST 2003com.jspservletcookbook

SendFilter

public class SendFilter extends Object implements Filter

Fields Summary
private static final String
PDF_DIR
private static final String
PDF_CONTENT_TYPE
private FilterConfig
config
Constructors Summary
public SendFilter()
Creates new SessionFilter

    
        
      
    
Methods Summary
public voiddestroy()

        /*called before the Filter instance is removed 
        from service by the web container*/
    
public voiddoFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain)

        
         //get the file name from the 'file' parameter
	  String fileName = request.getParameter("file");
	  if (fileName == null || fileName.equals(""))
	       throw new ServletException("Invalid or non-existent file parameter in SendPdf component.");
	  
	  if (fileName.indexOf(".pdf") == -1)
	      fileName = fileName + ".pdf";
		  
	  ServletOutputStream stream = null;
	  BufferedInputStream buf = null;
	  HttpServletResponse httpResp = null;
	 try{
	 
	 httpResp = (HttpServletResponse) response;
	 stream = httpResp.getOutputStream();
	 File pdf = new File(PDF_DIR + "/" + fileName);
	 
	  //set response headers
	  httpResp.setContentType(PDF_CONTENT_TYPE);
	  httpResp.addHeader("Content-Disposition","attachment; filename="+fileName );
	  httpResp.setContentLength( (int) pdf.length() );
	  
	 FileInputStream input = new FileInputStream(pdf);
	 buf = new BufferedInputStream(input);
	 int readBytes = 0;
	 //read from the file; write to the ServletOutputStream
	   while((readBytes = buf.read()) != -1)
	       stream.write(readBytes);
		
	 
	 } catch (Exception ioe){
	 
	  //  throw new ServletException(ioe.getMessage());
	  System.out.println(ioe.getMessage());
		 
	 } finally {
	 
	 if (buf != null)
	     buf.close();
     if (stream != null){
	     stream.flush();
		 //stream.close();
		}
	 
	 }//end finally
        chain.doFilter(request,httpResp);
    
public voidinit(javax.servlet.FilterConfig filterConfig)

        
        System.out.println("Instance created of "+getClass().getName());
        this.config = filterConfig;