/*
 * $Id$
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log$
 * Revision 1.2  2006/04/29 18:39:48  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.1  2006/04/11 19:46:34  marbobo
 * + Initiale Version
 *
 */
package vkc.servlets;

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

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

import vkc.misc.VKCLogManager;
import vkc.util.FileUtils;
import vkc.util.VKCStringUtils;
import vkc.webdav.URLUtil;

/**
 * This class represents 
 * 
 * @created 10.04.2006
 * @author marbobo
 */
public class DownloadFileServlet extends HttpServlet {
	/**
	 * Method to process a HTTP Request
	 *
	 * @param request
	 * @param response
	 *
	 * @throws ServletException
	 */
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		String filePath = VKCStringUtils.decodeXmlEntities(VKCStringUtils.base64Decode(request.getParameter("file")));

		if (filePath == null) {
			throw new ServletException("file parameter not set!");
		}
		
		File file = new File(filePath);

		if (!file.exists()) {
			throw new ServletException("file not found!");
		}
		
		String fileName = URLUtil.contentDispositionEncode(file.getName());
		
		response.setContentLength((int) file.length());
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		response.setBufferSize(8192);
        //Muss rein, sonst sagt der IE, wenn in der web.xml das security-constraint aktiviert ist: 
        //"Internet Explorer cannot download <filename> from <our website>
        //Internet Explorer was not able to open this Internet Site. The requested site is either unavailable or cannot be found. Please try again later"
        //
        //Quelle: http://forum.java.sun.com/thread.jspa?forumID=45&threadID=233446
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");

		try {
			InputStream in = new BufferedInputStream(new FileInputStream(file));
	        OutputStream out = new BufferedOutputStream(response.getOutputStream());

	        FileUtils.write(in, out);

	        in.close();
	        out.close();
		} catch (IOException e) {
			VKCLogManager.errorLog(this, "", e.getMessage(), e);
			throw new ServletException(e.getMessage());
		}
	}
}
