We help IT Professionals succeed at work.

Nullpointer problem

xoxomos
xoxomos asked
on
Medium Priority
332 Views
Last Modified: 2008-02-01
I'm trying to run some servlets, but not getting past the initDb()
It seems to get to this code :
dbConn = (CSUHOracleConnectionBroker)getServletContext().getAttribute("CSUHOracleConnectionBroker");
Then:
Loading CSUHHome...Initializing CSUHSchedulerHttpServlet...entered protected void initDb throws ServletException
Error initializing CSUHSchedulerHttpServlet: java.lang.NullPointerException
CSUHHome loaded.
How do i get rid of that exception?


import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.servlet.connmgr.*;

/*
 *  Basic servlet that all the other scheduler servlets inherit from.
 */

public class CSUHSchedulerHttpServlet extends HttpServlet implements CSUHRegistrationConstants
{
   //the default directory for WebSphere is the same directory the Netscape obj.conf file is in
   //for NT that directory is C:\Netscape\Suitespot\https-ess-0097\config
   //for Solaris that directory is /usr/netscape/suitespot/https-secure_anthony/config
   
   //these 4 variables require a new instance for each class that extends them so they are *not* static
   protected long[] pageServes = null;         // number of times this page has been served
   protected long[] pageTime = null;           // total amount of calender time the doGet code has spent executing
   protected java.util.Date loadTime = null;   // when the servlet was last loaded on the web server

   //these variables are shared by any class that extends them, there will not be a new instance
   protected static boolean trace = false;     // turns tracing on/off
   
   protected static String regularFont = null; //font to use for regular display
   protected static String grayFont = null;    //font to use for grayed out display
   protected static String buttonWidth = null; //width in pixels for any HTML buttons on the page (IE ignores this tag)
   protected static String buttonFont = null;  //font for the form buttons

   protected static String url = null;                //database connection url
   protected static IBMConnMgr connMgr = null;        //db connection manager
   protected static IBMConnSpec connSpec = null;      //db connection specification
   protected static CSUHOracleConnectionBroker dbConn = null; //returns the connMgr,connSpec and other objects related to the db

   protected static String CONFIG_FILE = null; //the text file "scheduler.properties" contains basic startup info for the servlets
   protected static String defaultDir = null;  //the "home" directory for WebSphere, on NT this is C:\WebSphere\AppServer on Solaris its /opt/IBMWebAS

   protected static final int SUBJECTS_PER_ROW = 10;     //how many subjects to display in one row              
   protected static final String LECTURE_TYPES = "'LEC', 'RCT', 'SEM'"; //lecture types...used in ratings

   protected static int MAX_NUMBER_TO_CONSIDER  = 5000; //max number of schedules to consider before stopping
   protected static int MAX_NUMBER_TO_CALCULATE = 500;  //max number of schedules to successfully create
   protected static int MAX_NUMBER_TO_DISPLAY   = 500;  //max number of ratings to display on the "ratings" page

   protected static final int NUMBER_OF_ELEMENTS_NOT_TO_INCLUDE = 1; //used in the ratings servlet
   protected static final int NUMBER_OF_DAYS_IN_ONE_WEEK = 7;
   protected static final int NUMBER_OF_DIGITS_IN_A_CALLNUMBER = 5;
   protected static final int NUMBER_OF_HALF_HOUR_BLOCKS_BETWEEN_1200AM_AND_0700AM = 14;

   protected static Boolean initialized = new Boolean(false);   //only initialize the static variables once.

   protected static boolean ipFiltering = false;

   protected static String validIP[] = { "129.65.210","129.65.8","129.65.7","129.65.82","207.62.152","207.62.153",
          "207.62.154","207.62.155","207.62.156","207.62.157","207.62.158","207.62.159","207.62.160",
          "207.62.161","207.62.162","207.62.163","207.62.164","207.62.165","207.62.166","207.62.167","129.65.145" };

   protected static Properties schedProperties = null;
 

 
   public void init(ServletConfig config) throws ServletException
   {
      super.init(config);
      try
      {
         synchronized(initialized)
         {
            if (!initialized.booleanValue())
            {
           //    System.out.print("Initializing SchedulerHttpServlet...");
               System.out.print("Initializing CSUHSchedulerHttpServlet...");


               initDb();
               System.out.println("...past initDb()...");
               regularFont = "<font face+Arial size=1>";
               grayFont    = "<font face=Arial size=1 color=slategray>";
               buttonWidth = "85";
               buttonFont  = "<font face=\"Courier New\" size=2>";
      //       defaultDir  = "/opt/WebSphere/AppServer";
      //       defaultDir  = "/opt/WebSphere/AppServer";
      //         defaultDir  = "C:\\Program Files\\IBM\\VisualAge for Java\\ide\\project_resources\\IBM WebSphere Test Environment";
            System.out.println("...past initDbIII()...");
               trace = false;
               ipFiltering = false;
               MAX_NUMBER_TO_CONSIDER = 5000;
               MAX_NUMBER_TO_CALCULATE = 500;
               MAX_NUMBER_TO_DISPLAY = 500;
             
         //    CONFIG_FILE = defaultDir + "/hosts/default_host/webreg/servlets/scheduler.properties";
         //    CONFIG_FILE = defaultDir + "/hosts/default_host/webreg/servlets/csuh.properties";
         //    CONFIG_FILE = defaultDir + "\\hosts\\default_host\\webreg\\servlets\\csuh.properties";  
               CONFIG_FILE = "C:\\csuh.properties";  
               System.out.println( "CONFIG_FILE IS  ");
               System.out.println("...past initDbIIIIIIIIIII()...");
               FileInputStream propertyFile = new FileInputStream(CONFIG_FILE);
               schedProperties = new Properties();
               schedProperties.load(propertyFile);
               
               initialized = new Boolean(true);
               System.out.println("SchedulerHttpServlet initialized.");
               System.out.println("Using CONFIG_FILE " + CONFIG_FILE);
            }
         }

         pageServes = new long[1];
         pageServes[0] = 0;
         loadTime = new java.util.Date();
         pageTime = new long[1];
         pageTime[0] = 0;
      }
      catch(Exception e)
      {
      //   System.out.println("Error initializing SchedulerHttpServlet: " + e);
          System.out.println("Error initializing CSUHSchedulerHttpServlet: " + e);
      }
   }
 
