/*
 * $Id: DisplayFileServlet.java,v 1.5 2004/11/10 15:02:49 koppy Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: DisplayFileServlet.java,v $
 * Revision 1.5  2004/11/10 15:02:49  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.4  2004/05/05 12:28:46  marbobo
 * + Bugfix für Internet-Explorer
 *
 * Revision 1.3  2004/05/05 12:19:29  koppy
 * exception handling
 *
 * Revision 1.2  2004/05/05 12:17:47  koppy
 * + content-disposition header
 *
 * Revision 1.1  2004/05/05 12:03:31  koppy
 * 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;

/**
 * This class represents 
 * 
 * @created 05.05.2004
 * @author <a href="mailto:andreas.koop@c-lab.de">Andreas Koop</a>
 */
public class DisplayFileServlet 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 = request.getParameter( "file" );
		
		if( filePath == null )
			throw new ServletException( "file parameter not set!" );
		
		File file 		= new File( filePath ); 
		
		response.setContentLength( (int)file.length() );
		response.setContentType( "text/plain" );
		response.setHeader( "Content-Disposition", "inline;filename=" + file.getName() + ".txt" );
		response.setBufferSize(8192);

		try {
			InputStream in	= new BufferedInputStream( new FileInputStream(file));
			OutputStream out= new BufferedOutputStream( response.getOutputStream() );
			
			int bytesRead 	= 0;		
			byte[] buffer 	= new byte[8192];
			
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {					
				out.write(buffer, 0, bytesRead);
				out.flush();
			}
			
			in.close();
			out.close();
			
		} catch (IOException e) {
			VKCLogManager.errorLog( this, "", e.getMessage(), e );
			
			throw new ServletException( e.getMessage() );
		}
	}
}
