package examples.xml.biztalk.ejb.bizTradeJournal;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.*;
import javax.ejb.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import examples.xml.biztalk.IncomingMessage;
import examples.xml.biztalk.BizException;
import weblogic.common.T3ServicesDef;
import weblogic.common.T3Exception;
import java.io.PrintWriter;
import org.w3c.dom.Element;
import java.io.FileOutputStream;


/**
 * BizTradeJournal is a stateless SessionBean. This bean is used 
 * to illustrate mapping a second bean to process a BizTalk document.
 *
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class BizTradeJournalBean implements SessionBean {
  static  final     boolean        VERBOSE = true;

  // -----------------------------------------------------------------
  // private variables
  private SessionContext ctx;
  private Context        rootCtx;
  private T3ServicesDef     t3s;


  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbActivate() {
    if (VERBOSE)
      System.out.println("ejbActivate called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbRemove() {
    if (VERBOSE)
      System.out.println("ejbRemove called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbPassivate() {
    if (VERBOSE)
      System.out.println("ejbPassivate called");
  }

  /**
   * Sets the session context.
   *
   * @param ctx               SessionContext Context for session
   */
  public void setSessionContext(SessionContext ctx) {
    if (VERBOSE)
      System.out.println("setSessionContext called");
    this.ctx = ctx;
  }

  // Interface exposed to EJBObject (pretty much a clone of the 
  // Trader interface without the RemoteException stuff, and an ejbCreate
  // without any parameters

  /**
   * This method corresponds to the create method in the home interface
   * "BizBeanHome.java".
   * The parameter sets of the two methods are identical. When the client calls
   * <code>BizBeanHome.create()</code>, the container allocates an instance of 
   * the EJBean and calls <code>ejbCreate()</code>.
   *
   * @exception               javax.ejb.CreateException if there is
   *                          a communications or systems failure
   * @see                     examples.xml.biztalk.ejb.biztradejournal.BizTradeJournalBean
   */
  public void ejbCreate () throws CreateException {
    if (VERBOSE)
      System.out.println("ejbCreate called");
    try {
      Properties p = new Properties();
      p.put(Context.INITIAL_CONTEXT_FACTORY,
        "weblogic.jndi.WLInitialContextFactory");
      InitialContext ic = new InitialContext(p);
      rootCtx = (Context) ic.lookup("java:comp/env");
      t3s = (T3ServicesDef) ic.lookup(T3ServicesDef.NAME);
    } catch (NamingException ne) {
      throw new CreateException("Could not look up context");
    }
  }

  /**
   * Called by BizTalk Server when a message for this bean is received. 
   * This method processes the BizTalk message payload by logging  the trade 
   * into the customers log file located in the /weblogic/examples/xml/biztalk 
   * directory.
   *
   * @param message           BizTalk message payload.
   * @exception               RemoteException
   */
  public void service(IncomingMessage message) 
    throws RemoteException {
    Element element=null;
    try {
      element = (Element) message.getPayloadAsObject();
    } catch (BizException be) {
      System.out.println(be.getMessage());
      return;
    }
    String customer = element.getAttribute("customer");
    String symbol = element.getAttribute("symbol");
    String shares = element.getAttribute("shares");
    String action = element.getAttribute("action");
    System.out.println("\nOrder received by TradeLogBean:");

    //get log for customer
    PrintWriter log = null;
    String logname = null;
    try {
      String WLHome = t3s.config().getProperty("weblogic.system.home");
      String separator = System.getProperty("file.separator");
      logname = WLHome+separator+"examples"+separator+"xml"+separator+
                "biztalk"+separator+customer+".log";
      log = new PrintWriter( new FileOutputStream(logname, true), true);
      log.println("Trade request received: "+ new Date());
      log.println("Customer: "+customer);
      log.println("Action: "+action);
      log.println("Stock symbol: "+symbol);
      log.println("Number of shares: "+shares+"\n");
      log.flush();
      System.out.println(logname+" updated.");
    }
    catch (Exception e) {
      System.err.println("Unable to open log file, "+logname+". Using System.err");
      System.err.println("Customer: "+customer);
      System.err.println("Action: "+action);
      System.err.println("Stock symbol: "+symbol);
      System.err.println("Number of shares: "+shares+"\n");
      return;
    }
  }
}
