package com.mplus.deploy.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

public class FileDownloadServlet extends HttpServlet {
	
	// constructor
    public FileDownloadServlet() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("filename");
		BufferedInputStream fin = null;
		BufferedOutputStream outs = null;
		
		try{
			
			File f = new File(this.getServletContext().getRealPath("/file"), fileName);
			
			//String url = this.getClass().getResource("").getPath(); 
			//url.substring(1,url.indexOf(".metadata"))+"Test/WebContent"
			response.setContentType("application/octet-stream");
			
			response.setHeader("Content-Transfer-Encoding:", "binary");
		    response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
		    response.setHeader("Content-Length", "" + f.length());
		    response.setHeader("Pragma", "no-cache;");
		    response.setHeader("Expires", "-1;");
	
		    byte b[] = new byte[1024];
			fin = new BufferedInputStream(new FileInputStream(f));
			outs = new BufferedOutputStream(response.getOutputStream());

		
			int read = 0;
			while ((read = fin.read(b)) != -1)
			{
				outs.write(b,0,read);
			}

		}catch (Exception e){
			response.sendRedirect(request.getContextPath() + "/error404.html");
		}finally{
			
			if (outs!=null) outs.close();
			if (fin!=null) fin.close();
		}
	}
}