   public void destroy()
   {
      super.destroy();
   }

 
   /*
    * Processes the current row of a ResultSet and returns the results as an array of strings.
    */

   public String[] getRsStringData(ResultSet rs) throws SQLException
   {
      int index = rs.getMetaData().getColumnCount();
      String[] values = new String[index];
      for (int i=0;i<index;i++) values[i] = rs.getString(i+1); //arrays are zero based, ResultSet's are one based
      return values;
   }


   /*
    * HTML hyperlink that displays a message in the status bar area while the mouse is over the link.
    * <p>Note: The display text cannot contain single quotes.
    */
   public String ahrefWithStatus (String dest, String show, String display)
   {
      return ("<a href=\"" + dest + "\" onMouseOver=\"self.status='" + display + "'; return true;\">" + show + "</a>");
   }


   public String ahref (String dest, String show)
   {
      return ("<a href=\"" + dest + "\">" + show + "</a>");
   }


   private static String right(String s,int length)
   {
      return s.substring(s.length() - length);
   }


   private static String left(String s,int length)
   {
      return s.substring(0,length);
   }


   protected void initDb() throws ServletException
   {
      System.out.println("entered protected void initDb throws ServletException");

      dbConn = (CSUHOracleConnectionBroker)getServletContext().getAttribute("CSUHOracleConnectionBroker");

      connSpec = dbConn.getConnSpec();
      connMgr = dbConn.getConnMgr();
      url = dbConn.getUrl();
     
   }


   protected boolean sessionExists(HttpServletRequest request)
   {
      //System.out.println("CSUHSchedulerHttpServlet: sessionExists() called");

    if (request.getSession(false) != null)
    {
      HttpSession session = request.getSession(false);
      /* System.out.println("\nCSUHSchedulerHttpServlet sessionExists()  *************************************");
      System.out.println("HttpSession ID = " + session.getId());
      System.out.println("HttpSession is new = " + session.isNew());

      String[] getsessionvalues = session.getValueNames();
      if (getsessionvalues != null)
      {
         for (int i = 0; i < getsessionvalues.length; i++)
         {
            System.out.print("name[" + i + "] = " + getsessionvalues[i] + ", ");
            System.out.println("value[" + i + "] = " + session.getValue(getsessionvalues[i])); */

            /*if (getsessionvalues[i].startsWith("CSUHStudent"))
            {
               studInfo = getStudentFromSession(session);
               System.out.println("CSUHAddServlet: CSUHStudent* = " + studInfo.toString());
            }*/

            /* Object svalue = session.getValue(getsessionvalues[i]);
            if (svalue instanceof String[])
            {
                        String[] sArray = (String[])svalue;
                        for (int j=0; j<sArray.length; j++)
                                System.out.println("detail value: " + sArray[j]);
                        System.out.print("\n");
            }
            else if (svalue instanceof CSUHStudent)
            {
                CSUHStudent studInfo = (CSUHStudent)svalue;
                System.out.println("detail value ssnum: " + studInfo.getSSNum());
                System.out.println("detail value pin: " + studInfo.getPIN());
                System.out.println("detail value priority count: " + studInfo.getPriorityCount());
                System.out.println("detail value survey answer: " + studInfo.getSurveyAnswer());
                System.out.println("detail value priority status: " + studInfo.getPriorityStatus());
                System.out.println("detail value survey status: " + studInfo.getSurveyStatus());
                System.out.println("detail value total units: " + studInfo.getTotalUnits());
                System.out.println("detail value: class schedule can be iterated here");
                studInfo.showClasses();
                System.out.println("detail value schedule size: " + studInfo.scheduleSize());
                System.out.println("detail value schedule changed?: " + studInfo.getScheduleChangedDontSet());
                System.out.print("\n");
            }
            else
            {
                System.out.println("detail value: not a String[] or CSUHStudent");
                System.out.print("\n");
            }  //end if
         }  //end for
      } // end if
      System.out.println("\nCSUHSchedulerHttpServlet sessionExists()  *************************************"); */
    }


      return (request.getSession(false) != null);
   }


   protected String[] getValuesFromHash(Hashtable dataHash, String key)
   {
      //System.out.println("CSUHSchedulerHttpServlet: getValuesFromHash() called");
      return (String[])dataHash.get(key);
   }

 
  protected CSUHStudent getStudentFromSession(HttpSession session) {
    //System.out.println("CSUHSchedulerHttpServlet: getStudentFromSession() called");
    if (session != null) {
    //System.out.println("getStudentFromSession() in CSUHRegistrationHttpServlet returns = session is NOT null.");
      return ((CSUHStudent)session.getValue(STUD_INFO));
    } else {
    //System.out.println("getStudentFromSession() in CSUHRegistrationHttpServlet returns = session null.");
      return null;
    }
  }

   protected boolean theseElementsExist(Hashtable dataHash, String[] elements)
   {
      if (dataHash == null) return false;  
      for (int i=0;i<elements.length;i++)
         if ((String[])dataHash.get(elements[i]) == null) return false;
   return true;
   }


