SDServlet.SDSessionServlet (Java2HTML)
/**
* @author : Umesh Kulkarni
* @version 1.0
*
* Name of the Application         :   SDSessionServlet.java
* Development Environment         :   JDeveloper 2.0
*
* Creation/ Modification History  :
* Jagriti           10-Sep-2001        Modified  to include JDBC2.0 features.
*                                      Included DataSource usage using JNDI.
*
*
* Overview of the application     :
*   This Servlet (SDSessionServlet) handles the session management &
*   method invocation of the Survey Definition Component.
*   The Survey Definition Component of the Survey Application, allows the user
*   to define his/her own survey, modify the Survey etc.
*
*   The service() method of this Servlet accepts the HTTP Requests from the user.
*   Depending on the Request Type, appropriate methods are invoked and the requests
*   are handled.
*
*   Brief correspondence between the Request Type and the related Functionality
*   is given below.
*
*   Request_Type                Related Functionality
*   ----------------------------------------------------------------------------
*    1) MAIN               - Show the Login Page & ask for User Name, password
*                          - If proper Login info provided then Show the Survey
*                             Application Main Page
*
*    2) SURVEY_MAIN        - Show the Survey Main Page
*    3) QUESTION_MAIN      - Show the Question Main Page
*    4) CHOICEGROUP_MAIN   - Show the Choice Group Main Page
*    5) WIZARD             - Then invoke the proper wizard processing method for Surveys
*    6) EDIT               - Show the Edit Page depending on which Survey Element
*                          - is being asked for (Survey, Question, Choice Group or choices)
*
*    7) SAVE               - Invoke a method to save the changes
*    8) DELETE             - Invoke a method to delete the changes
*
*
*
**/

package SDServlet;

import java.io.*;
import java.util.*;

// Packages for Servlets
import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*; // Package for JDBC Classes
import oracle.jdbc.driver.*; // Package for Oracle JDBC Driver
import javax.sql.*; // JDBC 2.0 core APIs
import oracle.jdbc.pool.OracleDataSource;
import javax.naming.*; // Package for JNDI

import SRServlet.*;


public class SDSessionServlet extends HttpServlet {

  public static String s_servletPath = null;

  //Define global variables
  protected ServletContext m_context; // Servlet Context
  protected Hashtable m_sessionCache; // HashTable used to store different Session Information
  protected Authorization m_myauth; // Class which implements Authorization Procedure for users


  String m_SURVEY_DATASOURCE = "jdbc/Loneifso817DS";
  DataSource m_dataSource = null;


