package examples.htmlkona;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import weblogic.common.*;
import weblogic.db.jdbc.*;
import weblogic.html.*;

/**
 * This servlet shows how to create an HTML page that can be used
 * interactively to take input from a client and then structure
 * a query with it.
 * 
 * @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 InteractiveQuery extends HttpServlet {

  public synchronized void service(HttpServletRequest req, HttpServletResponse res)
    throws IOException
  {
    Connection conn = null;
    
    try {
      res.setStatus(HttpServletResponse.SC_OK);
      res.setContentType("text/html");
      
      // See if invoked with an argument
      String person = req.getParameter("person");

      if (person != null) {
        ServletPage hp = new ServletPage("Results of your interactive query");
        hp.getBody()
          .addElement(MarkupElement.HorizontalLine)
          .addElement("You chose person: " + person)
          .addElement(MarkupElement.HorizontalLine);  
        hp.output(res.getOutputStream());
        return;
      }

      defaults.setPageDefaults();
      conn = defaults.login();

      TableDataSet ds = new TableDataSet(conn, "emp");
      ds.where("sal < 2000")
        .order("empno")
        .fetchRecords();

      TableElement tbl = new TableElement(ds);

      int numrows = tbl.getNumRows();
      for (int i = 1; i < numrows; i++) {
        TableDataElement cell = tbl.getRowAt(i).getCellAt(1);
        String objstr = cell.getElement().toString();
        cell.setElement(new LinkElement(defaults.prefix() + "InteractiveQuery?person=" + objstr,
					objstr));
      }

      ServletPage hp = new ServletPage("Interactive Query");
      hp.getBody()
        .addElement(MarkupElement.HorizontalLine)
        .addElement(new LiteralElement(ds))
        .addElement(MarkupElement.HorizontalLine)
        .addElement(tbl);

      ds.close();

      hp.output(res.getOutputStream());
    }
    catch (Exception e) {
      defaults.showException(e, res.getOutputStream());
    }
    finally {
      try {conn.close();} catch (Exception e2) {;}
    }
  }
}