   protected Hashtable getDataHash(HttpServletRequest request)
   {
      // System.out.println("\n****************************************************");
      //System.out.println("CSUHSchedulerHttpServlet: getDataHash() called");
      Hashtable dataHash = null;
      try
      {
         dataHash = HttpUtils.parsePostData(Integer.parseInt(request.getHeader("Content-length")), request.getInputStream());
      }
      catch(Exception e) { }
     
      if (dataHash == null)
      {
         //try {
         //   dataHash = HttpUtils.parseQueryString(request.getQueryString(), HttpUtils.getLanguage(request));}
   
         try
         {
            dataHash = HttpUtils.parseQueryString(request.getQueryString());
         }
         catch(Exception e) { }
      }

      if (dataHash != null)
      {

         Enumeration keyEnum = dataHash.keys();
         Enumeration elemEnum = dataHash.elements();
         int hashSize = dataHash.size();
         //System.out.println("CSUHSchedulerHttpServlet: dataHash size is: " + hashSize);

         /* commented out 11202000 while (keyEnum.hasMoreElements())
         {
                String key = (String)keyEnum.nextElement();
                System.out.print("key: " + key + ", ");

                Object elem = elemEnum.nextElement();
                if (elem instanceof String[])
                {
                        String[] elemArray = (String[])elem;
                        for (int i=0; i<elemArray.length; i++)
                                System.out.println("element: " + elemArray[i]);
                        System.out.print("\n");
                }
                else if (elem instanceof CSUHLectureInfo[])
                {
                        CSUHLectureInfo[] lectArray = (CSUHLectureInfo[])elem;
                        for (int i=0; i<lectArray.length; i++)
                                System.out.println("element: " + lectArray[i].getCallNum());
                        System.out.print("\n");
                }
                else
                {
                        System.out.println("element: not a String[] or CSUHLectureInfo[]");
                        System.out.print("\n");
                }
         } */
        }
      //System.out.println("CSUHSchedulerHttpServlet: leaving getDataHash()");
      //System.out.println("\n****************************************************");

   return dataHash;
   }


   protected void exitServlet(long start, CSUHSchedulerUtils u, String url, boolean trace)
   {
      long stop = System.currentTimeMillis();
      long elapsed = (stop - start);
      synchronized(pageTime) { pageTime[0] += elapsed; }
      u.prnHtmlFooter(pageServes[0],pageTime[0],elapsed,loadTime,url,trace);
      u.done();
   }
   

   protected void printResultSet(ResultSet rset, CSUHSchedulerUtils u) throws SQLException
   {
      u.prnln("<table border=1>");
      ResultSetMetaData rsMeta = rset.getMetaData();
      for(int j=1; j<=rsMeta.getColumnCount(); j++)
      {
         u.prn("<th>" + rsMeta.getColumnName(j) + "</th>");
      }
      u.prnln("");
      while (rset.next())
      {
         u.prnln("   <tr>");
         for (int j=1; j<=rsMeta.getColumnCount(); j++)
         {
            u.prnln("      <td>" + rset.getString(j) + "</td>");
         }
         u.prnln("   </tr>");
      }
      u.prnln("</table>");
   }
}



import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.ibm.servlet.connmgr.*;

/*
 *  Basic servlet that all the other scheduler servlets inherit from.
 */

public class CSUHSchedulerHttpServlet extends HttpServlet implements CSUHRegistrationConstants
{
   //the default directory for WebSphere is the same directory the Netscape obj.conf file is in
   //for NT that directory is C:\Netscape\Suitespot\https-ess-0097\config
   //for Solaris that directory is /usr/netscape/suitespot/https-secure_anthony/config
   
   //these 4 variables require a new instance for each class that extends them so they are *not* static
   protected long[] pageServes = null;         // number of times this page has been served
   protected long[] pageTime = null;           // total amount of calender time the doGet code has spent executing
   protected java.util.Date loadTime = null;   // when the servlet was last loaded on the web server

   //these variables are shared by any class that extends them, there will not be a new instance
   protected static boolean trace = false;     // turns tracing on/off
   
   protected static String regularFont = null; //font to use for regular display
   protected static String grayFont = null;    //font to use for grayed out display
   protected static String buttonWidth = null; //width in pixels for any HTML buttons on the page (IE ignores this tag)
   protected static String buttonFont = null;  //font for the form buttons

   protected static String url = null;                //database connection url
   protected static IBMConnMgr connMgr = null;        //db connection manager
   protected static IBMConnSpec connSpec = null;      //db connection specification
   protected static CSUHOracleConnectionBroker dbConn = null; //returns the connMgr,connSpec and other objects related to the db

   protected static String CONFIG_FILE = null; //the text file "scheduler.properties" contains basic startup info for the servlets
   protected static String defaultDir = null;  //the "home" directory for WebSphere, on NT this is C:\WebSphere\AppServer on Solaris its /opt/IBMWebAS

   protected static final int SUBJECTS_PER_ROW = 10;     //how many subjects to display in one row              
   protected static final String LECTURE_TYPES = "'LEC', 'RCT', 'SEM'"; //lecture types...used in ratings

   protected static int MAX_NUMBER_TO_CONSIDER  = 5000; //max number of schedules to consider before stopping
   protected static int MAX_NUMBER_TO_CALCULATE = 500;  //max number of schedules to successfully create
   protected static int MAX_NUMBER_TO_DISPLAY   = 500;  //max number of ratings to display on the "ratings" page

