package com.marinilli.b2.c7.deploylet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
public class LaunchServlet extends HttpServlet {
  private ServerRepository server;
  private static final String CONTENT_TYPE = "text/html";
  /**Initialize global variables*/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    deployletRepositoryLookup();
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>LaunchServlet</title></head>");
    out.println("<body>");
    out.println("<p>Welcome to the accounting procedure homepage.</p>");

    String dName = request.getRemoteHost();
    System.out.println("Deploylet-server="+server.getDeployletName(dName));
    Deploylet serverDeploylet = server.getServerDeploylet(dName);

    out.println("<p>");

    String uhoh =
      "<OBJECT classid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\""+
        "width=\"492\" height=\"280\" align=\"baseline\""+
        "codebase=\"http://server/b2/c7/j2re-1_3_1-win.exe#Version=1,3,0,0\">"+
        "<PARAM NAME=\"archive\" VALUE=\"clientDeploylet.jar\">"+
        "<PARAM NAME=\"code\" VALUE=\"com.marinilli.b2.c7.deploylet.AccountApplet\">"+
        "<PARAM NAME=\"codebase\" VALUE=\".\">"+
        "<PARAM NAME=\"type\" VALUE=\"application/x-java-applet;version=1.3\">"+
        "<PARAM NAME=\"name\" VALUE=\""+ serverDeploylet.getName() +"\">"+
        "<COMMENT>"+
            "<EMBED type=\"application/x-java-applet;version=1.3\" width=\"462\" height=\"280\""+
                "align=\"baseline\" code=\"com.marinilli.b2.c7.deploylet.AccountApplet\" codebase=\".\""+
                "archive=\"clientDeploylet.jar\"" +
                "name=\"" + serverDeploylet.getName() + "\""+
                "pluginspage=\"http://server/b2/c7/j2re-1_3_1-win.exe\">"+
            "<NOEMBED></COMMENT>"+
                "No JDK 1.3 support for APPLET!!"+
            "</NOEMBED>"+
            "</EMBED>"+
      "</OBJECT>";
    out.println(uhoh + "\n<p>");

    out.println("</body></html>");
  }
  /**Clean up resources*/
  public void destroy() {
  }

  /**
   * lookup the server repository
   */
  private void deployletRepositoryLookup(){
    //
    try {
      String serverName = "rmi://localhost/deployletRepository";
      server = (ServerRepository) Naming.lookup(serverName);
    } catch (Exception e) {
      System.out.println("LaunchServlet during ServerRepository lookup: "+e);
    }
  }
}