  /**
  * This method is called by the Servlet at the initialization.
  * A Session Cache is initialized. Also the authorization class is instantiated.
  **/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    m_context = config.getServletContext(); // Get the Servlet Context
    // Initialize the Session Cache. The Session Cache is used to keep track of
    // all the sessions started by the user.
    m_sessionCache = new Hashtable(10);
    m_myauth = new Authorization(); // Instantiate the authorization class
  }

  /**
  * Method to service the different HTTP requests. The method checks for request type.
  * Depending on the request type, this method invokes appropriate methods.
  **/
  public void service (HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

    // Initialize the servlet path setting
    if (this.s_servletPath == null) {
      String l_servletPath =  request.getRequestURI();
      StringTokenizer st = new StringTokenizer(l_servletPath,"?");
      s_servletPath = st.nextToken();
    }

    // Get the session associated with the request. If none exists, session is set to null.
    SDSession session = findValidSession (request);

    // Determine the REQUEST_TYPE i.e what is being asked for by looking
    // at the REQUEST_TYPE field first. If REQUEST_TYPE parameter is set,
    // then proper method is invoked.

    String requestType = request.getParameter ("REQUEST_TYPE");
    if (session != null && requestType == null) {
        endSession (session);
      // Display Log Out Page
      response.setContentType("text/html");
      PrintWriter out = new PrintWriter (response.getOutputStream());

      // Setting the database connection
      Connection l_connection;
      try {
       InitialContext ic = new InitialContext();
       m_dataSource = (DataSource)ic.lookup(m_SURVEY_DATASOURCE);
       l_connection  = m_dataSource.getConnection();

       // sets the auto-commit property for the connection to be false. By default
       // the connections always auto-commit.
       l_connection.setAutoCommit(false);
       out.println(m_myauth.getLoginPage(l_connection, true));
       l_connection.close();
      } catch (SQLException se) {
        System.out.println("SQL Error while connecting to the database : "+
                            se.toString());
      } catch (NamingException ne) {
        System.out.println("Naming exception Error while connecting to the database : "+
                            ne.toString());
      } catch (Exception ne) {
        System.out.println("Other Error while connecting to the database : "+
                            ne.toString());
      }


      out.close();
    } else if (session == null ) {
      if (requestType == null || (requestType != null && !requestType.equals("MAIN"))){
        // Session has not been created. Hence Show the Login Page.
        // Once login has been done, Session is created using the User Name as key.
        response.setContentType("text/html");
        PrintWriter out = new PrintWriter (response.getOutputStream());
        out.println("<html><body>");
        out.println("<head><title>Login </title></head>");

        // Setting the database connection
        Connection l_connection;
        try {
             InitialContext ic = new InitialContext();
             m_dataSource = (DataSource)ic.lookup(m_SURVEY_DATASOURCE);
             l_connection  = m_dataSource.getConnection();
             out.println(m_myauth.getLoginPage(l_connection, true));
            l_connection.close();
        } catch (SQLException se) {
        System.out.println("SQL Error while connecting to the database : "+
                            se.toString());
      } catch (NamingException ne) {
        System.out.println("Naming exception Error while connecting to the database : "+
                            ne.toString());
      } catch (Exception ne) {
        System.out.println("Other Error while connecting to the database : "+
                            ne.toString());

      }

        out.close();
      } else
        DoAction (requestType, session, request, response);
    } else
      DoAction (requestType, session, request, response);
  }

  /**
  * This Method Checks whether already there is any valid Session associated with the
  * request. If any valid session is present in the Session Cache then it is returned
  * back. If no valid session is present in the Session Cache then 'null' session
  * is returned back.
  **/
  private SDSession findValidSession (HttpServletRequest request) {
   // Get the Cookies associated with the request
   Cookie c[] = request.getCookies();
   SDSession session = null;
   for (int i=0;(c!= null) && (i<c.length);i++) {
     if (c[i].getName().equals("SDSessionServlet")) {
       String userID = String.valueOf (c[i].getValue());
       session = (SDSession) m_sessionCache.get(userID);
       break;
     }
   }

   return session;
  }

 /**
 * This Method checks for the action requested & invokes the appropriate methods.
 *
 **/
 private void DoAction (String action, SDSession session, HttpServletRequest request,
 HttpServletResponse response) throws IOException, ServletException{
   response.setHeader ("Pragma", "no-cache");
   // If Action is Main, then show the Main Page

   boolean l_repeat = false;
   if (action.equals("TOGGLE_USER")) {
     String state = request.getParameter("USER_STATE");
     if (state != null)
       session.setUserFlag(!state.equals("CURRENTUSER"));
     l_repeat = true;
     action = session.getLastAction();
   }

   if (action.equals("MAIN")) {
     try {
      // If Session Has not been created then create a new Session.
      if (session == null) {
        String userId = request.getParameter("USERID"); // Get the User Id
        String userType = request.getParameter("USER_TYPE"); // Get the Pass Word
        // Create a New Session
        session = startNewSession(userId,userType,response);

      }
      session.setLastAction("MAIN");
      // Display the Survey Application Main Page
      SDUtil.returnMainPage(response,session);
     } catch (SQLException ex) {
       response.setContentType("text/html");
       response.getOutputStream().println("<HTML><BODY>Error creating session");
       response.getOutputStream().println("<P>"+ex.toString());
       response.getOutputStream().println("</HTML></BODY>");
     }
   }


   // If Action is "SURVEY_MAIN" then show the Survey Main Page
     if ( action.equals ("SURVEY_MAIN") ) {
     String nullMessage = null;
     session.setLastAction("SURVEY_MAIN");
     SDUtil.returnSurveysMain(nullMessage,response,session);
     }

   // If Action is "QUESTION_MAIN" then show the Question Main Page
   if ( action.equals ("QUESTION_MAIN") ) {
     String nullMessage = null;
     session.setLastAction("QUESTION_MAIN");
     SDUtil.returnQuestionMain(nullMessage,response,session);
     }

   // If Action is "CHOICEGROUP_MAIN" then show the Choice Group Main Page
   if (action.equals("CHOICEGROUP_MAIN")) {
     String nullMessage = null;
     session.setLastAction("CHOICEGROUP_MAIN");
     SDUtil.returnChoiceGroupMain(nullMessage,response,session);
   }


   // If Action is "WIZARD" then start wizard processing
   if (action.equals("WIZARD")) {
     session.setLastAction("SURVEY_MAIN");
     // Get which Element (e.g Survey )
     String whichElement = request.getParameter("ELEMENT");
     // Get which Step Number
     String stepNo = request.getParameter("STEP");
     if (stepNo.startsWith("NEW")) { // For New Steps
       // Note that Wizard Processing is valid only for Survey Elements. The Elelements
       // Question, Choice Groups and Choices do not have wizard processing.
       if (whichElement.equals("SURVEY")) {
          // Instantiate a new Survey
          Survey s = new Survey();
          // Push the Survey onto the stack
          session.pushElement(s);
          s.wizardProcessing(1,session,request,response);
       }
     } else {
        if (stepNo.startsWith("FINISH")) { // For Step which is FINISH
           SurveyElement s = (SurveyElement) session.popElement();
           s.wizardFinish(session, request, response,false);
           // Delete Survey from Stack
           session.deleteFromStack();
        } else { // For Steps which are neither NEW nor FINISh
           SurveyElement s = (SurveyElement) session.popElement();
           s.wizardProcessing(Integer.parseInt(stepNo),session,request,response);
        }
     }
   }

   if (action.equals("CREATE_QSN_FOR_SURVEY")) {
     // If Element ID is provided then using the ID, instantiate the
     // Question Class.
     Question q = new Question();
     // In the Session, register the information that this question class
     // is being edited now.
     session.setSecondEditedObject(q);
     q.setQsnForSurvey();
     // Invoke the method which returns the Question Edit Page in HTML form.
     q.editElementHTML(session,request,response);
   }


   // If Action is "EDITING" of existing elements
   if (action.equals("EDIT")) {
     // Get which Element to Edit
     String whichElement = request.getParameter("ELEMENT");

     // Get ID of the Element
     //String ID = request.getParameter("ID");

     // When Element is Survey, invoke the method to Edit Survey
     if (whichElement.equals("SURVEY")) {
        session.setLastAction("SURVEY_MAIN");
        int elementID = -1;
        // Check whether Element ID is provided alongwith the request.
        if (request.getParameter("ELEMENTID") != null
             && !request.getParameter("ELEMENTID").equals("NEW"))
            // Get the Element ID
            elementID = Integer.parseInt(request.getParameter("ELEMENTID"));
          Survey s = null;
          //if (elementID == -1)
            // If Element Id is not provided then instantiate a new Survey Class
            // with Survey ID set as "".
           // s = new Survey();
          //else
            // If Element ID is provided then using the ID, instantiate the
            // Survey Class.
            s = new Survey(elementID);
          // In the Session, register the information that this Survey class is
          // being edited now.
          session.setEditedObject(s);
          // Invoke the method which returns the Survey Edit Page in HTML form.
          s.editElementHTML(session,request,response);
     }

     // When Element is Question, invoke the method to Edit Question
     if (whichElement.equals("QUESTION")) {
        session.setLastAction("QUESTION_MAIN");
        int elementID = -1;
        // Check whether Element ID is provided alongwith the request.
        if (request.getParameter("ELEMENTID") != null
               && !request.getParameter("ELEMENTID").equals("NEW"))
          // Get the Element ID
          elementID = Integer.parseInt(request.getParameter("ELEMENTID"));
          Question q = null;
          if (elementID == -1)
            // If Element Id is not provided then instantiate a new Question Class
            // with Question ID set as "".
            q = new Question();
          else
            // If Element ID is provided then using the ID, instantiate the
            // Question Class.
            q = new Question(elementID);
          // In the Session, register the information that this question class
          // is being edited now.
          session.setEditedObject(q);
          // Invoke the method which returns the Question Edit Page in HTML form.
          q.editElementHTML(session,request,response);
     }

     // When Element is Choice, invoke the method to Edit Choice
     if (whichElement.equals("CHOICE")) {
         Choices newCh = new Choices(); // Instantiate Choices class

         // In the Session, register the information that this Choices class
         // is now currently being edited.
         session.setEditedObject(newCh);

         // Invoke the method which returns the Choices Edit Page in HTML form.
         newCh.editElementHTML(session,request,response);
     }

     // When Element is Choice Group, invoke the method to Edit Choice Group
     if (whichElement.equals("CHOICEGROUP")) {
        session.setLastAction("CHOICEGROUP_MAIN");
        int elementID = -1;
        // Check whether Element ID is provided alongwith the request.
        if (request.getParameter("ELEMENTID") != null
               && !request.getParameter("ELEMENTID").equals("NEW"))
          // Get the Element ID
          elementID = Integer.parseInt(request.getParameter("ELEMENTID"));
          ChoiceGroup cg = null;
          // If Element Id is not provided then instantiate a new Choice Group Class
          // with ChoiceGroup ID set as "".
          if (elementID == -1)
              cg = new ChoiceGroup();
          else
              // If Element ID is provided then using the ID, instantiate the
              // Choice Group Class.
              cg = new ChoiceGroup(elementID);
         // In the Session, register the information that this Choice Group class
         // is now currently being edited.
         session.setEditedObject(cg);

         // Invoke the method which returns the Choice Groups Edit Page in HTML form.
         cg.editElementHTML(session,request,response);
     }
   }

   // When the action is save, invoke the method to save the changes
   if (action.equals("SAVE")) {
      //  String elementName = session.getEditedObject().getClass().getName();
      // Get the Survey Element which is currently being edited.
      SurveyElementEdit s = (SurveyElementEdit) session.getEditedObject();
      // Invoke save changes method on the currently edited object
      s.saveEditedChanges(session, request, response);
   }

   // When the action is save, invoke the method to save the changes
   if (action.equals("SAVE_QSN_FOR_SURVEY")) {
      //  String elementName = session.getEditedObject().getClass().getName();
      // Get the Survey Element which is currently being edited.
      SurveyElementEdit s = (SurveyElementEdit) session.getSecondEditedObject();
      // Invoke save changes method on the currently edited object
      s.saveEditedChanges(session, request, response);
   }

   // When action is delete, invoke the method to delete the changes
   if (action.equals("DELETE")) {
      // String elementName = session.getEditedObject().getClass().getName();
      // Get the Survey Element which is currently being edited.
      SurveyElementEdit s = (SurveyElementEdit) session.getEditedObject();
      // Invoke delete changes method on the currently edited object
      s.deleteElement(session, request, response);
   }

   // When action is modify survey contents, invoke the method to modify the survey
   // contents
   if (action.equals("MODIFY_SURVEY_CONTENTS")) {
        String elementName = session.getEditedObject().getClass().getName();
        Survey s = (Survey) session.getEditedObject();
        s.maintainQuestionsPage(session, request, response);
   }

   // When action is save survey contents, invoke the method to save the survey
   // contents
   if (action.equals("SAVE_SURVEY_CONENTS")) {
        String elementName = session.getEditedObject().getClass().getName();
        Survey s = (Survey) session.getEditedObject();
        s.saveSurveyContents(session, request, response);
   }

   if (action.equals("PREVIEW_SURVEY")) {
     Survey s = (Survey) session.popElement();

     try {
       session.getConnection().setAutoCommit(false);
       s.wizardFinish(session, request, response,true);
       StringBuffer l_buffer =
           SRSessionServlet.getSurveyHTML(session.getConnection(),Long.parseLong(s.m_surveyID));
       response.setContentType("text/html");
       response.getOutputStream().println(new String(l_buffer));
       response.getOutputStream().println(SRSessionServlet.ValidationJavaScript());
       session.getConnection().rollback();
       session.getConnection().setAutoCommit(true);
     } catch (SQLException ex) {
       response.setContentType("text/ascii");
       response.getOutputStream().println("Error in generating Survey form for preview "+ex.toString());
     }
   }

   // If Action is "SURVEY_MAIN" then show the Survey Main Page
     if ( action.equals ("PREGENERATION_MAIN") ) {
     String nullMessage = null;
     session.setLastAction("SURVEY_MAIN");
     PreGeneration.preGenerationMain(request, response, session);
     }

   // If Action is "SURVEY_MAIN" then show the Survey Main Page
     if ( action.equals ("PREGENERATE_CLOB") ) {
     String nullMessage = null;
     session.setLastAction("SURVEY_MAIN");
     PreGeneration.generateCLOB(request, response, session);
     }

   // If Action is "SURVEY_MAIN" then show the Survey Main Page
     if ( action.equals ("REGENERATE_CLOB") ) {
     String nullMessage = null;
     session.setLastAction("SURVEY_MAIN");
     PreGeneration.generateCLOB(request, response, session);
     }

   // If Action is "SURVEY_MAIN" then show the Survey Main Page
     if ( action.equals ("TOGGLE_CLOB") ) {
     String nullMessage = null;
     session.setLastAction("SURVEY_MAIN");
     PreGeneration.toggleUsage(request, response, session);
     }

   // When Logging out, remove session from session cache ( if one exists) .
     // Send the Log Out HTML page back to the client.
     else if ( action.equals ("Logout") ) {
      // If Session is not null then remove the session entry from the Session Cache.
      if ( session != null ) {
                endSession (session);
            }
      // Display Log Out Page
      response.setContentType("text/html");
      PrintWriter out = new PrintWriter (response.getOutputStream());

      // Setting the database connection
      Connection l_connection;
      try {
          InitialContext ic = new InitialContext();
          m_dataSource = (DataSource)ic.lookup(m_SURVEY_DATASOURCE);
         l_connection  = m_dataSource.getConnection();
         out.println(m_myauth.getLoginPage(l_connection, true));
        l_connection.close();
        out.close();
      } catch (SQLException se) {
        System.out.println("SQL Error while connecting to the database : "+
                            se.toString());
      } catch (NamingException ne) {
        System.out.println("Naming exception Error while connecting to the database : "+
                            ne.toString());
      } catch (Exception ne) {
        System.out.println("Other Error while connecting to the database : "+
                            ne.toString());

    }
  }
  }

  /**
  * This method Starts a new Session. The Class instance m_myauth provides a
  * method called 'isAuthorized' which helps in authentication of users.
  **/
  protected SDSession startNewSession (String userId, String userType, HttpServletResponse response )
  throws IOException, SQLException  {
    SDSession session = null;
    Connection dbConnection = null;

    // Check if the user is a authorized to use this application.
    // Get a new database connection for this session
    try {
         InitialContext ic = new InitialContext();
         m_dataSource = (DataSource)ic.lookup(m_SURVEY_DATASOURCE);
         dbConnection  = m_dataSource.getConnection();

       // sets the auto-commit property for the connection to be false. By default
       // the connections always auto-commit.
       dbConnection.setAutoCommit(false);
      } catch (SQLException se) {
        System.out.println("SQL Error while connecting to the database : "+
                            se.toString());
      } catch (NamingException ne) {
        System.out.println("Naming exception Error while connecting to the database : "+
                            ne.toString());
      } catch (Exception ne) {
        System.out.println("Other Error while connecting to the database : "+
                            ne.toString());
    }

    if (userType.equals("NEWUSER")) {
      Statement l_stmt = dbConnection.createStatement();
      l_stmt.execute("insert into survey_users values ('"+userId+"', SYSDATE)");
      l_stmt.close();
    }

    // Create a new session.
        session = new SDSession (userId, dbConnection);

        // Create a client Cookie. Cookies are a mechanism that a servlet can use
    // to have clients hold a small amount of state-information associated with
    // the user.
        Cookie c = new Cookie("SDSessionServlet", String.valueOf (session.getUserId()));

    // Put the Session into the Session Cache
        m_sessionCache.put (c.getValue(), session);
        c.setPath ("/");

    response.addCookie(c); // Add the cookie to the response

    return session;
  }

  /**
  * Method invoked to terminate a Session. It removes the session from the Session Cache.
  */
  protected void endSession (SDSession session) {
    try {
      session.getConnection().close();
        synchronized (m_sessionCache) {
            m_sessionCache.remove (session.getUserId());
        }
    }  catch (SQLException ex) {
    }
  }

  /**
  * Method to get the Servlet Information.
  */
  public String getServletInfo() {
    return "SDSessionServlet Information";
  }

}
E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy