package examples.event.clientside;

import weblogic.event.actions.*;
import weblogic.event.evaluators.*;
import weblogic.event.common.*;
import weblogic.common.*;
import java.util.*;
import javax.naming.*;
import weblogic.jndi.*;

/**
 * This class demonstrates an action that notifies the client
 * that the evaluator for its registration returned true;
 * i.e., client-side notification of an event. The main() in this
 * class sends a series of stock events to WebLogic Server. The
 * evaluate() method for the registration is executed on WebLogic Server.
 * The Action object that is part of the registration calls back
 * to the client who made the registration.
 *
 * @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 client1 implements ActionDef {
  
  static T3ServicesDef t3s;
  static int       totalevents = 10;
  static Object    lock        = new Object();
  
  T3ServicesDef services = null;
  
  /**
   * Sets the services object. The services object
   * allows access to services within WebLogic Server,
   * like the WebLogic Event Services used in this example.
   */
  public void setServices(T3ServicesDef services) {
    this.services = services;
  }
  
  /**
   * Registers initialization parameters for the action.
   *
   * @param p                ParamSet for initialization
   */
  public void registerInit(ParamSet p) {
    System.out.println("Registered ParamSet:\n[" + p + "]");
  }
  
  /**
   * Action method. Called when an event of interest
   * delivered to the evaluate() method returns true.
   *
   * @param ev               EventMessage
   */
  public void action(EventMessageDef ev) {
    int count;
    
    try {
      count = ev.getParameters().getParam("COUNT").asInt();
    } 
    catch (ParamSetException pse) {
      count = totalevents + 1; // be done
    }
    
    System.out.println("In action methods count = " + count);
    
    if (count < totalevents)
      generateEvent(++count);
    else {
      synchronized(lock) {
	lock.notifyAll();
      }
    }
  }
  
  static ParamSet h = new ParamSet();
  
  /**
   * Generates a stock event for illustrating
   * client-side notification.
   *
   * @param count            Count for this event
   */
  public static void generateEvent(int count) {
    try {
      System.out.println("In generateEvent count = " + count);
      h.setParam("COUNT",    count);
      h.setParam("HIGH",     100);
      h.setParam("LO",       98);
      h.setParam("Close",    99);
      h.setParam("News",     "PPC Announced");
      h.setParam("Buy",      true);
      h.setParam("PERatio",  10.5f);
      EventMessageDef e = t3s.events().getEventMessage("STOCKS.COMPUTERS", h);
      e.submit();
    } 
    catch (Exception e) {
      e.printStackTrace();
      return;
    }
  }
  
  /**
   * Main allows this to be called from the command line.
   * String argv is the URL of the WebLogic Server.
   */
  public static void main(String argv[]) { 

    if (argv.length != 1) {
      System.out.println("Usage:   java example.event.clientside.client1 WebLogicURL");
      System.out.println("Example: java example.event.clientside.client1 t3://localhost:7001");
      return;
    } 

    Context ctx = null;
    try {
      String host = argv[0];
      Hashtable env = new Hashtable();
      env.put(Context.PROVIDER_URL, host);
      env.put(Context.INITIAL_CONTEXT_FACTORY, 
              weblogic.jndi.WLInitialContextFactory.class.getName());
      ctx = new InitialContext(env);
      t3s = (T3ServicesDef)ctx.lookup("weblogic.common.T3Services");
      
      // The Client1 class implements the ActionDef interface.
      // It's Action() method will be invoked 
      // each time the evaluate method returns true. 
      // The constructor for an Action can take an Object
      // as an argument.
      Action   act  = new Action(new client1());
      // The EvaluateTrue class implements EvaluateDef and always evaluates to true
      // It is distributed by default with the WebLogic Server
      Evaluate eval = new Evaluate("weblogic.event.evaluators.EvaluateTrue");
    
      // Register for events
      try {
	// Create an EventRegistration by requesting an object
	// from the event services factory. This takes the place
	// of a constructor.
        EventRegistrationDef er = 
             t3s.events().getEventRegistration("STOCKS",
                                               eval,
                                               act,
                                               true,  // sink
                                               true,  // phase
                                               EventRegistrationDef.UNCOUNTED);
      
        int localregID = er.register();
        
        System.out.println("Your Registration ID is " + localregID);
      } 
      catch (Exception e) {
	System.out.println("Registration Failed!"  + e);
	e.printStackTrace();
      }
      
      totalevents = 10;
    
      // Now generate an initial event
      generateEvent(0);
    
      synchronized(lock) {
	try {
	  // wait until all of the events have been delivered
	  lock.wait();
	} catch (InterruptedException ie) {
	  // catch the exception thrown when we are notified 
	}
      }
    

    } catch (NamingException ne) {
      System.err.println("Exception thrown creating JNDI initial context");
      ne.printStackTrace();
    } finally {
      try {
        if (ctx != null)
          ctx.close();
      } catch (Exception e) {}
    }
  }
}

