package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Demonstrates a servlet translating paths and reading files.
 *  <P>
 *  Part of tutorial on servlets and JSP that appears at
 *  http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
 *  1999 Marty Hall; may be freely used or adapted.
 */

public class FileRetriever extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    String path = getServletContext().getRealPath("/");
    String file = request.getParameter("file");
    if (file == null)
      sendError(response, "You must supply a 'file' parameter.");
    else
      file = path + file;
    try {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Reading Files from Servlets";
      out.println(ServletUtilities.headWithTitle(title) +
                  "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                  "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                  "<H2>" + file + "</H2>\n" +
                  "<XMP>");
      BufferedInputStream in =
	new BufferedInputStream(new FileInputStream(file));
      int nextByte;
      while((nextByte = in.read()) != -1)
	out.write(nextByte);
      in.close();
      out.println("</XMP></BODY></HTML>");
    } catch(FileNotFoundException fnfe) {
      sendError(response,
                "No such file in: " + path);
    } catch(IOException ioe) {
      sendError(response, "IOException: " + ioe);
    }
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  private void sendError(HttpServletResponse response,
                         String message)
      throws IOException {
    response.sendError(response.SC_NOT_FOUND, message);
  }
}
