package examples.xml.http;

import com.sun.java.util.collections.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.xml.sax.*;
import javax.ejb.*;
import javax.naming.*;
import examples.ejb.basic.statefulSession.*;

/**
 * This example shows how to pass XML data between a Java client 
 * and a servlet over HTTP. This class receives stock trade instructions 
 * from <tt>StockClient</tt> in the form of XML data. This class 
 * obtains an instance of <tt>TraderBean</tt> and perfoms the stock trades. 
 * The results of the trade are then pass back to <tt>StockClient</tt> in 
 * the form of XML data. 
 *
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.  
 */
public class StockServlet extends HttpServlet {


  /** parser */
  private String parserClass;

  /** Default parser name. */
  private static final String 
      DEFAULT_PARSER_NAME = "com.sun.xml.parser.ValidatingParser";


    /**
     * Initializes servlet.
     *
     * @param config          ServletConfig
     * @exception             javax.servlet.ServletException if there is a servlet problem
     */
  public synchronized void init(ServletConfig config)
    throws ServletException {
    super.init(config);
    parserClass = getInitParameter("parser");
    if(parserClass == null) parserClass = DEFAULT_PARSER_NAME;
  }


    /**
     * Handles HTTP POST requests
     *
     * @param request         HttpServletRequest
     * @param response        HttpServletResponse
     * @exception             javax.servlet.ServletException if there is a servlet problem
     * @exception             java.io.IOException if there is a I/O problem
     */
  public final void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException  {

    String serverURL = new HttpUtils().getRequestURL(request).toString();

    // remove the servlet name from this String. This will be used to locate the dtd
    serverURL = serverURL.substring(0, serverURL.indexOf("StockServlet"));

    RequestHandler rh = new RequestHandler();

    try {
      rh.parseXML(request.getReader(), parserClass);
    } catch(FileNotFoundException fnfe) {
      System.out.println("[DTD not found] Please place the appropriate dtd "+
                         "file into WebLogic Server's document root.");
      fnfe.printStackTrace();
      return;
    } catch(IOException ioe) {
      System.out.println("Could not read stock request");
      ioe.printStackTrace();
      return;
    } catch(SAXException saxe) {
      System.out.println("Could not parse stock request");
      saxe.printStackTrace();
      return;
    } catch(ClassNotFoundException cnfe) {
      System.out.println("Could not find parser");
      cnfe.printStackTrace();
      return;
    } catch(IllegalAccessException iae) {
      System.out.println("Could not access default constructor of parser");
      iae.printStackTrace();
      return;
    } catch(InstantiationException ie) {
      System.out.println("Got an exception constructing parser");
      ie.printStackTrace();
      return;
    }
 
   java.util.Hashtable trade = rh.getData();

    if (! trade.isEmpty()) {
      try {
        // Create a trader object
        Context ctx          =  new InitialContext();
        TraderHome brokerage = (TraderHome) ctx.lookup("statefulSession.TraderHome");

        // Give this trader a name
        Trader trader = brokerage.create();

        response.setContentType("text/xml");

        // get writer
        PrintWriter responseWriter = response.getWriter();
        responseWriter.println("<?xml version='1.0'?>");

        // set document type declaration
        responseWriter.println("<!DOCTYPE traderesult SYSTEM '"+serverURL+"traderesult.dtd'>");

        // do trade
        if (((String) trade.get("action")).equals("buy")) {
          TradeResult tr = trader.buy("Erin", (String) trade.get("symbol"), 
                             Integer.parseInt((String) trade.get("numShares")));

          // send result via xml
          responseWriter.println("<traderesult action='bought' symbol='"+
                                (String) trade.get("symbol")+"' numShares='"+ tr.getNumberTraded() +
                                "' price ='"+ tr.getPrice() +"' changeInAccount ='" + trader.getBalance() +"' />");
        } else if (((String) trade.get("action")).equals("sell")) {
          TradeResult tr = trader.sell("Erin", (String) trade.get("symbol"), 
                             Integer.parseInt((String) trade.get("numShares")));
          // send result via xml
          responseWriter.println("<traderesult action='sold' symbol='"+
                                (String) trade.get("symbol")+"' numShares='"+ tr.getNumberTraded() +
            "' price ='"+ tr.getPrice() +"' changeInAccount ='" + trader.getBalance() +"' />");
         }
        trader.remove();
      } catch (Exception e) {
        System.out.println(":::::::::::::: Error :::::::::::::::::");
        e.printStackTrace();
      }
    }
  }


}