   protected static final int NUMBER_OF_ELEMENTS_NOT_TO_INCLUDE = 1; //used in the ratings servlet
   protected static final int NUMBER_OF_DAYS_IN_ONE_WEEK = 7;
   protected static final int NUMBER_OF_DIGITS_IN_A_CALLNUMBER = 5;
   protected static final int NUMBER_OF_HALF_HOUR_BLOCKS_BETWEEN_1200AM_AND_0700AM = 14;

   protected static Boolean initialized = new Boolean(false);   //only initialize the static variables once.

   protected static boolean ipFiltering = false;

   protected static String validIP[] = { "129.65.210","129.65.8","129.65.7","129.65.82","207.62.152","207.62.153",
          "207.62.154","207.62.155","207.62.156","207.62.157","207.62.158","207.62.159","207.62.160",
          "207.62.161","207.62.162","207.62.163","207.62.164","207.62.165","207.62.166","207.62.167","129.65.145" };

   protected static Properties schedProperties = null;
 

 
   public void init(ServletConfig config) throws ServletException
   {
      super.init(config);
      try
      {
         synchronized(initialized)
         {
            if (!initialized.booleanValue())
            {
           //    System.out.print("Initializing SchedulerHttpServlet...");
               System.out.print("Initializing CSUHSchedulerHttpServlet...");


               initDb();
               System.out.println("...past initDb()...");
               regularFont = "<font face+Arial size=1>";
               grayFont    = "<font face=Arial size=1 color=slategray>";
               buttonWidth = "85";
               buttonFont  = "<font face=\"Courier New\" size=2>";
      //       defaultDir  = "/opt/WebSphere/AppServer";
      //       defaultDir  = "/opt/WebSphere/AppServer";
      //         defaultDir  = "C:\\Program Files\\IBM\\VisualAge for Java\\ide\\project_resources\\IBM WebSphere Test Environment";
            System.out.println("...past initDbIII()...");
               trace = false;
               ipFiltering = false;
               MAX_NUMBER_TO_CONSIDER = 5000;
               MAX_NUMBER_TO_CALCULATE = 500;
               MAX_NUMBER_TO_DISPLAY = 500;
             
         //    CONFIG_FILE = defaultDir + "/hosts/default_host/webreg/servlets/scheduler.properties";
         //    CONFIG_FILE = defaultDir + "/hosts/default_host/webreg/servlets/csuh.properties";
         //    CONFIG_FILE = defaultDir + "\\hosts\\default_host\\webreg\\servlets\\csuh.properties";  
               CONFIG_FILE = "C:\\csuh.properties";  
               System.out.println( "CONFIG_FILE IS  ");
               System.out.println("...past initDbIIIIIIIIIII()...");
               FileInputStream propertyFile = new FileInputStream(CONFIG_FILE);
               schedProperties = new Properties();
               schedProperties.load(propertyFile);
               
               initialized = new Boolean(true);
               System.out.println("SchedulerHttpServlet initialized.");
               System.out.println("Using CONFIG_FILE " + CONFIG_FILE);
            }
         }

         pageServes = new long[1];
         pageServes[0] = 0;
         loadTime = new java.util.Date();
         pageTime = new long[1];
         pageTime[0] = 0;
      }
      catch(Exception e)
      {
      //   System.out.println("Error initializing SchedulerHttpServlet: " + e);
          System.out.println("Error initializing CSUHSchedulerHttpServlet: " + e);
      }
   }
 
   public void destroy()
   {
      super.destroy();
   }

 
   /*
    * Processes the current row of a ResultSet and returns the results as an array of strings.
    */

   public String[] getRsStringData(ResultSet rs) throws SQLException
   {
      int index = rs.getMetaData().getColumnCount();
      String[] values = new String[index];
      for (int i=0;i<index;i++) values[i] = rs.getString(i+1); //arrays are zero based, ResultSet's are one based
      return values;
   }


   /*
    * HTML hyperlink that displays a message in the status bar area while the mouse is over the link.
    * <p>Note: The display text cannot contain single quotes.
    */
   public String ahrefWithStatus (String dest, String show, String display)
   {
      return ("<a href=\"" + dest + "\" onMouseOver=\"self.status='" + display + "'; return true;\">" + show + "</a>");
   }


   public String ahref (String dest, String show)
   {
      return ("<a href=\"" + dest + "\">" + show + "</a>");
   }


   private static String right(String s,int length)
   {
      return s.substring(s.length() - length);
   }


   private static String left(String s,int length)
   {
      return s.substring(0,length);
   }


   protected void initDb() throws ServletException
   {
      System.out.println("entered protected void initDb throws ServletException");

      dbConn = (CSUHOracleConnectionBroker)getServletContext().getAttribute("CSUHOracleConnectionBroker");

      connSpec = dbConn.getConnSpec();
      connMgr = dbConn.getConnMgr();
      url = dbConn.getUrl();
     
   }


