package examples.htmlkona;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import weblogic.html.*;
import weblogic.db.jdbc.*;

/**
 * This servlet illustrates a simple database login through an
 * HTML interface.
 * 
 * @author Copyright (c) 1996-98 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class SimpleDBLogin extends HttpServlet {

  public synchronized void service(HttpServletRequest req, HttpServletResponse res) 
    throws IOException
  {
    try {
      res.setStatus(HttpServletResponse.SC_OK);
      res.setContentType("text/html");

      ServletPage hp = new ServletPage("Simple Database Login");

      Properties props = new Properties();
      props.put("user",     "scott");
      props.put("server",   defaults.server());

      // Use a bad password
      props.put("password",  "badpassword");
      login(props, hp);

      // Use a good password
      props.put("password",  "tiger");
      login(props, hp);

      hp.output(res.getOutputStream());
    }
    catch (Exception e) {
      defaults.showException(e, res.getOutputStream());
    }
  }

  public static void login(Properties props, ServletPage hp)
  {
    Connection conn = null;
    try {
      Class.forName("weblogic.jdbc.oci.Driver").newInstance();
      conn = DriverManager.getConnection("jdbc:weblogic:oracle", props);
    }
    catch (Exception e) {
      hp.getBodyElement()
	.setAttribute(BodyElement.bgColor, HtmlColor.white);
      hp.getBody()
        .addElement(MarkupElement.HorizontalLine)
        .addElement(new HeadingElement("Login attempt failed", 2))
        .addElement(new LiteralElement(e.getMessage()))
        .addElement(MarkupElement.HorizontalLine);
      return;
    }
    finally {
      try {conn.close();} catch (Exception e) {;}
    }

    hp.getBody()
      .addElement(new HeadingElement("Login attempt succeeded", 2))
      .addElement(MarkupElement.HorizontalLine)
      .addElement("Copyright 1996-2000 by BEA Systems, Inc. All Rights Reserved.");
  }
}
