package examples.wlec.ejb.simpapp;

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

import org.omg.CORBA.*;
import com.beasys.Tobj.*;
import com.beasys.*;

/*These come from WebLogic Enterprise Simpapp sample */
import SimpleFactory;
import SimpleFactoryHelper;
import Simple;

/**
 * <font face="Courier New" size=-1>ConverterBean</font> is a stateless SessionBean.
 * This bean illustrates:
 * <ul>
 * <li> Accessing ISL/ISH process and then a WebLogic Enterprise server
 * <li> No persistence of state between calls to the SessionBean
 * <li> Application-defined exceptions
 * </ul>
 *
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class ConverterBean implements SessionBean {

  static SimpleFactory simple_factory_ref;

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

  // -----------------------------------------------------------------
  // SessionBean implementation

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbActivate()  {}

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbRemove() {}

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbPassivate() {}

  /**
   * Sets the session context.
   *
   * @param ctx               SessionContext Context for session
   */
  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;
  }

  // Interface exposed to EJBObject 

  /**
   * This method corresponds to the <font face="Courier New" size=-1>create</font> method
   * in the home interface <font face="Courier New" size=-1>ConverterHome.java</font>.
   * The parameter sets of these two methods are identical. When the client calls the
   * <font face="Courier New" size=-1>ConverterHome.create</font> method, the container
   * allocates an instance of the EJBean and calls the
   * <font face="Courier New" size=-1>ejbCreate</font> method.
   *
   * @exception               CreateException
   *                          if there is an error while initializing the IIOP pool 
   * @see                     examples.wlec.ejb.simpapp.Converter
   */
  public void ejbCreate () throws CreateException {
    try {
      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");
      }
      catch (NamingException ne) {
        throw new CreateException("Could not lookup context");
      }
		
      initIIOPpool();
    }
    catch (Exception e) {
      throw new CreateException("ejbCreate called: " + e);
    }
  }

  /**
   * Converts the string to uppercase
   *
   * @param mixed             String Input data
   * @return                  ConverterResult Conversion Result
   * @exception               examples.wlec.ejb.simpapp.ProcessingErrorException
   *                          if there is an error while converting the string
   */
  public ConverterResult toUpper(String mixed)
    throws ProcessingErrorException
  {
    return convert("UPPER", mixed);
  }

  /**
   * Converts the string to lowercase
   *
   * @param mixed             String Input data
   * @return                  ConverterResult Conversion Result
   * @exception               examples.wlec.ejb.simpapp.ProcessingErrorException
   *                          if there is an error while converting the string
   */
  public ConverterResult toLower(String mixed)
    throws ProcessingErrorException
  {
    return convert("LOWER", mixed);
  }

  protected ConverterResult convert (String changeCase, String mixed) 
    throws ProcessingErrorException
  {
    String result;
    try {
      // Find the simple object.
      Simple simple = simple_factory_ref.find_simple();

      if (changeCase.equals("UPPER")) {
        // Invoke the to_upper opeation on M3 Simple object
        org.omg.CORBA.StringHolder buf = new org.omg.CORBA.StringHolder(mixed);
        simple.to_upper(buf);
        result = buf.value;
      }
      else
      {
        result = simple.to_lower(mixed);
      }
    
    }
    catch (org.omg.CORBA.SystemException e) {
      throw new ProcessingErrorException("Converter error: Corba system exception: " + e);
    }
    catch (Exception e) {
      throw new ProcessingErrorException("Converter error: " + e);
    }
    return new ConverterResult(result);
  }

// Private methods

  /**
   * Returns the WebLogic Enterprise Connectivity pool name.
   *
   * @return                  String IIOP pool name
   */
  private String getIIOPPoolName() throws ProcessingErrorException {
    try {
      return (String) rootCtx.lookup("IIOPPoolName");
    }
    catch (NamingException ne) {
      throw new ProcessingErrorException ("IIOPPoolName not found in context");
    }	
  }

  /**
   * Initializes an IIOP connection pool.
  */

  private void initIIOPpool() throws Exception {
  try {
      // Create the bootstrap object,
      Tobj_Bootstrap bootstrap = BootstrapFactory.getClientContext(getIIOPPoolName());

      // Use the bootstrap object to find the factory finder.
      org.omg.CORBA.Object fact_finder_oref =
        bootstrap.resolve_initial_references("FactoryFinder") ;

      // Narrow the factory finder.
      FactoryFinder fact_finder_ref =
        FactoryFinderHelper.narrow(fact_finder_oref);

      // Use the factory finder to find the simple factory.
      org.omg.CORBA.Object simple_fact_oref =
        fact_finder_ref.find_one_factory_by_id(SimpleFactoryHelper.id());

      // Narrow the simple factory.
      simple_factory_ref =
        SimpleFactoryHelper.narrow(simple_fact_oref);

    }
    catch (org.omg.CosLifeCycle.NoFactory e) {
      throw new Exception("Can't find the simple factory: " +e);
    }
    catch (CannotProceed e) {
      throw new Exception("FactoryFinder internal error: " +e);
    }
    catch (RegistrarNotAvailable e) {
      throw new Exception("FactoryFinder Registrar not available: " +e);
    }
    catch (InvalidName e) {
      throw new Exception("Invalid name from resolve_initial_reference(): " +e);
    }
    catch (org.omg.CORBA.BAD_PARAM e) {
      throw new Exception("Invalid TOBJADDR=//host:port property specified: " +e);
    }
    catch (org.omg.CORBA.UserException e) {
      throw new Exception("Unexpected CORBA user exception: " +e);
    }
    catch (org.omg.CORBA.SystemException e) {
      throw new Exception("CORBA system exception: " +e);
    }
  }
}
