package examples.intro;


import java.io.*;
import java.lang.Integer;
import java.sql.*;
import java.util.*;
import javax.jms.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpUtils;
import weblogic.common.*;


/**
 * This servlet shows how to establish a connection to a JMS
 * queue and sumbit messages. Messages are read from the queue
 * with the EmpQueueReader Java client. 
 *
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class EmpTrans extends HttpServlet
{

  private String resultMessage = null;
  java.sql.Date today = new java.sql.Date(new java.util.Date().getTime());

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

    response.setContentType("text/html");

    PrintWriter pw = response.getWriter();

    // print the header information
    pw.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" +
               "<html><head><title>" + 
               "Employee Transaction Request" + 
               "</title><body><font face=\"Helvetica\">" + 
               "<h1><font color=\"#FF0000\">" + 
               "Employee Transaction Request" + 
               "</font></h1><hr>" );

    // print the input form
    pw.println("<form action=\"" + request.getRequestURI() + "\" method=\"post\">");
    pw.println("<table border=1 cellpadding=10 align=center bgcolor=#EEEEEE>");
    pw.println("<tr><td>Transaction type</td><td>" + 
               "<table bgcolor=#CCCCCC border=0 width=100%>");
    pw.println("<tr><td><input type=\"radio\" name=xactType value=\"1\">Hire</td>");
    pw.println("<td>(Complete the <i>Hire data</i> section)</td></tr>");
    pw.println("<tr><td><input type=\"radio\" name=xactType value=\"2\">Terminate</td>");
    pw.println("<td>(Complete the <i>Termination data</i> section)</td>");
    pw.println("</tr><tr><td><input type=\"radio\" name=xactType value=\"3\">" +
               "Adjust salary</td>");
    pw.println("<td>(Complete the <i>Salary data</i> section)</td></tr>");
    pw.println("</table></td><tr><td>Hire data</td><td>");
    pw.println("<table bgcolor=#CCCCCC border=0 width=100%>");
    pw.println("<tr><td>Employee name</td><td><input type=text width=10 " + 
               "maxlength=10 name=hename></td></tr>");
    pw.println("<tr><td>Job title</td><td><input type=text width=9 maxlength=9 " +
               "name=job></td></tr>");
    pw.println("<tr><td>Manager</td><td>" + EmpSelector("mgr") + "</td></tr>");
    pw.println("<tr><td>Hire date</td><td><input type=text width=10 "+
               "maxlength=10 name=hiredate value=\"" + today.toString() + 
               "\"></td></tr>");
    pw.println("<tr><td>Salary</td><td><input type=text width=10 " + 
               "maxlength=10 name=salary></td></tr>");
    pw.println("<tr><td>Commission</td><td><input type=text width=10 " + 
               "maxlength=10 name=comm></td></tr>");
    pw.println("<td>Department</td><td><select size=1 name=deptno><option>10"+
               "<option>20<option>30</select></td></tr></table></td></tr>");
    pw.println("<tr><td>Termination data</td><td><table bgcolor=#CCCCCC " + 
               "border=0 width=100%>");
    pw.println("<tr><td>Employee</td><td>" + EmpSelector("tempno") + 
               "</td></tr></table></td></tr>");
    pw.println("<tr><td>Salary data</td><td>");
    pw.println("<table bgcolor=#CCCCCC border=0 width=100%>");
    pw.println("<tr><td>Employee</td><td>" + EmpSelector("sempno") + 
               "</td></tr>");
    pw.println("<tr><td>New salary</td><td><input type=text width=10 " + 
               "maxlength=10 name=newsal></td></tr></table></td></tr>");
    pw.println("<tr><td colspan=2 align=center>" +
               "<input type=submit value=\"Go\" action=" + 
               request.getRequestURI() + "</td></tr></table></form><p>");
    pw.println("<hr></font></body></html>");
  }


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

    boolean dataOK = true;
    int transtype = 0;
    int empno = 0;
    String ename = null;
    String job = null;
    int mgr = 0;
    java.sql.Date hiredate = null;
    float sal = 0.0f;
    float comm = 0.0f;
    int deptno = 0;
      
    PrintWriter pw = response.getWriter();
    pw.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" +
               "<html><head><title>" + 
               "Employee Transaction Request" + 
               "</title><body><font face=\"Helvetica\">" + 
               "<h1><font color=\"#FF0000\">" + 
               "Employee Transaction Request" + 
               "</font></h1><hr>");

    transtype = getAsInt(request, "xactType");
    if (transtype == 0) {
      pw.println("No transaction type selected.");
      dataOK = false;
    }

    switch (transtype) {
    case 1: // hire
      ename = getAsString(request, "hename");
      if (ename == null) {
        pw.println("<p>Error: no employee name in hire data.");
        dataOK = false;
      }
      job = getAsString(request, "job");
      if (job == null) {
        pw.println("<p>Error: no job title in hire data.");
        dataOK=false;
      }
      mgr = getAsInt(request, "mgr"); // can't fail
      hiredate = getAsDate(request, "hiredate");
      if (hiredate == null) {
        pw.println("<p>Error: invalid hire date in hire data.");
        dataOK=false;
      }
      sal = getAsFloat(request, "salary");
      if (sal == 0f) {
        pw.println("<p>Error: no salary in hire data.");
        dataOK=false;
      }
      comm = getAsFloat(request, "comm");  // ok to be null
      deptno = getAsInt(request, "deptno"); // can't fail
      break;
    case 2:  // terminate
      empno = getAsInt(request, "tempno"); // can't fail
      break;
    case 3: // salary adjustment
      empno = getAsInt(request, "sempno"); // can't fail
      sal = getAsFloat(request, "newsal");
      if (sal == 0) {
        pw.println("Error: no salary in salary data.");
        dataOK = false;
      }
      break;
    }
    if (! dataOK) {
      pw.println("<p>" +
                 "<p>There were errors in the data you entered. " + 
                 "Please back up to the form and fix them.");
    }
    else {
      if (! sendRequest(transtype, empno, ename, job, mgr, hiredate, sal, comm, deptno) ) {
	pw.println("Failed to send request.<p>" + resultMessage);
      }
      else {
	pw.println("Request sent.");
      }
    }
    pw.println("<hr></font></body></html>");
  }



  /**
   * Gets a <select> list of all employees and assigns the selection
   * to the name parameter. To be inserted into an HTML form.  
   */
  public String EmpSelector (String name)
  {
    String selector = null;
    java.sql.Connection conn = null;
    Statement s = null;
    ResultSet rs = null;

    try {
      Class.forName("weblogic.jdbc.pool.Driver").newInstance();
      conn = DriverManager.getConnection("jdbc:weblogic:pool:demoPool");
      s = conn.createStatement();
      
      s.execute("Select empno, ename from emp order by ename");
      rs = s.getResultSet();
      selector = "<select size=1 name=" + name + ">";
      while(rs.next()) {
        selector += ("<option value=" + 
                     rs.getString(1) + ">" +
                     rs.getString(2) + " (" +
                     rs.getString(1) + ")");
      }
      selector += "</select>";
    }
    catch (Exception se) {};
    try {
      rs.close();
      s.close();
      conn.close();
    }

    catch (Exception e) {};
    return selector;
  }


  // return a form field as an int, or null if it's bad
  // or missing. 
  private int getAsInt(HttpServletRequest request, String field)
  {
    int i = 0;
    if (request.getParameterValues(field) != null) {
      try {
        i = Integer.parseInt(((String[]) request.getParameterValues(field))[0]);
      }
      catch (NumberFormatException ne) {
        i = 0;
      }
    }
    return i;
  }

  private String getAsString(HttpServletRequest request, String field)
  {
    String s = null;
    if (request.getParameterValues(field) != null)
      s = ((String[]) request.getParameterValues(field))[0];
    if (s.length() == 0)
      s = null;
    else
      s = s.toUpperCase();
    return s;
  }

  private java.sql.Date getAsDate(HttpServletRequest request, String field)
  {
    java.sql.Date d = null;
    if (request.getParameterValues(field) != null) 
      try {
        d = java.sql.Date.valueOf(((String[]) request.getParameterValues(field))[0]);
      }
      catch (IllegalArgumentException ie) { 
        d = null;
      }
    return d;
  }
    

  private float getAsFloat(HttpServletRequest request, String field)
  {
    float f = 0f;
    if (request.getParameterValues(field) != null) 
      try {
        f = Float.valueOf(((String[]) request.getParameterValues(field))[0]).floatValue();
      }
      catch (NumberFormatException ne) {
        f = 0f;
      }
    return f;
  }

  private boolean sendRequest(int xactType, int empno, String ename, String job, 
                           int mgr, java.sql.Date hiredate, float sal, 
                           float comm, int deptno)
  {
    
    boolean result = true;

    Context ctx = null;
    QueueConnectionFactory factory;
    QueueConnection qconnection = null;
    QueueSession qsession = null;
    QueueSender qsender = null;
    Queue queue;
    MapMessage message;
    Hashtable ht = new Hashtable();

    ht.put(Context.SECURITY_PRINCIPAL, "guest");
    ht.put(Context.SECURITY_CREDENTIALS, "guest");
    try {
      ctx = new InitialContext(ht);
      factory = (QueueConnectionFactory)
        ctx.lookup("javax.jms.QueueConnectionFactory");
      qconnection = factory.createQueueConnection();
      qsession = qconnection.createQueueSession(false, 
                        Session.AUTO_ACKNOWLEDGE);
      
      queue = (Queue) ctx.lookup("jms.queue.EmpXactQueue");
      qsender = qsession.createSender(queue);
      message = qsession.createMapMessage();
      qconnection.start();

      message.setInt("xactType", xactType);
      switch (xactType) {
      case 1: // hire
        message.setString("ename", ename);
        message.setString("job", job);
        message.setInt("mgr", mgr);
        message.setString("hiredate", hiredate.toString());
        message.setFloat("sal", sal);
        message.setFloat("comm", comm);
        message.setInt("deptno", deptno);
        break;
      case 2: // termination
        message.setInt("empno", empno);
        break;
      case 3: // salary adjustment
        message.setInt("empno", empno);
        message.setFloat("sal", sal);
        break;
      }
      qsender.send(message, DeliveryMode.PERSISTENT,
		   0, 0);
    }
    catch (NamingException e) {
      result = false;
      resultMessage = "JNDI error on " + e.getMessage();
    }
    catch (JMSException je) {
      result = false;
      resultMessage = "JMS Error: " + je.getMessage();
    }
    try { qsender.close();     } catch (Exception e) {};
    try { qsession.close();    } catch (Exception e) {};
    try { qconnection.close(); } catch (Exception e) {};
    try { ctx.close();         } catch (Exception e) {};

    return result;
  }


}