   protected boolean sessionExists(HttpServletRequest request)
   {
      //System.out.println("CSUHSchedulerHttpServlet: sessionExists() called");

    if (request.getSession(false) != null)
    {
      HttpSession session = request.getSession(false);
      /* System.out.println("\nCSUHSchedulerHttpServlet sessionExists()  *************************************");
      System.out.println("HttpSession ID = " + session.getId());
      System.out.println("HttpSession is new = " + session.isNew());

      String[] getsessionvalues = session.getValueNames();
      if (getsessionvalues != null)
      {
         for (int i = 0; i < getsessionvalues.length; i++)
         {
            System.out.print("name[" + i + "] = " + getsessionvalues[i] + ", ");
            System.out.println("value[" + i + "] = " + session.getValue(getsessionvalues[i])); */

            /*if (getsessionvalues[i].startsWith("CSUHStudent"))
            {
               studInfo = getStudentFromSession(session);
               System.out.println("CSUHAddServlet: CSUHStudent* = " + studInfo.toString());
            }*/

            /* Object svalue = session.getValue(getsessionvalues[i]);
            if (svalue instanceof String[])
            {
                        String[] sArray = (String[])svalue;
                        for (int j=0; j<sArray.length; j++)
                                System.out.println("detail value: " + sArray[j]);
                        System.out.print("\n");
            }
            else if (svalue instanceof CSUHStudent)
            {
                CSUHStudent studInfo = (CSUHStudent)svalue;
                System.out.println("detail value ssnum: " + studInfo.getSSNum());
                System.out.println("detail value pin: " + studInfo.getPIN());
                System.out.println("detail value priority count: " + studInfo.getPriorityCount());
                System.out.println("detail value survey answer: " + studInfo.getSurveyAnswer());
                System.out.println("detail value priority status: " + studInfo.getPriorityStatus());
                System.out.println("detail value survey status: " + studInfo.getSurveyStatus());
                System.out.println("detail value total units: " + studInfo.getTotalUnits());
                System.out.println("detail value: class schedule can be iterated here");
                studInfo.showClasses();
                System.out.println("detail value schedule size: " + studInfo.scheduleSize());
                System.out.println("detail value schedule changed?: " + studInfo.getScheduleChangedDontSet());
                System.out.print("\n");
            }
            else
            {
                System.out.println("detail value: not a String[] or CSUHStudent");
                System.out.print("\n");
            }  //end if
         }  //end for
      } // end if
      System.out.println("\nCSUHSchedulerHttpServlet sessionExists()  *************************************"); */
    }


      return (request.getSession(false) != null);
   }


   protected String[] getValuesFromHash(Hashtable dataHash, String key)
   {
      //System.out.println("CSUHSchedulerHttpServlet: getValuesFromHash() called");
      return (String[])dataHash.get(key);
   }

 
  protected CSUHStudent getStudentFromSession(HttpSession session) {
    //System.out.println("CSUHSchedulerHttpServlet: getStudentFromSession() called");
    if (session != null) {
    //System.out.println("getStudentFromSession() in CSUHRegistrationHttpServlet returns = session is NOT null.");
      return ((CSUHStudent)session.getValue(STUD_INFO));
    } else {
    //System.out.println("getStudentFromSession() in CSUHRegistrationHttpServlet returns = session null.");
      return null;
    }
  }

   protected boolean theseElementsExist(Hashtable dataHash, String[] elements)
   {
      if (dataHash == null) return false;  
      for (int i=0;i<elements.length;i++)
         if ((String[])dataHash.get(elements[i]) == null) return false;
   return true;
   }


   protected Hashtable getDataHash(HttpServletRequest request)
   {
      // System.out.println("\n****************************************************");
      //System.out.println("CSUHSchedulerHttpServlet: getDataHash() called");
      Hashtable dataHash = null;
      try
      {
         dataHash = HttpUtils.parsePostData(Integer.parseInt(request.getHeader("Content-length")), request.getInputStream());
      }
      catch(Exception e) { }
     
      if (dataHash == null)
      {
         //try {
         //   dataHash = HttpUtils.parseQueryString(request.getQueryString(), HttpUtils.getLanguage(request));}
   
         try
         {
            dataHash = HttpUtils.parseQueryString(request.getQueryString());
         }
         catch(Exception e) { }
      }

      if (dataHash != null)
      {

         Enumeration keyEnum = dataHash.keys();
         Enumeration elemEnum = dataHash.elements();
         int hashSize = dataHash.size();
         //System.out.println("CSUHSchedulerHttpServlet: dataHash size is: " + hashSize);

         /* commented out 11202000 while (keyEnum.hasMoreElements())
         {
                String key = (String)keyEnum.nextElement();
                System.out.print("key: " + key + ", ");

                Object elem = elemEnum.nextElement();
                if (elem instanceof String[])
                {
                        String[] elemArray = (String[])elem;
                        for (int i=0; i<elemArray.length; i++)
                                System.out.println("element: " + elemArray[i]);
                        System.out.print("\n");
                }
                else if (elem instanceof CSUHLectureInfo[])
                {
                        CSUHLectureInfo[] lectArray = (CSUHLectureInfo[])elem;
                        for (int i=0; i<lectArray.length; i++)
                                System.out.println("element: " + lectArray[i].getCallNum());
                        System.out.print("\n");
                }
                else
                {
                        System.out.println("element: not a String[] or CSUHLectureInfo[]");
                        System.out.print("\n");
                }
         } */
        }
      //System.out.println("CSUHSchedulerHttpServlet: leaving getDataHash()");
      //System.out.println("\n****************************************************");

   return dataHash;
   }


   protected void exitServlet(long start, CSUHSchedulerUtils u, String url, boolean trace)
   {
      long stop = System.currentTimeMillis();
      long elapsed = (stop - start);
      synchronized(pageTime) { pageTime[0] += elapsed; }
      u.prnHtmlFooter(pageServes[0],pageTime[0],elapsed,loadTime,url,trace);
      u.done();
   }
   

   protected void printResultSet(ResultSet rset, CSUHSchedulerUtils u) throws SQLException
   {
      u.prnln("<table border=1>");
      ResultSetMetaData rsMeta = rset.getMetaData();
      for(int j=1; j<=rsMeta.getColumnCount(); j++)
      {
         u.prn("<th>" + rsMeta.getColumnName(j) + "</th>");
      }
      u.prnln("");
      while (rset.next())
      {
         u.prnln("   <tr>");
         for (int j=1; j<=rsMeta.getColumnCount(); j++)
         {
            u.prnln("      <td>" + rset.getString(j) + "</td>");
         }
         u.prnln("   </tr>");
      }
      u.prnln("</table>");
   }
}


