// Fig. 16.20: LoginServlet.java
// Logs user into site and creates new account
package cartXML;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import org.w3c.dom.*;

public class LoginServlet extends HttpServlet {
   private Database database;

   public void init( ServletConfig config )
      throws ServletException
   {
      super.init( config );
      database = new Database( "jdbc:odbc:cart", "anonymous",
         "guest" );
      database.connect();
   }

   public void service( HttpServletRequest req,
      HttpServletResponse res )
      throws ServletException, IOException
   {
      HttpSession session = req.getSession( true );
      ShoppingCart test = ( ShoppingCart ) session.getAttribute(
         "cart" );
      ServletContext sc = getServletConfig().getServletContext();

      if ( test != null ) { // do not allow a user to log in twice
         sc.getRequestDispatcher(
            "/servlet/cartXML.GetTechnologyServlet" )
            .forward( req, res );
         return;
      }

      ShoppingCart cart = new ShoppingCart();
      String name = req.getParameter( "param1" );
      String password = req.getParameter( "param2" );
      String action = req.getParameter( "action" );
      XMLCreator xmlCreator = new XMLCreator();
      Node loginNode = xmlCreator.initialize( "login" );
      Processor processor = new Processor();
      res.setContentType( "text/vnd.wap.wml" );
      PrintWriter output = res.getWriter();

      if ( action.equals( "login" ) ) {

         // send to servlet that retrieves cart
         if( isValid( name, password ) ) {
            cart.setUsername( name );
            session.setAttribute( "cart", cart );
            sc.getRequestDispatcher(
               "/servlet/cartXML.GetShoppingCartServlet" )
               .forward( req, res );
         }
         else {
            Node messageNode = xmlCreator.addChild( loginNode,
               "message" );

            xmlCreator.addTextNode( messageNode,
               "You entered an invalid password" );
            processor.process( xmlCreator.getDocument(),
               "C:/jakarta-tomcat/webapps/chapter16/login.xsl",
               output );
         }
      }
      else {

         if ( !password.equals( req.getParameter( "param3" ) ) )
         {
            xmlCreator.addTextNode( xmlCreator.addChild(
               loginNode, "message" ), "You entered two "
               + "different passwords. Please try again." );
            processor.process( xmlCreator.getDocument(),
               "C:/jakarta-tomcat/webapps/chapter16/newuser.xsl",
               output );
         }
         else {
            boolean created = createUser( name, password );

            if ( created ) {
               cart.setUsername( name );
               xmlCreator.addTextNode( xmlCreator.addChild(
                  loginNode, "message" ), "Account created \n "
                  + "username: " + name + "\n password: "
                  + password );

               session.setAttribute( "cart", cart );
               processor.process( xmlCreator.getDocument(),
                  "C:/jakarta-tomcat/webapps/chapter16/welcome.xsl",
                  output );
            }
            else {
               xmlCreator.addTextNode( xmlCreator.addChild(
                  loginNode, "message" ), "That username already "
                  + "exists. Please try again." );
               processor.process( xmlCreator.getDocument(),
                  "C:/jakarta-tomcat/webapps/chapter16/newuser.xsl",
                  output );
            }
         }
      }
   }

   public boolean isValid( String user, String passwd )
   {
      try {
         String query = "SELECT username FROM Users WHERE "
            + "username = '" + user +  "' and password = '"
            + passwd + "'";
          ResultSet rs = database.get( query );

         if ( rs.next() )
            return true;
      }
      catch ( SQLException sqlex ) {
         sqlex.printStackTrace();
      }

      return false;
   }

   private boolean found( String user )
   {
      try
      {
         String query = "SELECT username FROM Users WHERE "
            + "username= '" + user + "'";
         ResultSet rs = database.get( query );

         if ( rs.next() )
            return true;
      }
      catch ( SQLException sqlex ) {
         sqlex.printStackTrace();
      }

      return false;
   }

   public boolean createUser( String user, String passwd )
   {
      boolean canInsert = found( user );

      if ( !canInsert ) { // if name does not already exist
         String query = "INSERT INTO Users ( username, "
            + "password ) VALUES ('" + user + "','"
            + passwd + "' )";
         return database.update( query );
      }

      return false;
   }

   public void destroy()
   { database.shutDown(); }
}
/*
 **************************************************************************
 * (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 **************************************************************************
*/
