// NationalFlag.java
//
// from Java 1.1 Developer's Handbook
// by P. Heller, S. Roberts
// Sybex, Inc. 1997 ISBN 0-7821-1919-0
//
// edited by Jeff Schmitt
// October, 1998

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

public class NationalFlag extends HttpServlet {
  File flagDir;
  Hashtable flags = new Hashtable();

  private static final int SUFFIX      = 0;
  private static final int FILENAME    = 1;
  private static final int CONTENTTYPE = 2;

  private String defflagname[] = {
    "us",   "usa-flag.jpg", "image/jpeg"
  };

  private String flagnames[][] = {
    {"nl",  "nl-flag.jpg",  "image/jpeg"},
    {"fr",  "fr-flag.jpg",  "image/jpeg"},
    {"uk",  "uk-flag.jpg",  "image/jpeg"}
};

  public void init() throws ServletException {
//    String fileDir = getInitParameter("flagDirectory");
    String fileDir;
//    if (fileDir == null) {
      fileDir = "/usr/faculty/schmitt/WWW/server/servlet/sybex_jdh" +
                File.separator;
//    }
    log("fileDir = "+fileDir);
    flagDir = new File(fileDir);
    if (!(flagDir.exists() && flagDir.isDirectory())) {
      log("Invalid flagDirectory value specified");
      throw new ServletException("Can't find flag Directory");
    } else {
      File f = new File(flagDir, defflagname[FILENAME]);
      if (!(f.exists() && f.canRead())) {
        log("can't find default flag ");
        throw new ServletException("Can't find default flag");
      }
    }
    for (int i = 0; i < flagnames.length; i++) {
      flags.put(flagnames[i][0], flagnames[i]);
    }
  }

  public void service(HttpServletRequest req,
                      HttpServletResponse resp)
    throws IOException {
    String country = null;
    if (req.getParameter("country") != null) {
      country = req.getParameter("country");
    } else {
      country = req.getRemoteHost();
      int i = country.lastIndexOf('.');
      if (i != -1) {
        country = country.substring(i + 1);
      }
    }

    String [] flagdef = (String [])(flags.get(country));
    if (flagdef == null) {
      flagdef = defflagname;
    }

    try {
      resp.setContentType(flagdef[2]);
      File f = new File(flagDir + flagdef[1]);

      int size = (int)f.length();
      resp.setContentLength(size);

      byte [] buffer = new byte[size];
      FileInputStream in = new FileInputStream(f);
      in.read(buffer);
      resp.getOutputStream().write(buffer);
    } catch (IOException e) {
      log("Trouble: " + e);
      throw e;
    } finally {
      resp.getOutputStream().close();
    }
  }
}