******************************************************************************************************************************************************************************

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.Date;
import com.ibm.servlet.connmgr.*;

public class CSUHOracleConnectionBroker
{
   private static final int MS_PER_DAY   = 24*60*60*1000; //milliseconds per day
   private static final int MS_PER_HOUR  =    60*60*1000; //milliseconds per hour
   private static final int MS_PER_MIN   =       60*1000; //milliseconds per minute
   private static final int MS_PER_SEC   =          1000; //milliseconds per second

   private static IBMConnMgr connMgr = null; // threadsafe object for managing database connections
   private static IBMConnSpec connSpec = null; // specification for the database connections
 
   Connection conn = null;

   IBMJdbcConn cmConn = null;
 
   private static String poolName   = "JdbcOracle"; // pool name from WebSphere application manager
   private static boolean waitRetry = true; // waitRetry - try again if all connections are busy?
   private static String jdbcDriver = "oracle.jdbc.driver.OracleDriver"; // Java class for the JDBC driver
 //  private static String url        = "jdbc:oracle:thin:@127.0.0.1:1521:REG"; // database connection url
   private static String url        = "jdbc:oracle:thin:@127.0.0.1:1521:WEBREG"; // database connection url
/
    private static String user       = "system"; // user
    private static String password   = "manager"; // password


   
   private static Date schedWinter = null; // The date when the scheduler starts showing winter quarter classes
   private static Date schedSpring = null; // The date when the scheduler starts showing spring quarter classes
   private static Date schedSummer = null; // The date when the scheduler starts showing summer quarter classes
   private static Date schedFall = null;   // The date when the scheduler starts showing fall quarter classes
   
   private static Date regWinter = null; // The date when you can register for winter quarter classes
   private static Date regSpring = null; // The date when you can register for spring quarter classes
   private static Date regSummer = null; // The date when you can register for summer quarter classes
   private static Date regFall = null;   // The date when you can register for fall quarter classes

   //I have been guaranteed ZTLK will never need a 4 digit year...but just in case.  
   private static boolean ZTLKUses4DigitYear = false;

   // date format with month, day, and 4 digit year
   private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

