package examples.event.clockquery;

import weblogic.common.*;
import weblogic.event.actions.*;
import weblogic.event.common.*;
import weblogic.event.evaluators.*;
import weblogic.workspace.common.*;

import weblogic.jndi.*;
import javax.naming.*;
import java.util.*;

import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;
import weblogic.db.jdbc.*;

/**
 * This class is used to register interest in a regularly
 * updated table on a DBMS. It uses the class QueryOnTime,
 * also in this directory.
 *
 * @author Copyright (c) 1997-1998 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class Register {
  
  static void nap(int secs)  {
    try {
      Thread.currentThread().sleep(1000 * secs);
    }
    catch (InterruptedException ie) {
    }
  }
  
  /**
   * In the main of this class, we initialize the arguments 
   * needed to set up the registration, then use the command line
   * information supplied by the user to connect to the DBMS
   * and retrieve the contents of a table on a regular basis.
   * The result is stored in the server workspace so that it
   * is accessible to Clients.
   */
  public static void main(String argv[]) {
    
    int interval    = 5;
    String units    = "SEC";
    String t3Url    = "";
    String user     = "";
    String passwd   = "";
    String dbserver = "";

    EventRegistrationDef er = null;    // Declare here so we can unregister later

    boolean goodArgs = false;
    
    

    if (argv.length < 1) {
      System.out.println("Usage: java examples.event.clockqueray.Register " +
			 "WebLogicURL [user [password [dbserver]]]");
      System.out.println("Examples: java examples.event.clockquery.Register " +
                     "t3://localhost:7001 scott tiger DEMO (Oracle)");
      System.out.println("          java examples.event.clockquery.Register t3://localhost:7001 Cloudscape)");
      return;
    }


    t3Url    = argv[0];
    if (argv.length > 1) {
      user     = argv[1];
    }
    if (argv.length > 2) {
      passwd   = argv[2];
    }
    if (argv.length > 3) {
      dbserver = argv[3];
    }
    
    // Connect to the WebLogic Server using the URL supplied as the first
    // command-line argument
    
    java.sql.Connection conn  = null;
    
    
    try {
      T3ServicesDef t3s = getT3Services(t3Url);
      
      // Connect to the database
      java.util.Properties dbprops = new Properties();
      
      dbprops.put("user",     user     );
      dbprops.put("password", passwd   );
      dbprops.put("server",   dbserver );
      
      java.util.Properties t3props = new Properties();
      t3props.put("weblogic.t3.serverURL", t3Url);
      t3props.put("weblogic.t3.dbprops",  dbprops);
      t3props.put("weblogic.t3.driver",   "COM.cloudscape.core.JDBCDriver");
      t3props.put("weblogic.t3.url",      "jdbc:cloudscape:demo;create=true");

      try {
	Class.forName("weblogic.jdbc.t3.Driver").newInstance();
      } catch (ClassNotFoundException cnfe) {
	System.err.println("Couldn't find driver class");
	cnfe.printStackTrace();
	return;
      } catch (IllegalAccessException iae) {
	System.err.println("Couldn't instantiate driver");
	iae.printStackTrace();
	return;
      } catch (InstantiationException iae) {
	System.err.println("Couldn't instantiate driver");
	iae.printStackTrace();
	return;
      }
      
      conn = DriverManager.getConnection("jdbc:weblogic:t3", t3props);
      
      System.out.println("Connected to the database.");
      System.out.println("");
      
      // Create a table in tempdb for example use.
      Statement stmt = conn.createStatement();
      
      try {
        stmt.execute("drop table webEventTest");
      }
      catch (SQLWarning e) {
       
      }
      
      stmt.execute("create table webEventTest (Line char(17), Now timestamp)");

      
      System.out.println("Table created in tempdb with a string and a " +
			 "date-of-insertion.\n");

      ParamSet evRegParams = null;
      ParamSet acRegParams = null;

      try {
	// Create a ParamSet to be used by the Evaluate method as each
	// Event is received to decide whether the Action method should
	// be called. We take the second and third command-line
	// arguments as values.
	evRegParams = new ParamSet();
	evRegParams.setParam("INTERVAL", interval);
	evRegParams.setParam("UNITS", units);

	// Create another ParamSet to be used by the Action method
	// to connect to the database.
	acRegParams = new ParamSet();
	acRegParams.setParam("user", user);
	acRegParams.setParam("passwd", passwd);
	acRegParams.setParam("dbserver", dbserver);
      } catch (ParamSetException pse) {
	System.err.println("Trouble using paramset");
	pse.printStackTrace();
	return;
      }

      // Create an EventRegistration for the topic "WEBLOGIC.TIME", with the
      // EvaluateTime evaluate class, and the QueryOnTime action
      // class.
      try {
	er = t3s.events().getEventRegistration(
            "WEBLOGIC.TIME", // topic
	    new Evaluate("weblogic.event.evaluators.EvaluateTime", evRegParams),
	    new Action("examples.event.clockquery.QueryOnTime", acRegParams)
	    );
        int regid = er.register();
	System.out.println("We've registered interest in a by-the-second timer event.");
	System.out.println("We want action every 5 seconds. The action will insert");
	System.out.println("a new dated row in the table, and then fetch all the rows");
	System.out.println("into a dataset which it stores in a workspace. The RegID");
	System.out.println("is: " + regid );
	System.out.println("");
	System.out.println("Sleep 10 seconds to ensure the action has " +
			   "been triggered at least once.");
	System.out.println("");
      } catch (EventRegistrationException ere) {
	System.err.println("Trouble with event registration");
	ere.printStackTrace();
	return;
      }

      // Wait long enough to ensure that the action method has been
      // called.
      nap(10);
      
      // Get result set created by the action method, store in the
      // default workspace, and display data.
      ParamSet wsps = 
	(ParamSet) t3s.workspace().fetch("myworkspace",
						 WorkspaceDef.SCOPE_SERVER);
      try {
	QueryDataSet qds =
	  (weblogic.db.jdbc.QueryDataSet)wsps.getParam("dataset").asObject();
	System.out.println("ResultSet retrieved from the workspace: ");
      
	for (int i = 0; i < qds.size(); i++) {
	  weblogic.db.jdbc.Record rec = qds.getRecord(i);
	  System.out.println(rec.getValue("Line").asString() + " - " + 
			     rec.getValue("Now").asString());
	}
      
	System.out.println("Sleep another 5 seconds for another " +
			   "insert to have been triggered.");
	System.out.println("");
      
	// Sleep another 5 seconds to allow the action to run again,
	// changing the data.
	nap(5);
      
	System.out.println("Latest result set from the workspace:");
	System.out.println("");
      
	// Get the new dataset and display new data.
	wsps = (ParamSet)t3s.workspace().
	  fetch("myworkspace", WorkspaceDef.SCOPE_SERVER);
	qds =
	  (weblogic.db.jdbc.QueryDataSet)wsps.getParam("dataset").asObject();
      
	for (int i = 0; i < qds.size(); i++) {
	  weblogic.db.jdbc.Record rec = qds.getRecord(i);
	  System.out.println(rec.getValue("Line").asString() + " - " + 
			     rec.getValue("Now").asString());
	}

      } catch (DataSetException dse) {
	System.err.println("Trouble using dataset");
	dse.printStackTrace();
	return;
      } catch (ParamSetException pse) {
	System.err.println("Trouble using paramset");
	pse.printStackTrace();
	return;
      }

      // unregister the event
      try {
        er.unregister();
      }
      catch (EventRegistrationException ere) {
        System.err.println("Trouble unregistering event");
        ere.printStackTrace();
        return;
      }

      // then drop the table
      stmt.execute("drop table webEventTest");
      System.out.println("");
      System.out.println("We're done. Removing the temp table.");

    } catch (NamingException ne) {
      System.err.println("Failed to lookup T3Services in JNDI tree");
      ne.printStackTrace();
    } catch (SQLException sqle) {
      System.err.println("Trouble interacting with database");
      sqle.printStackTrace();
      return;
    } catch (java.io.IOException ioe) {
      System.err.println("Trouble communicating with the requested server");
      ioe.printStackTrace();
      return;
    } finally {
      try {
        conn.close();
      } catch (Exception e) {}
    }
  }
  
  private static T3ServicesDef getT3Services(String wlUrl) 
       throws javax.naming.NamingException
  {
    T3ServicesDef t3s;
    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, wlUrl);
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            weblogic.jndi.WLInitialContextFactory.class.getName());
    Context ctx = new InitialContext(env);
    t3s = (T3ServicesDef) ctx.lookup("weblogic.common.T3Services");
    ctx.close();
    return(t3s);
  }
}

