package examples.wlec.servlets.simpapp;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Properties;

import weblogic.html.*;

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

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

/**
 * This example demonstrates how a WebLogic Servlet can connect to WebLogic Enterprise
 * and invoke an operation on a CORBA object. It should be invoked from the
 * <font face="Courier New" size=-1>Simpapp.html</font> file.
 * <UL>
 * <LI>When the Weblogic Application Server comes up,
 * it opens multiple connections to the WebLogic Enterprise IIOP listener.
 * <li>At the  initialization phase of the servlet, it picks up a connection from the
 * the connection pool; that is, it acts as a WebLogic Enterprise client and gets a client context 
 * from the bootstrap factory.
 * <LI>The servlet then finds the factory finder and gets the 
 * Simple factory.
 * <LI>When the user submits the form, the IOR for the 
 * Simple object is obtained from the Simple factory and the toupper/tolower 
 * operation is invoked. (The user specifies "TO UPPER" or
 * "TO LOWER" in <font face="Courier New" size=-1>Simpapp.html</font>.)
 * This request goes through the ISL/ISH to the appropriate server in the WebLogic Enterprise domain.
 * <LI>The server converts the string and sends it back to the servlet.
 * <LI>The servlet returns the converted string to the client
 * browser within some generated HTML.
 * </UL>
 *
 * @author Copyright (c) 1999-2000 BEA Systems, Inc.  All rights reserved.
 */


public class SimpappServlet extends HttpServlet {


  // The SimpleFactory will be used to get the Simple Object

  static SimpleFactory simple_factory_ref;
  final String defaultCase = "UPPER";
  final String defaultString = "It Works";

  /**
  * Initializes the servlet.  Here, we get the Bootstrap
  * object, the Factory Finder and the Simple factory
  * during the startup.
  * 
  * @param config            Servlet configuration
  * @exception               ServletException if the servlet fails
  */

  public void init(ServletConfig config) throws ServletException
  {

    try {

      super.init(config);

      // Create the bootstrap object,
      Tobj_Bootstrap bootstrap = 
        BootstrapFactory.getClientContext("simplepool");

      // 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) {
      System.err.println("Can't find the simple factory: " +e);
      throw new ServletException(e.toString());
    }
    catch (CannotProceed e) {
      System.err.println("FactoryFinder internal error: " +e);
      throw new ServletException(e.toString());
    }
    catch (RegistrarNotAvailable e) {
      System.err.println("FactoryFinder Registrar not available: " +e);
      throw new ServletException(e.toString());
    }
    catch (InvalidName e) {
      System.err.println("Invalid name from resolve_initial_reference(): " +e);
      throw new ServletException(e.toString());
    }
    catch (org.omg.CORBA.BAD_PARAM e) {
      System.err.println("Invalid TOBJADDR=//host:port property specified: " +e);
      throw new ServletException(e.toString());
    }
    catch (org.omg.CORBA.UserException e) {
      System.err.println("Unexpected CORBA user exception: " +e);
      throw new ServletException(e.toString());
    }
    catch (org.omg.CORBA.SystemException e) {
      System.err.println("CORBA system exception: " +e);
      throw new ServletException(e.toString());
    }
  }

  /**
  * A simple implementation of the service method, in
  * which we get the IOR for Simple object, invoke the <font face="Courier New" size=-1>tolower</font>
  * or <font face="Courier New" size=-1>toupper</font> method (as requested by the user), construct a
  * servlet page, and print the user string in uppercase or lowercase.
  * See the provided <font face="Courier New" size=-1>Simpapp.html</font>
  * for the HTML form used to submit the data.
  */

  public void service(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
  {

    // Create a HTML page
    res.setContentType("text/html");
    ServletPage page = new ServletPage("WebLogic Enterprise Connectivity - Simpapp Servlet Sample");
    
    // Set the color of the page
    page.getBodyElement()
      .setAttribute(BodyElement.bgColor, HtmlColor.purple);
    page.getBodyElement()
      .setAttribute(BodyElement.textColor, HtmlColor.white);

    // Read the input data
    String mixed = (String) req.getParameter("InData");
    String changeCase = (String) req.getParameter("ChangeCase");

    // If no string is passed, use the default string
    if ((mixed == null) || (mixed.length() <= 0)) {
      mixed = defaultString;
      page.getBody().addElement("Note: Using the default data: " + mixed);
    }

    // If no case is passed, use the default case, UPPERCASE
    if ((changeCase == null) || (changeCase.length() <= 0)) {
      changeCase = defaultCase;
      page.getBody()
        .addElement(MarkupElement.Break) 
        .addElement("Note: Using the default action:" + defaultCase);
    }

    try {
      String result;

      // Find the simple object.
      Simple simple = simple_factory_ref.find_simple();

      if (changeCase.equals(defaultCase)) {
        // Invoke the to_upper opeation on WebLogic Enterprise Simple object
        org.omg.CORBA.StringHolder buf = 
        new org.omg.CORBA.StringHolder(mixed);
        simple.to_upper(buf);
        result = buf.value;
      }
      else
      {
        // Invoke the to_lower opeation on WebLogic Enterprise Simple object
        result = simple.to_lower(mixed);
      }
      page.getBody()
        .addElement(new HeadingElement("Output String: " + result, 4));
        
      // Return the html to the client browser
      page.output(res.getOutputStream());

    }
    catch (org.omg.CORBA.SystemException e) {
      log("CORBA system exception: " +e);
    }
  }

  /**
  * Basic servlet info.
  */

  public String getServletInfo() {
    return "A simple servlet which acts a client for WebLogic Enterprise";
  }

}