   // date format with 4 digit year
   private static SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); //format for extracting the 4 digit year e.g. yyyy

   // date format with month,day,year,hours,minutes and am/pm indicator
   private static SimpleDateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

   // date format for abbreviation of the weekday (Sun,Mon,Tue,Wed,Thu,Fri,Sat)
   private static SimpleDateFormat dayFormat = new SimpleDateFormat("E");

   private static String dateString = null; //string representation of the date
   private static String days = "Mon Tue Wed Thu Fri Sat";       //the days registration is available
   private static String start = "07:00 AM";      //time registration starts
   private static String stop = "07:00 PM";       //time registration stops

   /**
    *  Initializes all of the information necessary for connecting to the Oracle database.
      *  Makes use of the IBMConnMgr object for pooling database connections to avoid the overhead
      *  of establishing a connection for each HTTP request.<br>
      *  This class also contains some utility methods for determining what quarter we are in, when
      *  the next quarter will start and various other date related methods.
    */
 
  private static CSUHOracleConnectionBroker onlyInstance = null;

  private CSUHOracleConnectionBroker()
  {
    init();
  }


  public static CSUHOracleConnectionBroker instance()
  {
    if (onlyInstance == null)
      onlyInstance = new CSUHOracleConnectionBroker();

    return onlyInstance;
  }

 
   public void init()
   {
     
      System.out.println("Loading CSUHOracleConnectionBroker...");
     
      try {
         
         days = days.toLowerCase();

         //dateString = "02/19/2001";
         dateString = "01/09/2001";
         schedSpring = dateFormat.parse(dateString.trim());

         //dateString = "02/19/2001";
         dateString = "01/09/2001";
         regSpring = dateFormat.parse(dateString.trim());

         dateString = "05/14/2001";
         schedSummer = dateFormat.parse(dateString.trim());

         dateString = "05/14/2001";
         regSummer = dateFormat.parse(dateString.trim());

         dateString = "07/13/2001";
         schedFall = dateFormat.parse(dateString.trim());

         dateString = "07/13/2001";
         regFall = dateFormat.parse(dateString.trim());

         dateString = "10/16/2000";
         schedWinter = dateFormat.parse(dateString.trim());

         dateString = "10/16/2000";
         regWinter = dateFormat.parse(dateString.trim());
         
         System.out.println("Scheduling is available for " + getSchedQuarterText() + " " + getSchedYear() + ".");
         System.out.println("Registration is available for " + getRegQuarterText() + " " + getRegYear() + ".");
         System.out.println("ZTLK is using term " + getZTLKTerm() + ".");
         System.out.println("Registration is available on " + getDays() + " from " + getStart() + " to " + getStop() + ".");
         System.out.println("Registration is " + ((isRegistrationAllowed()) ? "" : "NOT ") + "currently active.");
         
         // Create JDBC connection specification.
         connSpec = new IBMJdbcConnSpec (poolName, waitRetry, jdbcDriver, url, user, password);  
         connSpec.verify();

         connMgr = IBMConnMgrUtil.getIBMConnMgr();

         cmConn = (IBMJdbcConn)connMgr.getIBMConnection(connSpec);

         if (cmConn != null) {
            conn = cmConn.getJdbcConnection();
            if (conn != null) {System.out.println("Oracle JDBC connection in CSUHOracleConnectionBroker successful");}
            cmConn.releaseIBMConnection();
            }

            Statement stmt = null;
            ResultSet rs = null;
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT DESCRIPTION FROM dept");

            while(rs.next())
            {
               System.out.println(rs.getString("DESCRIPTION"));
            }
   
         } catch(Exception e) {
         System.out.println("CSUHOracleConnectionBroker: " + e);
         return;}
   }//init()


   /** Returns the IBMConnMgr object that deals with database connections. */
   public IBMConnMgr  getConnMgr()     { return connMgr;     } //IBM database connection manager object

   /** Returns the IBMConnSpec object that handles the specification for the database connections.*/
   public IBMConnSpec getConnSpec()    { return connSpec;    } //specification for db connection

   /** The database pool name from the Connection Mgmt tab in WebSphere (jdbcOracle). */
   public String      getPoolName()    { return poolName;    } //db pool name from the Connection Mgmt tab in WebSphere

   /** Try again if all database connections are in use?  */
   public boolean     getWaitRetry()   { return waitRetry;   } //try again if all connections are busy?

   /** Class name of the JDBC driver. (e.g. oracle.jdbc.driver.OracleDriver) */
   public String      getJdbcDriver()  { return jdbcDriver;  } //class name of the Jdbc driver

   /** Database connection url (eg jdbc:oracle:thin:@lovelace.its.calpoly.edu:1521:webr). */
   public String      getUrl()         { return url;         } //db connection url

   /** Username for the database account. */
   public String      getUser()        { return user;        } //db username

   /** Password for the database user account. */
   public String      getPassword()    { return password;    } //db password

   /** Days that the registration portion of POWER is available (eg Mon Tue Wed Thu Fri). */
   public String      getDays()        { return days;        } //days of operation

   /** Time that the registration portion of POWER becomes available on the days it is in operation. */
   public String      getStart()       { return start;       } //start time on those days

   /** Time that the registration portion of POWER becomes unavailable on the days it is in operation. */
   public String      getStop()        { return stop;        } //stop time on those days

   /** Date scheduling for Winter quarter becomes available. */
   public Date        getSchedWinter() { return schedWinter; } //date scheduling for Winter quarter is available

   /** Date scheduling for Spring quarter becomes available. */
   public Date        getSchedSpring() { return schedSpring; } // ""      ""      "" Spring   ""    ""    ""

   /** Date scheduling for Summer quarter becomes available. */
   public Date        getSchedSummer() { return schedSummer; } // ""      ""      "" Summer   ""    ""    ""

   /** Date scheduling for Fall quarter becomes available. */
   public Date        getSchedFall()   { return schedFall;   } // ""      ""      "" Fall     ""    ""    ""

   /** Date registration for Winter quarter becomes available. */
   public Date        getRegWinter()   { return regWinter;   } //date registration for Winter quarter is available

   /** Date registration for Spring quarter becomes available.  */
   public Date        getRegSpring()   { return regSpring;   } // ""      ""        "" Spring   ""    ""    ""

   /** Date registration for Summer quarter becomes available. */
   public Date        getRegSummer()   { return regSummer;   } // ""      ""        "" Summer   ""    ""    ""

   /** Date registration for Fall quarter becomes available. */
   public Date        getRegFall()     { return regFall;     } // ""      ""        "" Fall     ""    ""    ""

   /** Is registration currently allowed? */
   public boolean isRegistrationAllowed() throws ParseException {

      Date now = new Date();
      String today = dayFormat.format(now).toLowerCase();
      if (days.indexOf(today) == -1) return false;

      String s1 = dateFormat.format(now) + " " + start;
      String s2 = dateFormat.format(now) + " " + stop;
      Date startTime = timeFormat.parse(s1);
      Date stopTime = timeFormat.parse(s2);
      if ((now.before(startTime)) || (now.after(stopTime)))
         return false;
      else
         return true;
   }

   /** Returns a 4 digit year corresponding to the year registration is available for. */
   public int getRegYear() {
      Date now = new Date();
      String s = null;

      if (now.after(regSpring) && now.before(regSummer))
         s = yearFormat.format(regSpring);
      else if (now.after(regSummer) && now.before(regFall))
         s = yearFormat.format(regSummer);
      else if (now.after(regFall) && now.before(regWinter))
         s = yearFormat.format(regFall);
      else { //Winter quarter has special logic because it contains a transition from one year to the next
         s = yearFormat.format(regWinter);
         return (Integer.parseInt(s)+1);
      }
      return Integer.parseInt(s);
   }

   /** Returns a 4 digit year corresponding to the year it will be for next quarters registration cycle. */
   public int getNextRegYear() {
      Date now = new Date();
      String s = null;

      if (now.after(regWinter) && now.before(regSpring))
         s = yearFormat.format(regSpring);
      else if (now.after(regSpring) && now.before(regSummer))
         s = yearFormat.format(regSummer);
      else if (now.after(regSummer) && now.before(regFall))
         s = yearFormat.format(regFall);
      else { //Winter quarter has special logic because it spills over into the next calendar year.
         s = yearFormat.format(regWinter);
         return (Integer.parseInt(s)+1);
      }
      return Integer.parseInt(s);
   }

   /** Returns a 4 digit year corresponding to the year the scheduler is available for. */
   public int getSchedYear() {
      Date now = new Date();
      String s = null;

      if (now.after(schedSpring) && now.before(schedSummer))
         s = yearFormat.format(schedSpring);
      else if (now.after(schedSummer) && now.before(schedFall))
         s = yearFormat.format(schedSummer);
      else if (now.after(schedFall) && now.before(schedWinter))
         s = yearFormat.format(schedFall);
      else { //Winter quarter has special logic because it spills over into the next calendar year.
         s = yearFormat.format(schedWinter);
         return (Integer.parseInt(s)+1);
      }
      return Integer.parseInt(s);
   }

   /** Returns a 4 digit year corresponding to the year for the next quarter's for the scheduler. */
   public int getNextSchedYear() {
      Date now = new Date();
      String s = null;

      if (now.after(schedWinter) && now.before(schedSpring))
         s = yearFormat.format(schedSpring);
      else if (now.after(schedSpring) && now.before(schedSummer))
         s = yearFormat.format(schedSummer);
      else if (now.after(schedSummer) && now.before(schedFall))
         s = yearFormat.format(schedFall);
      else { //Winter quarter has special logic because it spills over into the next calendar year.
         s = yearFormat.format(schedWinter);
         return (Integer.parseInt(s)+1);
      }
      return Integer.parseInt(s);
   }

   /** Returns the date registration became available for the current quarter. */
   public Date getRegDate() {
      Date now = new Date();
      if (now.after(regWinter) && now.before(regSpring))
         return regWinter;
      else if (now.after(regSpring) && now.before(regSummer))
         return regSpring;
      else if (now.after(regSpring) && now.before(regFall))
         return regSpring;
      else
         return regFall;
   }

   /** Returns the date when registration will become available for the next quarter. */
   public Date getNextRegDate() {
      Date now = new Date();
      if (now.after(regWinter) && now.before(regSpring))
         return regSpring;
      else if (now.after(regSpring) && now.before(regSummer))
         return regSummer;
      else if (now.after(regSpring) && now.before(regFall))
         return regFall;
      else
         return regWinter;
   }

   /** Returns the date when scheduling will become available for the next quarter. */
   public Date getNextSchedDate() {
      Date now = new Date();
      if (now.after(schedWinter) && now.before(schedSpring))
         return schedSpring;
      else if (now.after(schedSpring) && now.before(schedSummer))
         return schedSummer;
      else if (now.after(schedSpring) && now.before(schedFall))
         return schedFall;
      else
         return schedWinter;
   }

   /**
     * Returns the number of days between now and the date passed in.
     * <p>If there is a fraction of a day left between the two dates it gets rounded up to 1.
     */
   public int getDaysUntilThisDate(Date future) {
      return (int)(Math.ceil(((double)future.getTime() - (double)(new java.util.Date()).getTime()) / MS_PER_DAY));
   }


   /** This is the text for the quarter currently available for registration (Winter, Spring, Summer, Fall).*/
   public String getRegQuarterText() {
      Date now = new Date();
      if (now.after(regWinter) && now.before(regSpring))
         return "Winter";
      else if (now.after(regSpring) && now.before(regSummer))
         return "Spring";
      else if (now.after(regSummer) && now.before(regFall))
         return "Summer";
      else
         return "Fall";
   }//getRegQuarterText

   /** This is the text for the next quarter's registration cycle. */
   public String getNextRegQuarterText() {
      Date now = new Date();
      if (now.after(regWinter) && now.before(regSpring))
         return "Spring";
      else if (now.after(regSpring) && now.before(regSummer))
         return "Summber";
      else if (now.after(regSummer) && now.before(regFall))
         return "Fall";
      else
         return "Winter";
   }//getRegQuarterText

   /** This is the text for the quarter currently available for scheduling (Winter, Spring, Summer, Fall). */
   public String getSchedQuarterText() {
      Date now = new Date();
      if (now.after(schedWinter) && now.before(schedSpring))
         return "Winter";
      else if (now.after(schedSpring) && now.before(schedSummer))
         return "Spring";
      else if (now.after(schedSummer) && now.before(schedFall))
         return "Summer";
      else
         return "Fall";
   }//getSchedQuarterText

   /** This is the text for the next quarter for the scheduler. */
   public String getNextSchedQuarterText() {
      Date now = new Date();
      if (now.after(schedWinter) && now.before(schedSpring))
         return "Spring";
      else if (now.after(schedSpring) && now.before(schedSummer))
         return "Summer";
      else if (now.after(schedSummer) && now.before(schedFall))
         return "Fall";
      else
         return "Winter";
   }//getSchedQuarterText

   /** Returns the term ZTLK is using. */
   public String getRegTerm() { return getZTLKTerm(); }

   /**
     * This is the term used by ZTLK for registration.
     * <p>Right now it is 3 digits ie 991,992,993,994,001,002,003<br>
     *
     */
   public String getZTLKTerm() {
      Date now = new Date();
      String yearStr = getRegYear() + "";
      if (!ZTLKUses4DigitYear) yearStr = yearStr.substring(2);

      if (now.after(regWinter) && now.before(regSpring)) {
         return yearStr + "1";
      } else if (now.after(regSpring) && now.before(regSummer)) {
         return yearStr + "2";
      } else if (now.after(regSummer) && now.before(regFall)) {
         return yearStr + "3";
      } else {
         return yearStr + "4";
      }
   }

   
   }//CSUHOracleConnectionBroker
Comment
Watch Question

Commented:
we have no mood to debug the program for you !

Author

Commented:
Actually knowing what I should look for specifically on the
dbConn = (CSUHOracleConnectionBroker)getServletContext().getAttribute("CSUHOracleConnectionBroker");
line would be sufficent.

Commented:
I think calling getServletContext() returns null, and that's why you get the exception.

Author

Commented:
thanks yongsing:  that's sure what it looks like, but  isn't servlet context  associated with the  client-server request-response session?
 
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
Yes, but you are in the init() method.
It is not involved in a request-response session, it's just run when the servlet is started up.
So I don't think you have serlet context at this point.

Author

Commented:
Understanding

Explore More ContentExplore courses, solutions, and other research materials related to this topic.