import UserObject;
import Configure;
import AuctionHtmlPageWriter;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import MyDateTime;


/**
 * This is the implementation of the JDBC query engine. It processes the
 * transactions to the database. It has various methods like
 * <code>checkLoginPasswd</code>, etc which return the appropriate info from
 * the database. It has two basic functions:
 * <ol>
 * <li> Retrieving information from the database
 * <li> Inserting information into the database
 * </ol>
 *
 * @author Abishek Ranjan, Himanshu Jain, Nilesh Agarwal, Sandeep Pandey    
 * @version     1.00, 07/11/2001
 */  


/*
 * boolean "checkLoginPasswd(login, passwd)"
 * return true if correct else false
 *
 * String "handleSellFormDisplay(String categoryName)"
 * returns String of html page for the given category.
 * It passes the category attribute vector to APG which returns the page. 
 * 
 * String "handleAuctionConfirmation(request)"
 * places the requested product in auction database if login/passwd correct
 * and also returns appropriate pages as: confirmation or error page(uses APG).
 *
 * void handleAuctionRevival(int prodid)
 * Revives auction from "Unsuccessful auction table"
 * 
 */


//this handles all queries
//constructor opens the DB connectmon
//and creates statement object.

public class QueryEngine{

  private Connection con;
  // private Statement stmt;
  private AuctionHtmlPageWriter apw;
  private int prodID;
  private int auctionID;
  private DatabaseMetaData dsmd; 
  public BidPageGen bpg;

  QueryEngine()
  {
	/* Statements related to bidding*/

	bpg=new BidPageGen();
	/* -------------------------*/





	apw = new AuctionHtmlPageWriter();
	prodID = 0;
	auctionID = 0;
	try
	{
	  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	  con = DriverManager.getConnection( Configure.HOST_NAME, Configure.LOGIN, Configure.PASSWD);
	  /* Statements related to Product*/

	  dsmd=con.getMetaData();  
	  /* -------------------------*/


	  // con = c;
	  System.out.println("*************************** connection opened ******************************");
	  Statement stmt = con.createStatement();

	  //now getting the last auctionID and prodID in the database.
	  int n = 0;
	  ResultSet rs_a = stmt.executeQuery("select auctionid from currentauction");
	  if(rs_a != null)
	  {
		while(rs_a.next())
		{
		  n = rs_a.getInt("auctionID");
		  System.out.println("for auction n= " + n);
		  if(n > auctionID)
		  {
			auctionID = n;
		  }
		}
	  }

	  n = 0;

	  ResultSet rs_p = stmt.executeQuery("select productID from product");

	  //now getting the last prodID in the database.
	  if(rs_p != null)
	  {
		while(rs_p.next())
		{
		  n = rs_p.getInt("PRODUCTID");
		  System.out.println("for prod  n= " + n);
		  if(n > prodID)
		  {
			prodID = n;
		  }
		}
	  }
	  rs_a.close();
	  rs_p.close();
	  stmt.close();
	  System.out.println("max auctioid, prodid= " +  auctionID + "-" + prodID);
	}
	catch(SQLException se)
	{
	  System.out.println("err:nfe:QueryEngine/constructor " + se);
	}
  }

  public void closeConn()
  {
	try
	{
	  con.close();
	}
	catch(SQLException se)
	{System.out.println("err:se:QueryEngine/closeconn");}
  }
  //-------------------------------------------------------------------------------------------
  /*
###
##    #####     ##    #    #       #    ##    #    #   ###     ####
#  #   #    #   #  #   ##   #       #   #  #   ##   #    #     #
#    #  #    #  #    #  # #  #       #  #    #  # #  #   #       ####
######  #####   ######  #  # #       #  ######  #  # #               #
#    #  #   #   #    #  #   ##  #    #  #    #  #   ##          #    #
#    #  #    #  #    #  #    #   ####   #    #  #    #           ####   



   */

  //---------------------------

  public synchronized boolean checkLoginPasswd(String login, String passwd)
  {

	String query = "select * from users where userlogin=\'" + login + "\' and passwd=\'" + passwd +"\'";		  
	try
	{
	  Statement stmt=con.createStatement();
	  ResultSet rs = stmt.executeQuery(query);
	  int count =0;
	  if(rs.next())
	  {
		System.out.println("correct login");
		rs.close();
		stmt.close();
		return true;
	  }
	  else
	  {
		System.out.println("incorrect login");
		rs.close();
		stmt.close();
		return false;
	  }


	}
	catch(SQLException se)
	{
	  System.out.println("incorrect login in exceptio" + se);
	  return false;
	}
  }

  //-------------------------------------------------------------------------------------------

  //I/P: categoryname
  //o/p: html page with with a form to fill up + login form.
  //uses query to find out attribs and types of the category.

  public synchronized void handleSellFormDisplay( PrintWriter out, String categoryName)
  {

	ResultSet rs1, rs2, rs3;
	ResultSetMetaData rsmd;
	Vector featureName = new Vector();
	Vector featureType = new Vector();
	String colName = "" ;
	System.out.println("in handleSellFormDisplay1 categoryName=" + categoryName);

	try
	{
	  Statement stmt=con.createStatement();
	  // this while loop for getting features of "Product" 
	  String query = "select featureName, featureType from CategoryFeature where categoryName ='" + categoryName + "'";
	  rs1 = stmt.executeQuery(query) ;
	  int i=0;
	  while(rs1.next())
	  {
		featureName.addElement(rs1.getObject(1));
		System.out.println("rs fname: " + (String)featureName.elementAt(i));
		featureType.addElement(rs1.getObject(2));
		System.out.println("rs ftype: " + (String)featureType.elementAt(i) );
		i++;
	  }		  		  

	  // this for loop for getting common features of "Product"			   
	  featureName.addElement("productName");
	  featureType.addElement("string");
	  featureName.addElement("IMAGEURL");
	  featureType.addElement("string");

	  // this for loop for getting features of "CurrentAuction"
	  String aucDetails = "select * from currentauction";
	  rs2 = stmt.executeQuery(aucDetails) ;
	  System.out.println("in handleSellFormDisplay2");
	  rsmd = rs2.getMetaData();
	  for (int j=0; j < rsmd.getColumnCount(); j++)
	  {
		colName = rsmd.getColumnName(j+1);
		if(!( colName.equalsIgnoreCase("PRODUCTID") ||  colName.equalsIgnoreCase("AUCTIONID") || colName.equalsIgnoreCase("SELLERLOGIN")))
		{
		  System.out.println("in if ............");
		  featureName.addElement(rsmd.getColumnName(j+1));
		  System.out.println("rs fname: " + (String)featureName.elementAt(i));
		  featureType.addElement(rsmd.getColumnTypeName(j+1));
		  System.out.println("rs ftype: " + (String)featureType.elementAt(i) );
		}
	  }
	  rs1.close();
	  rs2.close();
	  // rs3.close();
	  stmt.close();
	}
	catch(SQLException se){System.out.println("sql query in QueryEngine/handleSellFormDisplay()" + se);}		  

	//now pass the vector of featurename and featuretype for creating form and sent to client.
	apw.wrSellFormPage(out, categoryName, featureName, featureType);
  }

  //-------------------------------------------------------------------------------------------

  /* 1)i/p a HttpServletRequest containing prod specs.
   * 2)if login correct then gen. confirmation page using apg.genAuctionConfirmPage()
   * 4)and enter that prod. with specs in table.
   * 3)else apg.genLoginErrorPage();
   */	  
  public synchronized void handleAuctionConfirmation(PrintWriter out, HttpServletRequest request)
  {

	String userID = request.getParameter("Login");
	System.out.println("in hac login= " + userID);

	MyDateTime mdt = new MyDateTime();

	//Add to db only if L/P correct
	if (! checkLoginPasswd(request.getParameter("Login"), request.getParameter("Password")))
	{
	  apw.wrLoginErrorPage(out);
	}		  
	else
	{
	  Enumeration en;
	  Vector attribNames = new Vector(); //for storing request atrib names 
	  Vector attribValues = new Vector(); //for storing request attribValues

	  Vector featureName = new Vector(); //for storing featureName (obtained from DB)
	  //featureName contains only special features of the product
	  Vector featureType = new Vector(); // for storing featureType (obtained from DB)
	  //featureType contains type of special features of the Product

	  Object obj;
	  ResultSet rs;

	  String[] month = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};

	  String attName;
	  String attVal = "" , insertProdQuery = "", insertAucQuery = "";

	  String categoryName = request.getParameter("category");
	  System.out.println("categoryName in hac 2 = " + categoryName);

	  int i= 1 ;

	  prodID++;
	  auctionID++;

	  System.out.println("prodID in hac 2 = " + prodID);
	  System.out.println("auctionID in hac 2 = " + auctionID);

	  //to get the next auctionID : increaes auctionID		  
	  //to get the next prodID : increaes productID		  
	  String query = "select featureName, featureType from CategoryFeature where categoryName ='" + categoryName + "'";		  


	  System.out.println("query str at 4=  " + query);
	  try
	  {
		Statement stmt=con.createStatement();
		rs = stmt.executeQuery(query) ;

		//rs contains special features/TYpes

		System.out.println("prob");		

		//special features and type being inserted in the vector
		while(rs.next())
		{
		  featureName.addElement(rs.getObject(1));
		  featureType.addElement(rs.getObject(2));
		}

		rs.close();
		stmt.close();
	  }
	  catch(SQLException se){System.out.println("err: QueryEngine/handleSellFormDisplay()" + se);}

	  en = request.getParameterNames();

	  //From request , get the attribNames and attribValues .
	  //and get them in vector.
	  while(en.hasMoreElements())
	  {
		attName = (String)en.nextElement();
		attribNames.addElement(attName);
		attVal = request.getParameter(attName);
		if (attName != null)
		{
		  attribValues.addElement(attVal);
		}
		else
		{
		  attribValues.addElement("null");
		}				   			   
	  }
	  //for storing request atribNames            
	  //for storing request attribValues          
	  //for storing featureName (obtained from DB) 
	  // for storing featureType (obtained from DB)     

	  String d="", m="", y="";
	  String type = "";
	  String fname = "";

	  //feature name doesn't include productID

	  for (int j=0; j<featureName.size(); j++)
	  {
		System.out.println("attname/attribtype= " + (String)attribNames.elementAt(j) + " "  + (String)attribValues.elementAt(j));		
		System.out.println("fname/ftype= " + (String)featureName.elementAt(j) + "  " + (String)featureType.elementAt(j));		
	  }


	  //for loop:
	  //used to insert values from User request to :
	  // 1) ProductStringAttributes or
	  // 2) ProductIntegerAttributes . only

	  for(i=0; i<featureName.size(); i++)
	  {
		type = (String)featureType.elementAt(i);
		fname = (String)featureName.elementAt(i);

		System.out.println("value of i in for loop hahaha = " + i);		

		//check that string type features are not common features
		//they should be only special features
		//
		//1) attribtype = string but not a common prop
		if((type.equalsIgnoreCase("string")) && (! fname.equalsIgnoreCase("imageURL")) && (! fname.equalsIgnoreCase("categoryName")) && (! fname.equalsIgnoreCase("productName")))
		{
		  System.out.println("***************if part 1 fname , ftype : " + fname + " " + type);		
		  //field prodID is common for all tuples.
		  insertProdQuery = "insert into ProductStringAttributes values(";
		  insertProdQuery += prodID + ", " ;

		  insertProdQuery += "'" + fname + "'" + ", ";
		  insertProdQuery += "'" + (String)attribValues.elementAt(attribNames.indexOf(fname)) + "')";

		}

		//2) attribtype = date but not a common porp
		else if (type.equalsIgnoreCase("date"))
		{
		  System.out.println("*************if part 2 fname , ftype : " + fname + " " + type);		
		  insertProdQuery = "insert into ProductStringAttributes values(";
		  insertProdQuery += prodID + ", " ;

		  insertProdQuery += "'" + fname + "'" + ", ";

		  d = (String)attribValues.elementAt(attribNames.indexOf(fname + "day"));
		  m = (String)attribValues.elementAt(attribNames.indexOf(fname + "month"));
		  y = (String)attribValues.elementAt(attribNames.indexOf(fname + "year"));

		  System.out.println(fname + "date== " + d + "-" + month[Integer.parseInt(m)] + "-" + y );

		  insertProdQuery += "'" + d + "-" + month[Integer.parseInt(m)] + "-" + y + "')";
		}					

		//3) attribtype = integer but not a common feature 
		else if(type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("number"))
		{
		  System.out.println("***************if part 3 fname , ftype : " + fname + " " + type);		
		  insertProdQuery = "insert into ProductIntegerAttributes values(";
		  insertProdQuery += prodID + ", " ;
		  insertProdQuery += "'" + fname + "'" + ", ";
		  try
		  {
			insertProdQuery += Integer.parseInt((String)attribValues.elementAt(attribNames.indexOf(fname))) + ")";
		  }
		  catch(NumberFormatException ne)
		  {
			System.out.println("err:nfe:AuctionQueryHand1ler/handleAuctionConfirmation");
			insertProdQuery += "null";
		  }					
		}

		//insert into string/integer attribute table.
		try
		{
		  Statement stmt=con.createStatement();
		  System.out.println("*****!!@@ query 5 ******= " + insertProdQuery);
		  stmt.executeUpdate(insertProdQuery);
		  stmt.close();
		}
		catch(SQLException se)
		{System.out.println("err:se:QueryEngine/handleAuctionConfirmation/1" + i + se);}

		/*
		   else
		   {
		   insertProdQuery = "insert into Product values(";
		   insertProdQuery +="'" + (String)attribValues.elementAt(attribNames.indexOf("productName")) + "'" + ", ";
		   insertProdQuery += prodID + "," ;
		   insertProdQuery += "'" + (String)attribValues.elementAt(attribNames.indexOf("imageURL")) + "'" + ", ";
		   insertProdQuery += "'" + categoryName + "')";
		   }			
		   try
		   {
		   System.out.println("query 5= " + insertProdQuery);
		   stmt.executeUpdate(insertProdQuery);
		   }
		   catch(SQLException se)
		   {System.out.println("err:se:QueryEngine/handleAuctionConfirmation/1" + i + se);}
		 */

	  }


	  //Inserting into CurrentAuction table:
	  //*************************************
	  System.out.println("crossed 1st");

	  insertAucQuery += "insert into CurrentAuction values (";
	  insertAucQuery += auctionID + ", ";
	  insertAucQuery += prodID + ", ";
	  insertAucQuery += " '" + userID + "'"  + ", " ;
	  System.out.println("crossed 2");
	  insertAucQuery += Integer.parseInt((String)attribValues.elementAt(attribNames.indexOf("THRESHOLDPRICE"))) + ", ";
	  System.out.println("crossed 3");

	  insertAucQuery += Integer.parseInt((String)attribValues.elementAt(attribNames.indexOf("RESERVEPRICE"))) + ", ";
	  System.out.println("crossed 4");

	  d = (String)attribValues.elementAt(attribNames.indexOf("STARTDATEday"));
	  m = (String)attribValues.elementAt(attribNames.indexOf("STARTDATEmonth"));
	  y = (String)attribValues.elementAt(attribNames.indexOf("STARTDATEyear"));

	  String e = mdt.getTime();

	  String templ = "";
	  if(e.indexOf("A.M.") == -1)
	  {
		templ = "'DD-MM-YYYY HH:MI:SS P.M.'";
	  }
	  else
	  {
		templ = "'DD-MM-YYYY HH:MI:SS A.M.'";
	  }

	  String w="TO_DATE(" + "'" + d + "-" + month[Integer.parseInt(m)-1] + "-" + y + " " + e + "' ," + templ + ")" ;

	  System.out.println("*********inserted query" + w);

	  insertAucQuery += w + ", ";

	  //insertAucQuery += "'" + (String)attribValues.elementAt(attribNames.indexOf("STARTDATE")) + "' " + ", ";
	  System.out.println("crossed 5");

	  d = (String)attribValues.elementAt(attribNames.indexOf("CLOSINGDATEday"));
	  m = (String)attribValues.elementAt(attribNames.indexOf("CLOSINGDATEmonth"));
	  y = (String)attribValues.elementAt(attribNames.indexOf("CLOSINGDATEyear"));

	  System.out.println(fname + "CLOSINGDATEdate== " + w);

	  w="TO_DATE(" + "'" + d + "-" + month[Integer.parseInt(m)-1] + "-" + y + " " + e + "'," + templ + ")"; 

	  insertAucQuery += w + ", ";

	  System.out.println("*******inserted query" + w);

	  //insertAucQuery += "'"+ d +"-"+ month[Integer.parseInt(m)-1] +"-"+ y +"' "+", ";

	  //insertAucQuery += " '" + (String)attribValues.elementAt(attribNames.indexOf("CLOSINGDATE")) + "'"  + ", ";

	  System.out.println("crossed 6");

	  insertAucQuery += Integer.parseInt((String)attribValues.elementAt(attribNames.indexOf("MININCREMENT"))) + ",";
	  System.out.println("crossed 7");

	  insertAucQuery += " '" + (String)attribValues.elementAt(attribNames.indexOf("LOCATION")) + "' )" ;
	  System.out.println("crossed 8");

	  try
	  {
		Statement stmt=con.createStatement();
		System.out.println("query 6= " + insertAucQuery);
		stmt.executeUpdate(insertAucQuery);
		stmt.close();
	  }
	  catch(SQLException se){
		System.out.println("err:se:QueryEngine/handleAuctionConfirmation/auc2" + se);}


	  //Insert into Product table:
	  //**************************
	  String commFeInsertQuery = "insert into Product values (";
	  commFeInsertQuery += "'" + (String)attribValues.elementAt(attribNames.indexOf("productName")) + "' ," ;
	  commFeInsertQuery += prodID + ", ";
	  commFeInsertQuery += " '" + (String)attribValues.elementAt(attribNames.indexOf("IMAGEURL")) + "' ," ;
	  commFeInsertQuery += "'" + categoryName + "')";
	  System.out.println("crossed 8");
	  try
	  {
		Statement stmt=con.createStatement();
		System.out.println("query 7= " + commFeInsertQuery);
		stmt.executeUpdate(commFeInsertQuery);
		stmt.close();
	  }
	  catch(SQLException se)
	  {System.out.println("err:se:QueryEngine/handleAuctionConfirmation/auc3" + se);}

	  apw.wrAuctionConfirmPage(out);
	}
  }


//------------------------------------------------------------------------
  
  public synchronized void handleAuctionRevivalDisplay(PrintWriter out, int prodID)
  {
	
	apw.wrReviveAuctionPage(out, prodID);
  }
  
  
  public synchronized void handleAuctionRevival(PrintWriter out, int prodID, HttpServletRequest request)
  {

	MyDateTime mdt = new MyDateTime();
	
	String query1 = "insert into CurrentAuction (select * from UnsuccAuctHistory where productID = " + prodID + ")";
	System.out.println("here in revival: " + query1);
	String query2 = "delete from UnsuccAuctHistory where productID = " + prodID ;

	String d = request.getParameter("day");
	String m = request.getParameter("month");
	String y = request.getParameter("year");

	String[] mon = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};


	String e = mdt.getTime();
	
	String templ = "";
	if(e.indexOf("A.M.") == -1)
	{
	  templ = "'DD-MM-YYYY HH:MI:SS P.M.'";
	}
	else
	{
	  templ = "'DD-MM-YYYY HH:MI:SS A.M.'";
	}

	String closingDate ="TO_DATE(" + "'" + d + "-" + mon[Integer.parseInt(m)-1] + "-" + y + " " + e + "' ," + templ + ") " ;

	String query3 = "update CurrentAuction set ClosingDate = " + closingDate + "where productId = " + prodID ;

	System.out.println("here in revival date updating ************: " + query3);
	try
	{
	  Statement stmt1=con.createStatement();
	  stmt1.executeUpdate(query1);
	  stmt1.close();

	  Statement stmt2=con.createStatement();
	  stmt2.executeUpdate(query2);
	  stmt2.close();

	  Statement stmt3=con.createStatement();
	  stmt3.executeUpdate(query3);
	  stmt3.close();
	}	
	catch(SQLException se)
	{
	  System.out.println("error handleAuctionRevival/11" + se);
	}
	apw.wrAuctionConfirmPage(out);
  }


  //-------------------------------------------------------------------------------------------


  public synchronized void handleSearchDisplay(PrintWriter out)
  {
	apw.wrSearchPage(out);		  
  }


  //-------------------------------------------------------------------------------------------


  public synchronized void handleSearchQuery(PrintWriter out, HttpServletRequest request)
  {
	try
	{
	  Statement stmt=con.createStatement();
	  String[] mon = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
	  Vector fname = new Vector();
	  Enumeration en = request.getParameterNames();
	  ResultSet rs=null;

	  String prodName ="", reservePrice = "" , day="", month="", year="";
	  String query="";

	  System.out.println("submit1 checked************************");

	  prodName = request.getParameter("productName");
	  reservePrice = request.getParameter("bidValue");
	  day = request.getParameter("day");
	  month = request.getParameter("month");
	  year = request.getParameter("year");

	  System.out.println("values: " + prodName + ":" + reservePrice +":" + day + month + year);

	  if(en == null)
	  {
		System.out.println("just for null +++++++++++++++*");
	  }

	  while(en.hasMoreElements())
	  {
		fname.addElement(en.nextElement());
	  }


	  System.out.println("just _________________+++++++++++++++*");
	  if((prodName != null) && (fname.contains("submit1"))) //general search is requested
	  {
		System.out.println("prod eneterred");
		query = "select Product.productId from Product,CurrentAuction where Product.productId=CurrentAuction.productId and  categoryName = \'" + prodName + "\'";
		System.out.println("query1= " + query);
		rs = stmt.executeQuery(query);
		ProdHtmlGen.linksToPages(out);
		out.println("<html><body bgcolor=\"#fffff\"><b> Query Results </b></body></html>");
		while(rs.next())
		{
		  out.println(getProductDetailsPage(rs.getInt("productId")));
		}
	  }

	  else if ((reservePrice != null) && (fname.contains("submit2")))
	  {
		System.out.println("price eneterred");
		
		try
		{
		query = "select CurrentAuction.productId from CurrentBid, CurrentAuction where CurrentAuction.auctionId = CurrentBid.auctionId and bidValue <= " + Integer.parseInt(reservePrice) ;
		}
		catch(NumberFormatException ne){out.println("<html><body bgcolor=\"#fffff\"><font color=\"red\"><b>Bid value for search not an integer</b></font></body></html>");}

		
		System.out.println("query2= " + query);
		rs = stmt.executeQuery(query);

		
		out.println("<html><body bgcolor=\"#fffff\"><b> Query Results </b></body></html>");
		ProdHtmlGen.linksToPages(out);
		while(rs.next())
		{
		  out.println(getProductDetailsPage(rs.getInt("productId")));
		}

	  }
	  else if (fname.contains("submit3"))
	  {
		String date = day + "-" + mon[Integer.parseInt(month)-1] +"-" + year; 
		System.out.println("date eneterred= " + date);
		query = "select productId from CurrentAuction where closingDate <= \'" + date + "\'" ;
		System.out.println("query3= " + query);
		rs = stmt.executeQuery(query);

		ProdHtmlGen.linksToPages(out);
		out.println("<html><body bgcolor=\"#fffff\"><b> Query Results </b></body></html>");
		while(rs.next())
		{
		  out.println(getProductDetailsPage(rs.getInt("productId")));
		}
	  }
	  else
	  {
		prodName = request.getParameter("specProduct");
		System.out.println("search " + prodName);
	  }
	  rs.close();
	  stmt.close();
	  System.out.println("safe out .................");
	}
	catch(SQLException se){System.out.println("err: QueryEngine/searchdisp" + se);}
  }

  //-------------------------------------------------------------------------------------------








  /*
	 public synchronized void handleSearchQuery(PrintWriter out, HttpServletRequest request)
	 {
	 try
	 {
	 String[] mon = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
	 Vector fname = new Vector();
	 Enumeration en = request.getParameterNames();
	 ResultSet rs;

	 String prodName ="", reservePrice = "" , day="", month="", year="";
	 String query="";

	 while(en.hasMoreElements())
	 {
	 fname.addElement(en.nextElement());
	 }

	 if(fname.contains("submit1")) //general search is requested
	 {
	 System.out.println("submit1 checked************************");
	 prodName = request.getParameter("productName");
	 reservePrice = request.getParameter("reservePrice");
	 day = request.getParameter("day");
	 month = request.getParameter("month");
	 year = request.getParameter("year");


	 System.out.println(reservePrice + day + month + year);

	 System.out.println("search for " +prodName);

  if(! prodName.equals(""))
  {
	System.out.println("prod eneterred");
	query = "select productId from Product where productName = \'" + prodName + "\'";
	rs = stmt.executeQuery(query);

	while(rs.next())
	{
	  out.println(getProductDetailsPage(rs.getInt("productId")));
	}
  }


  if(! reservePrice.equals(""))
  {
	System.out.println("price eneterred");
	query = "select productId from CurrentAuction where reservePrice <= " + Integer.parseInt(reservePrice) ;
	rs = stmt.executeQuery(query);

	while(rs.next())
	{
	  out.println(getProductDetailsPage(rs.getInt("productId")));
	}
  }

  String date = day + "-" + mon[Integer.parseInt(month)-1] +"-" + year; 
  System.out.println("date eneterred= " + date);
  query = "select productId from CurrentAuction where closingDate <= \'" + date + "\'" ;
  rs = stmt.executeQuery(query);

  while(rs.next())
  {
	out.println(getProductDetailsPage(rs.getInt("productId")));
  }

}
else
{
  prodName = request.getParameter("specProduct");
  System.out.println("search " + prodName);
}
}
catch(SQLException se){System.out.println("err: QueryEngine/searchdisp" + se);}
}
*/
//-------------------------------------------------------------------------------------------








/*

#    #       #    ##       #    #    #           ####    ####   #####   ######
#    #       #   #  #      #    ##   #          #    #  #    #  #    #  #
######       #  #    #     #    # #  #          #       #    #  #    #  #####
#    #       #  ######     #    #  # #          #       #    #  #    #  #
#    #  #    #  #    #     #    #   ##          #    #  #    #  #    #  #
#    #   ####   #    #     #    #    #           ####    ####   #####   ######  

 */


/**
 *  This class is for generating all the childs for a given parent category. Output is a vector having entries for all the childs. 

 */
public synchronized Vector getChildCategoryList(String parentName){
  try{
	System.out.println("Gotta inside");
	Statement stmt=con.createStatement();
	String query="SELECT childName from ParentChild where parentName= "+"'"+parentName+"'";
	//System.out.println(query);
	ResultSet rs=stmt.executeQuery(query);
	System.out.println("query is "+query);
	Vector resultVec=new Vector(10,10);
	while(rs.next()){
	  resultVec.addElement(rs.getString(1));
	} 
	rs.close();
	stmt.close();
	return resultVec; 
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}   
  }
  return null;
}


// public synchronized Vector getInfoOfProductsOnAuction


/*This function will be used by sysad for inserting new Categories. */
public synchronized boolean addNewCategory(String parentName,String childCategoryName){
  boolean succsesFullyInserted=false;
  try{
	Statement stmt=con.createStatement();
	String query="INSERT into ParentChild values('"+parentName+"','"+childCategoryName+"')";
	System.out.println(query);
	ResultSet rs=stmt.executeQuery(query);
	succsesFullyInserted=true;
	rs.close();
	stmt.close();
	return succsesFullyInserted;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return succsesFullyInserted;
}

/*
   1. Assuming featureNameAndType is a vector of objects which are (feature name, type attributes)
   2. This will also be used by Dbase administrator
   3. Feature type supposed to be integer or string
 */
public synchronized boolean addFeaturesToCategory(String categoryName, Vector featureNameAndType){
  boolean succsesFullyAdded=false; 
  try{
	Statement stmt=con.createStatement();
	String query="INSERT into CategoryFeature values ('" + categoryName + "','";
	int size=featureNameAndType.size();
	// System.out.println("size is: "+size);
	ResultSet rs=null;
	String query1=null;
	for(int i=0;i<size;i++){
	  ProdFeatureNameAndType fnatObj=(ProdFeatureNameAndType)featureNameAndType.elementAt(i);
	  query1=query+ fnatObj.getFeatureName() + "','" + fnatObj.getFeatureType() + "')";
	  System.out.println("Query for adding features is : "+ query1);
	  rs=stmt.executeQuery(query1);
	  rs.close();
	}

	stmt.close();
	succsesFullyAdded=true;
	return succsesFullyAdded;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return succsesFullyAdded;
}

/*
Assumption:
Passed categoryName actually exixts in Database.

1. This function returns true if a category is not final, else it returns false. 
Further more categories can be added under a category which is not final. A category is not final if it      has some childs in ParentChild. In case its not a Parent of any category in ParentChild then if it has       no products currently placed under it, it is not final. 


 */
public synchronized boolean isNotFinal(String categoryName){
  boolean isNotFinal=false;
  try{
	Statement stmt=con.createStatement();
	String query="SELECT * from ParentChild where parentName="+"'"+categoryName+"'";
	ResultSet rs=stmt.executeQuery(query);
	int numberOfChilds=0;
	while(rs.next()){
	  numberOfChilds++;
	} 
	rs.close();

	if (numberOfChilds>0){
	  isNotFinal=true;         //Because this category is already a parent so its not final
	}
	else{
	  query="SELECT * FROM Product where categoryName="+ "'" + categoryName+ "'";
	  rs=stmt.executeQuery(query);
	  int numberOfProductsUnderThis=0;
	  while(rs.next()){
		numberOfProductsUnderThis++;
	  } 
	  if(numberOfProductsUnderThis==0){
		isNotFinal=true;
	  }
	  else{
		isNotFinal=false;
	  }
	  rs.close();
	}
	stmt.close();
	return isNotFinal;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return isNotFinal;

}

/*
Assumption:
Passed categoryName actually exixts in Database.

1. This function deletes a category if it does not have any sub-categories under it.  
2. If it does not have sub-categories then it checks if it does not have any products in it.
 */

public synchronized boolean canBeDeleted(String categoryName){
  boolean canBeDel=false;
  try{
	Statement stmt=con.createStatement();
	String query="SELECT * from ParentChild where parentName="+"'"+categoryName+"'";
	ResultSet rs=stmt.executeQuery(query);
	int numberOfChilds=0;
	while(rs.next()){
	  numberOfChilds++;
	} 
	rs.close();

	if (numberOfChilds>0){
	  canBeDel=false;         //Because this category is already a parent so its not final
	}
	else{
	  query="SELECT * FROM Product p,CurrentAuction ca where categoryName="+ "'" + categoryName+ "' and ca.productId=p.productId";
	  rs=stmt.executeQuery(query);
	  int numberOfProductsUnderThis=0;
	  while(rs.next()){
		numberOfProductsUnderThis++;
	  } 
	  if(numberOfProductsUnderThis==0){
		canBeDel= true;
	  }
	  else{
		canBeDel= false;
	  }
	  rs.close();
	}
	stmt.close();
	System.out.println("Can be deleted is : "+canBeDel);
	return canBeDel;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return canBeDel;

}
/*
   This function deletes a category, by checking if it can be deleted
 */

public synchronized String deleteTheCategory(String categoryName){
  boolean wasDeleted= false;
  boolean isPossibleToDelete= canBeDeleted(categoryName);
  String result="nil";
  if (isPossibleToDelete){
	System.out.println("Yes Possible to delete");
	try{
	  Statement stmt1=con.createStatement();
	  Statement stmt2=con.createStatement();
	  String query1="DELETE from CategoryFeature where categoryName="+"'"+categoryName+"'";
	  String query2="DELETE from ParentChild where childName="+"'"+categoryName+"'";
	  System.out.println("Trying to execute the updates");
	  stmt1.executeUpdate(query1);
	  System.out.println("First level of deletes done");

	  stmt2.executeUpdate(query2);
	  System.out.println("Second level of deletes done");
	  result="Category Deleted Successfully";
	  stmt1.close();
	  stmt2.close();
	}
	catch(SQLException sqle){
	  while(sqle != null){
		System.out.println("SQLState: "+sqle.getSQLState());
		System.out.println("Message: "+sqle.getMessage());
		sqle=sqle.getNextException();
		System.out.println(" ");
	  }
	  result="Problem Occured while Deleting the Category";
	}
  }
  else{
	System.out.println("No not possible to delete");
	result= "Sorry! Cannot be deleted. It contains memeber inside it.";
  }
  return result;
}

/* This function checks if the sub category to be created in the parent Category, have a name collision with an already exixting sub category. Accordingly returns a boolean. A parent category have zero or more sub categories.   

 */

public synchronized boolean isCategoryNameOverlaping(String parentCatName,String childSubCatName){
  boolean isCategoryNameOverlaping=false;
  try{
	Statement stmt=con.createStatement();
	String query="SELECT childName from ParentChild where parentName="+"'"+parentCatName+"'";
	ResultSet rs=stmt.executeQuery(query);

	while ((rs.next()) && (!isCategoryNameOverlaping)){
	  if(childSubCatName.equals(rs.getString(1))){
		isCategoryNameOverlaping=true;
	  }
	}
	rs.close();
	stmt.close();
	return isCategoryNameOverlaping;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return (! isCategoryNameOverlaping);
}

/*
   This function given an auction Id determines whether the particular auction was successful or not.

   If there are any bids, the auction is successful ir returns true else it returns false... 
 */

public synchronized boolean whetherSuccessfulAuction(int auctionId){
  boolean whetherSuccess=false;
  String query="select count(*) from CurrentBid cb where cb.auctionId="+auctionId;
  System.out.println(query);
  try{
	Statement stmt=con.createStatement();
	ResultSet rs=stmt.executeQuery(query);
	int count=0;
	while(rs.next()){
	  count= rs.getInt(1);
	}

	if(count>0){ 
	  whetherSuccess=true;
	}
	rs.close();
	stmt.close();
	return whetherSuccess ;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
  return whetherSuccess;
}

/*
   This function made by pandey to shift bids of current auctions whose closing date has been exceeded to Bidhistory

   To be tested
 */
public synchronized void removeBidsOfOutdatedAuctions (int auctionId){
  try{
	Statement stmt=con.createStatement();
	String query="insert into BidHistory (select bidId,auctionId,bidderLogin,bidValue,autobid,bidTime from CurrentBid where CurrentBid.auctionId="+auctionId+")";
	System.out.println(query);
	stmt.executeUpdate(query);
	query="delete from CurrentBid where auctionId="+auctionId; 
	System.out.println(query);
	stmt.executeUpdate(query);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception in removing Bid " + sqle);
  }
}



/*
   This function will shift all the auctions whose closing date has been exceeded.

   Only auctions which are going to be listed will be checked against there closing date.

   Very Important query needs to be documented fully
 */

public synchronized void updateAuctionTableAndShift (String finalCatName){
  String query="select ca.auctionId, ca.productId, ca.sellerLogin, ca.thresholdPrice, ca.reservePrice, ca.minIncrement, ca.location, TO_CHAR(ca.startDate,'yyyy-mm-dd hh:mi:ss.AM'),TO_CHAR(ca.closingDate,'yyyy-mm-dd hh:mi:ss.AM') from CurrentAuction ca, Product p where p.productId=ca.productId and p.categoryName='"+finalCatName+"' and ca.closingDate< sysdate";
  try{	 	     
	int auctionId;
	int productId;
	int thresholdPrice;
	int reservePrice;
	int minIncrement;

	String sellerLogin=null;
	String location=null;

	// java.sql.Date closingDate=null;
	// java.sql.Date startDate=null;
	// java.sql.Date curDate=new java.sql.Date(System.currentTimeMillis());

	// Timestamp curdt=new Timestamp(System.currentTimeMillis());
	// System.out.println("fundaes on timestamp"+curdt.toString());

	System.out.println("Query to be executed: "+query);

	Statement stmt=con.createStatement();
	ResultSet rs=stmt.executeQuery(query);

	System.out.println("watt lag gayi");
	while(rs.next()){
	  // startDate= rs.getDate(6);
	  //  closingDate= rs.getDate(7);
	  String startDateString= rs.getString(8);
	  String closingDateString= rs.getString(9);
	  System.out.println("startDateString "+startDateString);
	  System.out.println("closingDateString "+closingDateString);



	  // long isAuctionTimeOver= closingDate.getTime();//-curDate.getTime();
	  // System.out.println(isAuctionTimeOver);

	  //  if (isAuctionTimeOver <0){
	  //  System.out.println("Now I have to do shifting babes");
	  auctionId= rs.getInt(1);
	  productId= rs.getInt(2);
	  sellerLogin= rs.getString(3);
	  thresholdPrice= rs.getInt(4);
	  reservePrice= rs.getInt(5);

	  minIncrement=rs.getInt(6);
	  location=rs.getString(7);

	  boolean isSuccessful= whetherSuccessfulAuction(auctionId);

	  if (isSuccessful) {
		System.out.println(" Do a lotsa work, and the auction in consideration is successful"); 

		String queryToFindWinner="select bidderLogin,bidValue from CurrentBid where auctionId="+auctionId;
		Statement stmt1=con.createStatement();
		ResultSet rs1=stmt1.executeQuery(queryToFindWinner);
		String winnerBidderLogin=null;
		int winnerBidPrice=0;
		while(rs1.next()){
		  winnerBidderLogin=rs1.getString(1);
		  winnerBidPrice=rs1.getInt(2);
		}
		rs1.close();
		stmt1.close();
		System.out.println("Winner login:"+winnerBidderLogin+" Winner Bid: "+winnerBidPrice);

		String insQuery="insert into succAuctHistory values ("+auctionId+","+productId+",'"+sellerLogin+"',"+thresholdPrice+","+reservePrice+",'"+winnerBidderLogin+"',"+winnerBidPrice+")";

		System.out.println("insQuery: "+insQuery);

		String delQuery="delete from CurrentAuction where auctionId="+auctionId;

		// Shifting bids by calling pandey's function
		System.out.println("Calling pandeys func");
		removeBidsOfOutdatedAuctions(auctionId);

		Statement updateStmt=con.createStatement();
		System.out.println("Executing 2 queries");
		updateStmt.executeUpdate(insQuery);
		System.out.println("Executed one query");
		updateStmt.executeUpdate(delQuery);
		updateStmt.close();
	  }
	  else{
		System.out.println("well wasn't tghat successful");
		startDateString="TO_DATE('"+startDateString+"','yyyy-mm-dd hh:mi:ss.AM')";
		closingDateString="TO_DATE('"+closingDateString+"','yyyy-mm-dd hh:mi:ss.AM')";
		// System.out.println(startDateString+"  "+ closingDateString);

		String insQuery=" insert into UnsuccAuctHistory values ("+auctionId+","+productId+",'" +sellerLogin+"'," +thresholdPrice+"," +reservePrice+"," +startDateString+"," +closingDateString+"," +minIncrement+",'" +location+ "')";
		String delQuery="delete from CurrentAuction where auctionId="+auctionId;
		System.out.println(" insQuery: "+insQuery);
		System.out.println(" delQuery: "+delQuery);

		Statement updateStmt=con.createStatement();
		updateStmt.executeUpdate(insQuery);
		updateStmt.executeUpdate(delQuery);
		updateStmt.close();
		System.out.println("Checking for next auction");
	  }
	  // }
	  // else{
	  // System.out.println("Still time to go");
	  // }
	}
	stmt.close();
	//	     updateStmt.close();
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}  
  }
}

/*
   Converts an Java Date object to String which can be inserted in Database..
 */

//  private synchronized String convertToSqlString(java.sql.Date jsd){


// } 



/* 1. Displays the details of all the current auctions going on in a particular final category.

   2. The details which are stored in result vector are productId, ProductName, city, current max. bid on a particular product, numberOfBids, closingDate   
 */
public synchronized Vector productDetailsOfFinalCategory(String finalCatName){
  String query="select p.productId, p.productName, ca.location, ca.closingDate, ca.auctionId from Product p, CurrentAuction ca where  p.categoryName='"+ finalCatName+"' and p.productId=ca.productId group by  p.productId, p.productName, ca.location,ca.closingDate, ca.auctionId";
  try{
	System.out.println("Calling updateAuctionTableAndShift");
	updateAuctionTableAndShift(finalCatName);
	System.out.println("Executed updateAuctionTableAndShift");
	Statement stmt=con.createStatement();
	ResultSet rs=stmt.executeQuery(query);
	Vector resultVec=new Vector(10,10);
	System.out.println("query is: "+ query);
	String maxCount=null;
	String numberOfBids=null;
	String numberOfBids1=null;
	while(rs.next()){
	  Vector indivVec=new Vector(6);
	  Vector maxBidAndCount=retMaxBidAndCountVector(rs.getString(5));
	  if (maxBidAndCount.size() == 2){
		maxCount= (String)maxBidAndCount.elementAt(0);
		numberOfBids= (String)maxBidAndCount.elementAt(1);
		System.out.println(" Laocation after maxBidAndCoun "+maxCount+" "+ numberOfBids);
	  }
	  if (maxCount == null){
		maxCount="No bids";
	  }

	  numberOfBids1=retCountOfParticularAuction(rs.getString(5));
	  int count=Integer.parseInt(numberOfBids)+Integer.parseInt(numberOfBids1);

	  indivVec.addElement(rs.getString(1)); // adding productId to vector
	  indivVec.addElement(rs.getString(2)); // adding productName to vector
	  indivVec.addElement(rs.getString(3)); // adding location of auc. to vector
	  indivVec.addElement(maxCount); // maximum bid on that prod.
	  // indivVec.addElement(numberOfBids); // number of bids
	  String count1=""+count;
	  indivVec.addElement(count1); // number of bids

	  indivVec.addElement(rs.getString(4)); // closing date of auction

	  resultVec.addElement(indivVec);       // Adding this vector to vector of vectors.
	  System.out.println("In adding vec "+rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5));
	} 
	rs.close();
	stmt.close();
	return resultVec; 
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}   
  }
  return null;
}

/*
   This func  used by above function , to find max. bid and number of bids for a particular product.
 */

private synchronized Vector retMaxBidAndCountVector(String auctionId){
  String query="select max(bidValue),count(*) from CurrentBid where auctionId='"+auctionId+"'";
  try{
	Statement stmt=con.createStatement();
	ResultSet rs=stmt.executeQuery(query);
	Vector rv=new Vector(2);
	while(rs.next()){
	  rv.addElement(rs.getString(1));
	  rv.addElement(rs.getString(2));
	}
	rs.close();
	stmt.close();
	return rv;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}   
  }
  return null;
}

/* This function returs*/

private synchronized String retCountOfParticularAuction(String auctionId){
  String query="select count(*) from BidHistory where auctionId='"+auctionId+"'";
  String count=null;
  try{
	Statement stmt=con.createStatement();
	ResultSet rs=stmt.executeQuery(query);
	System.out.println("Query is: "+ query);
	while(rs.next()){
	  count=rs.getString(1);
	  System.out.println("Count is: "+count);
	}
	rs.close();
	stmt.close();
	return count;
  }
  catch(SQLException sqle){
	while(sqle != null){
	  System.out.println("SQLState: "+sqle.getSQLState());
	  System.out.println("Message: "+sqle.getMessage());
	  sqle=sqle.getNextException();
	  System.out.println(" ");
	}   
  }
  return count;
}




/*                                                ###
#####     ##    #    #  #####   ######   #   #   ###     ####
#    #   #  #   ##   #  #    #  #         # #     #     #
#    #  #    #  # #  #  #    #  #####      #     #       ####
#####   ######  #  # #  #    #  #          #                 #
#       #    #  #   ##  #    #  #          #            #    #
#       #    #  #    #  #####   ######     #             ####   

 */




public synchronized String getProductDetailsPage(int productId){
  String query=null,Page=null;
  ResultSet rs=null;
  try{
	//	    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select location,CurrentAuction.auctionId auctionId,bidValue,minIncrement,startDate,closingDate,thresholdPrice from CurrentAuction,CurrentBid where ((CurrentBid.auctionId=CurrentAuction.auctionId)and(CurrentAuction.productId="+productId+"))";
	rs=stmt.executeQuery(query);
	System.out.println("problem here");
	if (rs.next()) {
	  System.out.println("if in detail page");
	  Page=bpg.makeProductDetailsPage(rs,1);
	}
	else {
	  query="select auctionId,productId,sellerLogin,thresholdprice,reserveprice,startdate,closingdate,minincrement,location from CurrentAuction where CurrentAuction.productId="+productId;
	  System.out.println(query);
	  rs.close();
	  rs=stmt.executeQuery(query);
	  rs.next();
	  System.out.println("else in detail page");
	  Page=bpg.makeProductDetailsPage(rs,0);
	  rs.close();
	  stmt.close();
	}
	//con.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return Page;
}

public synchronized String getBidFormPage(int productId){
  String query=null,Page=null;
  ResultSet rs=null;
  try{
	//	    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select bidValue,minIncrement from CurrentAuction,CurrentBid where ((CurrentBid.auctionId=CurrentAuction.auctionId)and(CurrentAuction.productId="+productId+"))";
	rs=stmt.executeQuery(query);
	if(rs.next()){
	  Page=bpg.makeBidFormPage(rs);
	}
	else{
	  query="select thresholdPrice,minIncrement from CurrentAuction where (CurrentAuction.productId="+productId+")";
	  rs=stmt.executeQuery(query);
	  rs.next();
	  Page=bpg.makeBidFormPage(rs);
	  rs.close();
	  stmt.close();
	}
	//con.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return Page;
}


public synchronized String  getBidDetailsPage(int productId){
  String query=null,Page=null;
  ResultSet rs=null;
  try{
	///DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select auctionId from CurrentAuction where CurrentAuction.productId="+productId;
	rs=stmt.executeQuery(query);
	rs.next();
	Page=bpg.makeBidDetailsPage(rs);
	rs.close();
	stmt.close();
	//con.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return Page;
}




public synchronized String getBidHistoryPage(int auctionId){
  String query=null,Page=null;
  ResultSet rs=null;
  try{
	//	    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select bidderLogin,bidValue,TO_CHAR(bidtime,'DD-MON-YY HH:MI:SS A.M.') as bidTime from BidHistory where BidHistory.auctionId="+auctionId; 
	rs=stmt.executeQuery(query);
	//rs.next();
	Page=bpg.makeBidHistoryPage(rs);
	rs.close();
	stmt.close();
	//con.close();
	//Under construction ----------------------*****************
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return Page;
}



public synchronized String getItemInfoPage(int auctionId){
  String Page=null;
  String query=null,productName;

  int productId=0;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	query="select productName from CurrentAuction,Product where ((CurrentAuction.productId=Product.productId)and(CurrentAuction.auctionId="+auctionId+"))";
	//ResultSetMetaData rsmd=rs.getMetaData();
	rs=stmt.executeQuery(query);
	rs.next();
	productName=rs.getString("productName");

	Page="<br>";
	Page+="<table width=760 border=\"0\" bgcolor=\"#ffffff\"><tr><td bgcolor=\"FFFFFF\">";
	Page+="<table width=\"760\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#CCCCFF\">";
	Page+="<tr bgcolor=\"#CCCCFF\">";
	Page+="<td class=\"cathead\" height=\"20\">&nbsp;<a name=\"desc\">Product Details</a></td>";
	Page+="</tr>";
	Page+="<tr bgcolor=\"#FFFFFF\">";
	Page+="<td class=\"cathead\" height=\"20\">&nbsp;</td>";
	Page+="</tr>";

	Page+="<tr>";
	Page+="<td>";
	Page+="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#CCCCFF\">";
	Page+="<tr>";
	Page+="<td rowspan=\"2\" width=\"5\"><img src=\"../images/spacer.gif\" width=\"6\" height=\"1\"></td>";
	Page+="<td bgcolor=\"#CCCCFF\">&nbsp;</td>";
	Page+="<td rowspan=\"2\" width=\"5\"><img src=\"../images/spacer.gif\" width=\"6\" height=\"1\"></td>";
	Page+="</tr>";
	Page+="<tr>";
	Page+="<td class=\"cathead\" align=\"center\">"+productName+"</td>";
	Page+="</tr>";
	Page+="<tr>";
	Page+="<td width=\"5\"><img src=\"../images/spacer.gif\" width=\"6\" height=\"5\"></td>";
	Page+="</tr>";
	Page+="<tr bgcolor=\"#CCCCFF\">";
	Page+="<td width=\"5\">&nbsp;</td>";
	Page+="<td>";
	Page+="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" height=\"100%\" bgcolor=\"#CCCCCC\">";
	Page+="<tr><td>";
	Page+="<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\" height=\"100%\">";
	Page+="";
	Page+="<tr><td><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" height=\"100%\"><tr bgcolor=\"#CCCCFF\"><td  height=\"25\" align=left class=\"cathead\" >Item Description</td></tr><tr bgcolor=\"#EFEFEF\"><td  height=\"25\" align=left class=\"details\">"+productName+"</td></tr>";


	query="select attributeName,attributeValue from ProductStringAttributes,CurrentAuction where ((ProductStringAttributes.productId=CurrentAuction.productId)and(CurrentAuction.auctionId = "+auctionId+"))";
	rs=stmt.executeQuery(query);
	int col=1;
	while (rs.next()){
	  Page+="<tr><td bgcolor=\"#CCCCFF\" width=\"100%\" align=left class=\"cathead\">"+rs.getString("AttributeName")+"</td></tr><tr><td bgcolor=\"#EFEFEF\" width=\"100%\" align=left class=\"details\">"+rs.getString("attributeValue")+"</td></tr><tr></tr><tr></tr>";

	}


	query="select attributeName,attributeValue from ProductIntegerAttributes,CurrentAuction where ((ProductIntegerAttributes.productId=CurrentAuction.productId)and(CurrentAuction.auctionId = "+auctionId+"))";
	rs=stmt.executeQuery(query);

	while (rs.next()){
	  Page+="<tr><td bgcolor=\"#CCCCFF\" width=\"100%\" align=left class=\"cathead\">"+rs.getString("AttributeName")+"</td></tr><tr><td bgcolor=\"#EFEFEF\" width=\"100%\" align=left class=\"details\">"+rs.getInt("attributeValue")+"</td></tr><tr></tr><tr></tr>";

	}

	Page+="</table>";

	Page+="</td></tr>";

	Page+="<tr><td bgcolor=\"#CCCCFF\" width=\"100%\" align=\"center\"><a href=\"#bid_now\"><img vspace=4 src=\"../images/bid_now.gif\" border=0></a></td></tr>";
	Page+="</table>";
	Page+="</td>";
	Page+="</tr>";
	Page+="</table>";
	Page+="<td width=\"5\"><img src=\"../images/spacer.gif\" width=\"5\" height=\"1\"></td>";
	Page+="</tr>";
	Page+="</table>";
	Page+="</td>";
	Page+="</tr>";
	Page+="<tr bgcolor=\"#CCCCFF\">";
	Page+="<td><img src=\"../images/spacer.gif\" width=\"1\" height=\"6\"></td>";
	Page+="</tr>";
	Page+="</table>";
	Page+="</td></tr>";
	Page+="</table>";
	Page+="</td></tr></table>";
	Page+="        ";
	Page+="<!-- End servlet AuctionMain -->";
	Page+="</td>";
	Page+="</tr>";
	Page+="</table>";
	Page+="<br>";
	Page+="";
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return Page;
}






public synchronized int getCurrentBid(int productId){
  String query=null;
  int cid=0;
  ResultSet rs=null;
  try{
	DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select bidValue from CurrentAuction,CurrentBid where ((CurrentBid.auctionId=CurrentAuction.auctionId)and(CurrentAuction.productId="+productId+"))";
	rs=stmt.executeQuery(query);
	rs.next();
	cid=rs.getInt("bidValue");
	rs.close();
	stmt.close();
	//con.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return cid;
}


public synchronized int IsValidUser(String login,String passwd){
  String query=null;
  int stat=0;
  ResultSet rs=null;
  try{
	//DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query="select userLogin from Users where ((userLogin='"+login+"')and (passwd='"+passwd+"'))";
	rs=stmt.executeQuery(query);
	//rs.next();
	if(!rs.next()){
	  System.out.println(login+passwd);
	  stmt.close();
	  //con.close();
	  return 1;
	}
	else{
	  System.out.println(login+passwd);
	  //System.out.println(rs.getString("userLogin"));
	  //con.close();
	  stmt.close();
	  return 0;
	}
  }catch(SQLException sqle){
	System.out.println("Exception in Isvaliduser " + sqle);

  }
  return 0;
}


public synchronized void updateCurrentBid(int productId,int nextBid,String bidderLogin,String autobid,int maxamt){
  String query1=null,query2=null,query3=null,query4=null,query5=null;
  String query6=null,query7=null,query8=null,query9=null,query10=null;
  ResultSet rs=null;
  String timeOfBid;
  int bi,nb,auctionId,prevMaxAmt,temp;
  String isPrevBidAuto="n";
  String pain="','DD-MON-YYYY HH:MI:SS";
  MyDateTime mdt=new MyDateTime();
  timeOfBid=mdt.getDate()+" "+mdt.getTime();
  if (timeOfBid.indexOf("A.M.")==-1)
	pain+=" A.M.'";
  else
	pain+=" P.M.'";

  System.out.println("++++++++"+timeOfBid+"*********");
  try{
	//  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//con=DriverManager.getConnection("jdbc:oracle:thin:@everest:1521:GEN","pandey","urgonemad");
	Statement stmt=con.createStatement();
	query1="insert into BidHistory (select bidId,CurrentAuction.auctionId auctionId,bidderLogin,bidValue,autobid,bidTime from CurrentBid,CurrentAuction where ((CurrentBid.auctionId=CurrentAuction.auctionId)and(CurrentAuction.productId="+productId+")))";
	query2="select bidId,CurrentAuction.auctionId auctionId,autobid,maxAmount from CurrentBid,CurrentAuction where ((CurrentBid.auctionId=CurrentAuction.auctionId)and(CurrentAuction.productId="+productId+"))";
	System.out.println(query1+query2);
	//rs=stmt.executeQuery(query1);
	rs=stmt.executeQuery(query2);
	autobid=convertInttoString(autobid);
	System.out.println("This bid is :"+autobid);
	if (rs.next()){
	  System.out.println("Not first Bid");
	  bi=rs.getInt("bidId");
	  auctionId=rs.getInt("auctionId");
	  System.out.println("autobid pain kya");
	  isPrevBidAuto=rs.getString("autobid");
	  System.out.println(isPrevBidAuto);
	  if (isPrevBidAuto.indexOf("y")!=-1){
		System.out.println("Prev bid id autobid");
		prevMaxAmt=rs.getInt("maxAmount");
		System.out.println(prevMaxAmt);
		if(autobid.indexOf("y")!=-1){
		  System.out.println("Both autobid");
		  if(prevMaxAmt < maxamt){

			query4="select max(bidId) bidId from CurrentBid";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			nb=rs.getInt("bidId")+1;
			query4="select max(bidId) bidId from BidHistory";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			temp=rs.getInt("bidId")+1;
			if(nb<temp)
			  nb=temp;

			//rs=stmt.executeQuery(query3);
			System.out.println("mar gaye re");
			stmt.executeQuery(query1);
			System.out.println("Both autobid and if part");
			query3="delete from CurrentBid where bidId="+bi; 
			System.out.println(query3);
			rs=stmt.executeQuery(query3);

			//***************************
			//************************
			//Latest change            
			prevMaxAmt++;

			System.out.println("Here in this part 5");
			//query5="insert into CurrentBid values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+prevMaxAmt+" ,'"+autobid+"' ,"+maxamt+" ,"+" '20-OCT-01')";
			query5="insert into CurrentBid values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+prevMaxAmt+" ,'"+autobid+"' ,"+maxamt+" ,"+" TO_DATE('"+timeOfBid+pain+"))";

			System.out.println(query5);
			stmt.executeQuery(query5);


		  }
		  else{

			System.out.println("Both autobid and else part");

			query4="select max(bidId) bidId from CurrentBid";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			nb=rs.getInt("bidId")+1;
			query4="select max(bidId) bidId from BidHistory";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			temp=rs.getInt("bidId")+1;
			if(nb<temp)
			  nb=temp;


			maxamt++;
			query3="update CurrentBid set bidValue = "+maxamt+"  where bidId = "+bi;
			System.out.println(query3);
			stmt.executeQuery(query3);
			System.out.println("Here in this part 1");

			query5="insert into BidHistory values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+nextBid+" ,'"+autobid+"' ,"+" TO_DATE('"+timeOfBid+pain+"))";
			System.out.println(query5);
			stmt.executeQuery(query5);
		  }
		}
		else {
		  if (nextBid<prevMaxAmt) {
			query4="select max(bidId) bidId from CurrentBid";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			nb=rs.getInt("bidId")+1;
			query4="select max(bidId) bidId from BidHistory";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			temp=rs.getInt("bidId")+1;
			if(nb<temp)
			  nb=temp;
			System.out.println("Here in this part 2");
			nextBid++;
			query3="update CurrentBid set bidValue = "+nextBid+"  where bidId = "+bi;
			System.out.println(query3);
			stmt.executeQuery(query3);		    
			nextBid--;
			query5="insert into BidHistory values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+nextBid+" ,'"+autobid+"' ,"+" TO_DATE('"+timeOfBid+pain+"))";
			System.out.println(query5);
			stmt.executeQuery(query5);

		  }
		  else {
			query4="select max(bidId) bidId from CurrentBid";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			nb=rs.getInt("bidId")+1;
			query4="select max(bidId) bidId from BidHistory";
			System.out.println(query4);
			rs=stmt.executeQuery(query4);
			rs.next();
			temp=rs.getInt("bidId")+1;
			if(nb<temp)
			  nb=temp;

			System.out.println("mar gaye re");
			stmt.executeQuery(query1);
			System.out.println("This not autobidandelse part");
			query3="delete from CurrentBid where bidId="+bi; 
			System.out.println(query3);
			rs=stmt.executeQuery(query3);
			System.out.println("Here in this part 3");
			query5="insert into CurrentBid values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+nextBid+" ,'"+autobid+"' ,"+maxamt+" ,"+" TO_DATE('"+timeOfBid+pain+"))";
			System.out.println(query5);
			stmt.executeQuery(query5);
		  }    
		}
	  }
	  else {
		//========= Part on Construction now
		query4="select max(bidId) bidId from CurrentBid";
		System.out.println(query4);
		rs=stmt.executeQuery(query4);
		rs.next();
		nb=rs.getInt("bidId")+1;
		query4="select max(bidId) bidId from BidHistory";
		System.out.println(query4);
		rs=stmt.executeQuery(query4);
		rs.next();
		temp=rs.getInt("bidId")+1;
		if(nb<temp)
		  nb=temp;

		//rs=stmt.executeQuery(query3);
		//System.out.println("mar gaye re");
		stmt.executeQuery(query1);
		System.out.println("Prev bid was not autobid");
		query3="delete from CurrentBid where bidId="+bi; 
		System.out.println(query3);
		rs=stmt.executeQuery(query3);
		System.out.println("Here in this part 4");
		query5="insert into CurrentBid values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+nextBid+" ,'"+autobid+"' ,"+maxamt+" ,"+" TO_DATE('"+timeOfBid+pain+"))";
		System.out.println(query5);
		stmt.executeQuery(query5);
		//   stmt.close();

	  }
	}
	else {
	  System.out.println("It cant be here ");
	  query3="select auctionId from CurrentAuction where CurrentAuction.productId="+productId;
	  rs=stmt.executeQuery(query3);
	  rs.next();
	  auctionId=rs.getInt("auctionId");
	  System.out.println("Its first bid on this product");

	  query4="select max(bidId) bidId from CurrentBid";
	  System.out.println(query4);
	  rs=stmt.executeQuery(query4);
	  rs.next();
	  nb=rs.getInt("bidId")+1;
	  System.out.println("Here in this part 6");
	  query5="insert into CurrentBid values ("+nb+" ,"+auctionId+" ,'"+bidderLogin+"' ,"+nextBid+" ,'"+autobid+"' ,"+maxamt+" ,"+" TO_DATE('"+timeOfBid+pain+"))";
	  System.out.println(query5);
	  stmt.executeQuery(query5);
	  //rs.close();
	  //stmt.close();

	}
	stmt.close();
	//con.close();
  }catch(SQLException sqle){
	System.out.println("Exception in Update " + sqle);
  }
}



String convertInttoString(String autobid){
  if(autobid.indexOf("1")!=-1)
	return "y";
  else
	return "n";
}

/*Just for testing if queries are working properly or not*/

public static void main(String[] args){
  //QueryEngine qe=Shared;
  //  Vector rv= (SharedObjects.qe).getChildCategoryList("Computers");
  //  	int size=rv.size();
  //  	for(int i=0;i<size;i++){
  //  	    String s=(String) rv.elementAt(i);
  //  	    System.out.println(s);
  //  	}

  // (SharedObjects.qe).updateAuctionTableAndShift("Ram");
  //    boolean b=(SharedObjects.qe).whetherSuccessfulAuction(10323);
  //   	if (b) {
  //    	    System.out.println("Yes successful");
  //    	}
  //    	else{
  //    	    System.out.println("no not successful");
  //    	}
  System.out.println("Calling the function");
  // (SharedObjects.qe).updateAuctionTableAndShift("Ram");

  String b=(SharedObjects.qe).deleteTheCategory("Electronics");
  System.out.println("String is: "+b);
}

/*

#    #     #    #       ######   ####   #    #    ##     ####
##   #     #    #       #       #       #    #   #  #   #    #
# #  #     #    #       #####    ####   ######  #    #  #
#  # #     #    #       #            #  #    #  ######  #  ###
#   ##     #    #       #       #    #  #    #  #    #  #    #
#    #     #    ######  ######   ####   #    #  #    #   ####     

 */

// returns true if a login, password pair exist. else returns false  //CHECKED
public synchronized boolean isValidUser(String login, String password){
  String queryStatement=null;
  ResultSet rs=null;
  System.out.println("login: "+ login);
  System.out.println("password: "+ password);
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT userLogin FROM Users WHERE userLogin='"+login+"' and passwd='"+password+"'";
	System.out.println(queryStatement);
	rs=stmt.executeQuery(queryStatement);
	int test=0;
	while (rs.next()){
	  test++;
	}
	if(test==0){
	  System.out.println("no such user passwd pair exist");
	  rs.close();
	  stmt.close();
	  return false;
	}
	else{
	  System.out.println("user passwd pair exist");
	  rs.close();
	  stmt.close();
	  return true;
	}
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
  return false;// in this case some problem with conneciton
}


// returns true if a login exist. else returns false CHECKED
public synchronized boolean isLoginPresent(String login){

  System.out.println("login: "+ login);// test print

  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT userLogin FROM Users WHERE userLogin='"+login+"'";
	System.out.println(queryStatement);
	rs=stmt.executeQuery(queryStatement);
	int test=0;
	while (rs.next()){
	  test++;
	}
	System.out.println("test="+test);
	if(test<=0){
	  System.out.println("rs was null so returning false");
	  rs.close();
	  stmt.close();
	  return false;
	}
	else{
	  System.out.println("rs was not null so returning true");
	  rs.close();
	  stmt.close();
	  return true;
	}
  }catch(SQLException sqle){
	System.out.println("exception occuresd:"+sqle);
  }
  return false;// in this case some prob with connection
}

// returns true if a login exist. else returns false CHECKED
public synchronized boolean isEmailPresent(String email){

  System.out.println("email: "+ email);// test print

  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT email FROM Users WHERE email='"+email+"'";
	System.out.println(queryStatement);
	rs=stmt.executeQuery(queryStatement);
	int test=0;
	while (rs.next()){
	  test++;
	}
	System.out.println("test="+test);
	if(test<=0){
	  System.out.println("rs was null so returning false");
	  rs.close();
	  stmt.close();
	  return false;
	}
	else{
	  System.out.println("rs was not null so returning true");
	  rs.close();
	  stmt.close();
	  return true;
	}
  }catch(SQLException sqle){
	System.out.println("exception occuresd:"+sqle);
  }
  return false;// in this case some prob with connection
}

// returns true if a user is suspended  CHECKED
public synchronized boolean isSuspendedUser(String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT isSuspended FROM Users WHERE userLogin='"+login+"' and isSuspended='no'";
	System.out.println(queryStatement);
	rs=stmt.executeQuery(queryStatement);
	int count=0;
	while (rs.next()){
	  count++;
	}
	if (count==1){
	  System.out.println("done");
	  rs.close();
	  stmt.close();
	  return false;
	}
	else{
	  rs.close();
	  stmt.close();
	  return true;
	}

  }catch(SQLException sqle){
	System.out.println("Exception number 1 " + sqle);
  }
  return false;// in this case some prob with connection
}

//adding a user's information in the database CHECKED
public synchronized void addUserInfo(String login, String password, String firstName, String lastName, String email, String gender, String address, String city, String dateOfBirth){
  String updateStatement=null;
  try{
	Statement stmt=con.createStatement();
	updateStatement="INSERT INTO Users VALUES ('"+login+"','"+password+"','"+email+"','"+gender+"','"+dateOfBirth+"','"+firstName+"','"+lastName+"','"+address+"','"+city+"', 'no')";
	System.out.println(updateStatement);
	stmt.executeUpdate(updateStatement);
	stmt.close();
	System.out.println("user info added");
  }catch(SQLException sqle){
	System.out.println("Exception number 1: 1969 :" + sqle);
  }
}

// Updating a user's info to the database
public synchronized void updateUserInfo(String loginName, String oldPassword, String newPassword, String firstName, String lastName, String email, String gender, String address, String city){
  String updateStatement="";
  if (newPassword.equals("")){
	updateStatement="UPDATE users SET firstName='"+firstName+"', lastName='"+lastName+"', email='"+email+"', gender='"+gender+"', address='"+address+"', city='"+city+"' WHERE userLogin='"+loginName+"'"; 
  }
  else{
	updateStatement="UPDATE users SET passwd='"+newPassword+"',firstName='"+firstName+"', lastName='"+lastName+"', email='"+email+"', gender='"+gender+"', address='"+address+"', city='"+city+"' WHERE userLogin='"+loginName+"'";
  }
  try{    
	Statement stmt=con.createStatement();
	System.out.println("UPDATESTMT:"+updateStatement);
	stmt.executeUpdate(updateStatement);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// will return a ResultSet containing user's info
public synchronized void getUserInfo(PrintWriter out, String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT firstName, lastName, email, gender, address, city FROM Users WHERE userLogin='"+login+"'";
	rs=stmt.executeQuery(queryStatement);
	// will change user Profile
	UserPageGenerator.changeProfilePage(out, login, rs);
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// will return the details of a successful auctoin for a user
public synchronized void userQueryOne(PrintWriter out, String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT SAH.productId, P.productName, SAH.winnerLogin, SAH.winnerPrice, U.email, U.address FROM SuccAuctHistory SAH, Users U, Product P WHERE SAH.winnerLogin=U.userLogin AND P.productId=SAH.productId AND SAH.sellerLogin='"+login+"'";
	rs=stmt.executeQuery(queryStatement);
	UserPageGenerator.queryOnePage(out, rs, login);
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// will return the details of a unsuccessful auction of a user
public void userQueryTwo(PrintWriter out, String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT UAH.productId, P.productName, UAH.startDate, UAH.closingDate  FROM UnsuccAuctHistory UAH, Product P WHERE UAH.productId=P.productId AND UAH.sellerLogin='"+login+"'";
	rs=stmt.executeQuery(queryStatement);
	UserPageGenerator.queryTwoPage(out, rs);
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}


// will return details of current auctions of a user
// it will return two result sets,( actually we divide query three in twofunctions, part1, part2. one containing product with auctions placed on them and other containing products with no auction on them. NOte that both rs's will have different number of attributes. so in UserPageGen class you need to keep it in mind

public synchronized void userQueryThree(PrintWriter out, String login){
  String queryStatement=null;
  ResultSet rs1=null, rs2=null;
  try{
	Statement stmt1=con.createStatement();
	Statement stmt2=con.createStatement();
	queryStatement="SELECT CA.productId, P.productName, CA.startDate, CA.closingDate, CA.location, CB.bidderLogin, CB.bidValue FROM CurrentAuction CA, Product P, CurrentBid CB WHERE P.productId=CA.productId AND CA.auctionId=CB.auctionId AND CA.sellerLogin='"+login+"'";
	rs1=stmt1.executeQuery(queryStatement);
	queryStatement="SELECT CA.productId, P.productName, CA.startDate, CA.closingDate, CA.location FROM CurrentAuction CA, Product P WHERE P.productId=CA.productId AND CA.sellerLogin='"+login+"' AND CA.auctionId NOT IN (SELECT auctionId FROM currentBid)";
	rs2=stmt2.executeQuery(queryStatement);
	UserPageGenerator.queryThreePage(out, rs1, rs2);
	rs1.close();
	stmt1.close();
	rs2.close();
	stmt2.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// list all auctions for which user has placed bids
// (data will be taken from curent

public synchronized void userQueryFour(PrintWriter out,String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT CA.productId, P.productName, CA.location, CA.closingDate, CB.bidValue FROM Product P, CurrentAuction CA, CurrentBid Cb WHERE P.productId=CA.productId AND CB.auctionId=CA.auctionId AND CB.bidderLogin='"+login+"'";
	rs=stmt.executeQuery(queryStatement);
	UserPageGenerator.queryFourPage(out, rs);
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// will return the details of a auction won by a user
public synchronized void userQueryFive(PrintWriter out, String login){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT SAH.productId, P.productName, SAH.winnerPrice, SAH.sellerLogin, U.email, U.address FROM SuccAuctHistory SAH, Users U, Product P WHERE SAH.sellerLogin=U.userLogin AND P.productId=SAH.productId AND SAH.winnerLogin='"+login+"'";
	rs=stmt.executeQuery(queryStatement);
	UserPageGenerator.queryFivePage(out, rs, login);
	rs.close();
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}

// will update feedback table when a seller gives feedback on a winner
public synchronized void updateWinnerRatedAs(String productId, String sellerRatedWinnerAs){
  String updateStatement=null;
  try{
	Statement stmt=con.createStatement();
	updateStatement="UPDATE Feedback SET sellerRatedWinnerAs='"+sellerRatedWinnerAs+"' WHERE productId='"+productId+"'";
	stmt.executeUpdate(updateStatement);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception while updating winnerRatedAs feedback:" + sqle);
  }
}

// will update feedback table when a winner gives feedback on a seller
public synchronized void updateSellerRatedAs(String productId, String winnerRatedSellerAs){
  String updateStatement=null;
  try{
	Statement stmt=con.createStatement();
	updateStatement="UPDATE Feedback SET winnerRatedSellerAs='"+winnerRatedSellerAs+"' WHERE productId='"+productId+"'";
	stmt.executeUpdate(updateStatement);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception while updating sellerRatedAs feedback:" + sqle);
  }
}


// will insert into feedback table when a seller gives feedback on a winner
public synchronized void insertWinnerRatedAs(String productId, String sellerRatedWinnerAs, String winnerLogin, String sellerLogin){
  String updateStatement=null;
  try{
	Statement stmt=con.createStatement();
	updateStatement="INSERT INTO Feedback VALUES ('"+productId+"', '"+winnerLogin+"', '"+sellerLogin+"', null, '"+sellerRatedWinnerAs+"')";
	System.out.println("updateStatement="+updateStatement);
	stmt.executeUpdate(updateStatement);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception while updating insertWinnerRatedAs feedback:" + sqle);
  }
}


// will insert into feedback table when a winner gives feedback on a seller
public synchronized void insertSellerRatedAs(String productId, String winnerRatedSellerAs, String winnerLogin, String sellerLogin){
  String updateStatement=null;
  try{
	Statement stmt=con.createStatement();
	updateStatement="INSERT INTO Feedback VALUES ('"+productId+"', '"+winnerLogin+"', '"+sellerLogin+"', '"+winnerRatedSellerAs+"', null)";
	stmt.executeUpdate(updateStatement);
	stmt.close();
  }catch(SQLException sqle){
	System.out.println("Exception while updating insertSellerRatedAs feedback:" + sqle);
  }
}



// will return the rating given by winner to seller, if not rated then 'notRated' and if this auction has no entry in feedback table then 'noEntry' 
public synchronized String winnerRatedSellerAs(String productId){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT winnerRatedSellerAs FROM Feedback WHERE productId='"+productId+"'";
	rs=stmt.executeQuery(queryStatement);
	int count=0;
	while (rs.next()){
	  count++;
	}
	if (count==0){
	  rs.close();
	  stmt.close();
	  return "noEntry";
	}
	else if ((rs.getString(1)).equals("good") || rs.getString(1).equals("neutral") || rs.getString(1).equals("bad")){
	  String retString=rs.getString(1);
	  rs.close();
	  stmt.close();
	  return retString;
	}	    
	else{
	  rs.close();
	  stmt.close();
	  return "notRated";
	}	
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
	return "";
  }
}

// will return the rating given by seller to winner, if not rated then 'notRated' and if this auction has no entry in feedback table then 'noEntry' 
public synchronized String sellerRatedWinnerAs(String productId){
  String queryStatement=null;
  ResultSet rs=null;
  try{
	Statement stmt=con.createStatement();
	queryStatement="SELECT sellerRatedWinnerAs FROM Feedback WHERE productId='"+productId+"'";
	rs=stmt.executeQuery(queryStatement);
	int count=0;
	while (rs.next()){
	  count++;
	}
	if (count==0){
	  rs.close();
	  stmt.close();
	  return "noEntry";
	}
	else if ((rs.getString(1)).equals("good") || rs.getString(1).equals("neutral") || rs.getString(1).equals("bad")){
	  String retString=rs.getString(1);
	  rs.close();
	  stmt.close();
	  return retString;
	}
	else{
	  rs.close();
	  stmt.close();
	  return "notRated";
	}
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
	return "";
  }
}

// will return the rating details of a particular user
public synchronized void generalUserRating(String userLogin, PrintWriter out){
  System.out.println("yes1");
  String queryStatement=null;
  ResultSet rs1=null;
  ResultSet rs2=null;
  try{
	System.out.println("1928.queryEngine");
	Statement stmt1=con.createStatement();
	Statement stmt2=con.createStatement();
	System.out.println("userLogin="+userLogin);
	queryStatement="SELECT productId, sellerLogin, sellerRatedWinnerAs FROM Feedback WHERE winnerLogin='"+userLogin+"' and sellerRatedWinnerAs IS NOT NULL";
	rs1=stmt1.executeQuery(queryStatement);
	System.out.println("1928.queryEngine");
	queryStatement="SELECT productId, winnerLogin, winnerRatedSellerAs FROM Feedback WHERE sellerLogin='"+userLogin+"' and winnerRatedSellerAs IS NOT NULL";
	rs2=stmt2.executeQuery(queryStatement);
	System.out.println("1928.queryEngine");
	UserPageGenerator.generalUserRatingTable(out, rs1, rs2);
	rs1.close();
	stmt1.close();
	rs2.close();
	stmt2.close();
  }catch(SQLException sqle){
	System.out.println("Exception " + sqle);
  }
}
}





//    public void closeCon(){
///try{
//    con.close();
//}catch(SQLException sqle){
//      System.out.println("Exception " + sqle);
//}
//}

/* Have to do In BidServlet updating for session
   checking for session
   autobid part
   some transfer checks (means where to go and going or not)
   and (browsw sell myacc all option frame)
 */


/* Starting now autobid part 
   first convert into y and n
   then make query to insert into the table 

 */

//first doing first bid ok

/* Now work is on :::::
   Bid History : Idea is that make a new servlet where all extraneous
   info will be displayed.One more thing i think now is that doPost method is
   not of any use for the servlet but u have to give definition for it as it is
   necessary.
 */






















