package examples.intro;

import java.io.*;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.jms.*;
import javax.jts.*;
import javax.naming.*;


/**
 * This example shows how to establish a connection to a JMS
 * queue and receive messages from a queue. Messages are placed 
 * in the queue using the EmpTrans servlet. 
 *
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class EmpQueueReader
{
  public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
  public final static String JMS_FACTORY="javax.jms.QueueConnectionFactory";
  public final static String QUEUE="jms.queue.EmpXactQueue";

  static QueueConnectionFactory factory;
  static QueueConnection qconnection;
  static QueueSession qsession;
  static QueueReceiver qreceiver;
  static Queue queue;
  static Context ctx;
  private boolean quit = false;

  /**
   * Create all the necessary objects for receiving
   * messages from a JMS queue.
   */
  public static void main(String[] args)
    throws NamingException, JMSException, RemoteException
  {

    Message message;

    Hashtable ht = new Hashtable();
    ht.put(Context.SECURITY_PRINCIPAL, "guest");
    ht.put(Context.SECURITY_CREDENTIALS, "guest");
    ht.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    ht.put(Context.PROVIDER_URL, "t3://localhost:7001");

    ctx = new InitialContext(ht);
    factory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
    qconnection = factory.createQueueConnection();
    qsession = qconnection.createQueueSession(false, 
                                              Session.AUTO_ACKNOWLEDGE);
    queue = (Queue) ctx.lookup(QUEUE);
    qreceiver = qsession.createReceiver(queue);
    qconnection.start();
    while (true) { // get messages until the queue is empty
      message = qreceiver.receiveNoWait();
      if (message == null) 
        break;
      if (message instanceof MapMessage) {
        switch (((MapMessage) message).getInt("xactType")) {
        case 1:  // hire
          doHire((MapMessage) message);
          break;
        case 2: // termination
          doTerm((MapMessage) message);
          break;
        case 3: // salary adjustment
          doSal((MapMessage) message);
          break;
        }
      }
    }
    qsession.close();
    qconnection.close();
  }

  static void doHire(MapMessage message) 
    throws JMSException, NamingException, RemoteException
  {
    boolean response;
    Emp e;

    System.out.println("\n\n\n=== Hire request ===");
    System.out.println("Employee name ...... : " + 
                       message.getString("ename"));
    System.out.println("Job title .......... : " + 
                       message.getString("job"));
    System.out.println("Manager ............ : " +
                       message.getInt("mgr"));
    System.out.println("Hire date .......... : " + 
                       message.getString("hiredate"));
    System.out.println("Salary ............. : " +
                       message.getFloat("sal"));
    System.out.println("Commission ......... : " +
                       message.getFloat("comm"));
    System.out.println("Department no ...... : " +
                       message.getInt("deptno"));
    System.out.println("===========================");
    response = Confirm("Approve this request?");
    if (response) {
      try {
        EmpBeanHome home = (EmpBeanHome) ctx.lookup("EmpBeanHome");
        e = home.create(NextEmpno(),
                        message.getString("ename"),
                        message.getString("job"),
                        message.getInt("mgr"),
                        java.sql.Date.valueOf(message.getString("hiredate")),
                        message.getFloat("sal"),
                        message.getFloat("comm"),
                        message.getInt("deptno"));
        System.out.println("Created new employee.");
      }
      catch (CreateException ce) {
        System.out.println("EJB CreateException: " + ce.getMessage());
      }
    }
    else
      System.out.println("Ignoring request.");
  }

  static void doTerm(MapMessage message) 
    throws JMSException, RemoteException, NamingException
  {
    boolean response;
    
    try {
      EmpBeanHome home = (EmpBeanHome) ctx.lookup("EmpBeanHome");
      Emp e = home.findByEmpno(message.getInt("empno"));
      System.out.println("\n\n\n=== Termination request ===");
      System.out.println("Employee number ..... : " + 
                         e.getEmpno());
      System.out.println("Employee name ....... : " +
                         e.getEname());
      System.out.println("===========================");
      response = Confirm("Approve this request?");
      if (response) {
        e.remove();
        System.out.println("Deleted employee.");
      }
      else
        System.out.println("Ignoring request.");
    }
    catch (FinderException fe) {
      System.out.println("EJB FinderException: " + fe.getMessage());
    }
    catch (RemoveException re) {
      System.out.println("Failed to delete employee: " + re.getMessage());
    }
  }
  


  static void doSal(MapMessage message) 
    throws JMSException, RemoteException, NamingException
  {
    boolean response;

      try {
        EmpBeanHome home = (EmpBeanHome) ctx.lookup("EmpBeanHome");
        Emp e = home.findByEmpno(message.getInt("empno"));
        System.out.println("\n\n\n=== Salary adjustment request ===");
        System.out.println("Employee number ..... : " +
                           message.getInt("empno"));
        System.out.println("Employee name ....... : " +
                           e.getEname());
        System.out.println("Current salary ...... : " +
                           e.getSal());
        System.out.println("New salary .......... : " +
                           message.getFloat("sal"));
        System.out.println("===========================");
        response = Confirm("Approve this request?");
        if (response) {
          e.setSal(message.getFloat("sal"));
          System.out.println("Salary adjusted.");
        }
        else
          System.out.println("Ignoring request.");        
      }
      catch (FinderException fe) {
        System.out.println("EJB FinderException: " + fe.getMessage());
      }
  }
  
  
  static boolean Confirm(String question)
  {
    String response = null;
    BufferedReader keys = new BufferedReader( new InputStreamReader(System.in));
    try {
      while (true) {
        System.out.print(question + " (yes/no) " );
        response = keys.readLine();
        if (response.equalsIgnoreCase("yes") ||
            response.equalsIgnoreCase("no")) 
          break;
      }
    }
    catch (IOException io) {
      io.printStackTrace();
    }
    return response.equalsIgnoreCase("yes") ? true : false;
  }

  /**
   * Find the next employee number in the database
   */
  static int NextEmpno()
  {
    java.sql.Connection conn = null;
    Statement s = null;
    ResultSet rs = null;
    int nextEmpno=0;
    Properties t3props = new Properties();
    t3props.put("weblogic.t3.connectionPoolID", "demoPool");
    t3props.put("weblogic.t3.serverURL", "t3://localhost:7001");
    try {
      Class.forName("weblogic.jdbc.t3.Driver").newInstance();
      conn = DriverManager.getConnection("jdbc:weblogic:t3", t3props);
      s = conn.createStatement();
      s.execute("select max(empno) from emp");
      rs = s.getResultSet();
      while (rs.next()) {
        nextEmpno = rs.getInt(1);
      }
      rs.close();
      s.close();
      conn.close();
    }
    catch (Exception e) {
      System.out.println("JDBC error: " + e.getMessage());
    }
    return nextEmpno+1;
  }


}




