Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2005

Tip: Looking for answers? Try searching our database.

Null pointer exception

Thread view: 
dschectman@yahoo.com - 25 Jul 2005 16:10 GMT
I get a stange NullPointerException in getClass().getName().  The code
below is running on Iplanet app server 6.5 running on windows 2000.
The datasource is defined by an app server connection pool.

Here is the code
package helper;

import org.apache.log4j.Category;
import java.sql.*;

// This class gets an connection to the datasource
public class DBConnectionHelper
{
 Category loggerObj = Category.getInstance(("DBConnectionHelper");
 Connection conn = null;
 com.netscape.server.jdbc.ConnectionProxy csproxy = null;

  public DBConnectionHelper()
  {
  }

  public Connection getDBConnection() {
    return getDBConnection("defaultdb");
  }
  public Connection getDBConnection(String connName)
  {
    Connection csproxyconn = null;
    try
    {
loggerObj.info("getting connection");
      // Get a connection to the datasorce
      conn = new helper.DBConnectionManager().getDBConnection(
          connName);
loggerObj.info("Got connection");
loggerObj.info(conn);  // The funny thing is that this line logs a
valid class (com.netscape.server.jdbc.ConnectionProxy@1a4bd4)
loggerObj.info(conn.getClass()); // Yet this line throws a
NullPOinterException as if conn was null
loggerObj.info(conn.getClass().getName());
      String className = conn.getClass().getName();
      loggerObj.info("Connection class Name ->" + className);

      //For Iplanet connection pool, convert to Oracle connection
      if
(!className.equalsIgnoreCase("oracle.jdbc.driver.OracleConnection")) {
        csproxy = (com.netscape.server.jdbc.ConnectionProxy) conn;
        csproxyconn = csproxy.getConnection();
        return csproxyconn;
      }
     }
    catch (Exception ex) {
loggerObj.error("Exception caught");
loggerObj.error(ex.getMessage());
loggerObj.error(ex);
      //loggerObj.error(ex.getMessage(), ex);
    }

    return conn;
  }
}

The connection manager class is just a wrapper for getting the
connection.  A configuration file identifies whether to get it from a
JNDI lookup or from Oracle.

  public Connection getDBConnection(String connName)
  {
loggerObj.info("in getDBConnection" + connName);
     // Get the db configuration from the config file
     DBConfig aDBConfig = DBConfig.getInstance();
     OrderedHashMap lookupData = aDBConfig .getLookupData(DBConfig
.KEY_DBCONNECTION);
     InitialContext initialContext = null;
     Hashtable env = new java.util.Hashtable(1);
     Connection conn = null;
     String oracleUserName     = null;
     String oracleUserPassword = null;
     String oracleTnsName      = null;
     String oracleDriverName   = null;
     String jndiLookupType = null;
     String jndiName      = null;
     String jndiLookup   = null;

     if (lookupData != null)
     {
       OrderedHashMap dbLookupData = (OrderedHashMap)         if
(dbLookupData != null) {
         oracleUserName = (String) dbLookupData.get("username");
         oracleUserPassword = (String) dbLookupData.get("password");
         oracleTnsName = (String) dbLookupData.get("dburl");
         oracleDriverName = (String) dbLookupData.get("driver");
         jndiLookupType = (String)
dbLookupData.get("jndi_lookup_type");
         jndiName = (String) dbLookupData.get("jndi_name");
         jndiLookup = (String) dbLookupData.get("jndi_lookup");

         try {
           // To use Iplanet connection pooling
           if ( (jndiLookup != null) &&
jndiLookup.equalsIgnoreCase("yes")) {
             loggerObj.info("INSIDE Iplanet Connection Pool
getConnection(" +
                            jndiName + ")");
             initialContext = new InitialContext(env);
             DataSource ds = (javax.sql.DataSource)
initialContext.lookup(
                 jndiName);
             conn = ds.getConnection();

//              com.netscape.server.jdbc.ConnectionProxy csproxy =
(com.netscape.server.jdbc.ConnectionProxy)ds.getConnection();
//
System.out.println("csproxy.getConnection().getClass().getName(): " +
csproxy.getConnection().getClass().getName());
//              conn = csproxy.getConnection();
//              loggerObj.info("conn.getClass().getName()"
+conn.getClass().getName());

             loggerObj.info("Completed Iplanet Connection Pool
getConnection(" +
                            jndiName + ")");
           }
           else { // To use Oracle connection pooling
             loggerObj.info("INSIDE Oracle Connection getConnection("
+ connName +
                            ")");
             Driver d = (Driver)
Class.forName(oracleDriverName).newInstance();
             conn = DriverManager.getConnection(oracleTnsName,
oracleUserName,
                                                oracleUserPassword);
             loggerObj.info("Completed Oracle Connection
getConnection(" +
                            connName + ")");
           }
         }
         catch (SQLException e) {
           loggerObj.error("Error in getting the NEW Connection " +
                           e.getMessage());
         }
         catch (NamingException e) {
           loggerObj.error("Error in getting the NEW Connection " +
                           e.getMessage());
         }
         catch (Exception ex) {
           loggerObj.error(ex.getMessage(), ex);
         }
         finally {
           return conn;
         }
       } else loggerObj.error("dbLookupData is null");
     } else loggerObj.error("lookupData is null");
     return conn;
 }

Here are the log files
[25/Jul/2005 10:01:37:2] info: [25 Jul 2005 10:01:37] getting
connection
[25/Jul/2005 10:01:37:2] info: [25 Jul 2005 10:01:37] INSIDE Iplanet
Connection Pool getConnection(jdbc/defaultdb)
[25/Jul/2005 10:01:37:6] info: [25 Jul 2005 10:01:37] Completed Iplanet
Connecti
on Pool getConnection(jdbc/defaultdb)
[25/Jul/2005 10:01:37:6] info: [25 Jul 2005 10:01:37] Got connection
[25/Jul/2005 10:01:37:6] info: [25 Jul 2005 10:01:37]
com.netscape.server.jdbc.ConnectionProxy@1a4bd4
[25/Jul/2005 10:01:37:6] error: [25 Jul 2005 10:01:37] Exception caught
[25/Jul/2005 10:01:37:6] error: [25 Jul 2005 10:01:37]
[25/Jul/2005 10:01:37:6] error: [25 Jul 2005 10:01:37]
java.lang.NullPointerException
John Currier - 25 Jul 2005 16:31 GMT
You're evidently throwing away your stack traces.  I assume that your
logger can log an exception with stack traces, right?  That extra piece
of info should significantly help isolate the problem.

IMHO normal code should not call Exception.getMessage().

John Currier
http://schemaspy.sourceforge.net
Thomas Fritsch - 25 Jul 2005 16:39 GMT
> I get a stange NullPointerException in getClass().getName(). ...
How do you know that the NullPointerException happened in
getClass().getName()? I see no evidence for this in your material below.
Do you have an exception stack trace leading to that conclusion? Please
share that information with us. If you don't have a stack trace, let
your loggerObj print one. If the stack trace gives any line numbers,
please mark-up those lines in the posted source code.

> ...  The code
> below is running on Iplanet app server 6.5 running on windows 2000.
> The datasource is defined by an app server connection pool.
>
> Here is the code
[...code snipped...]
BTW: the line-wrapping makes the code very hard to read.

> The connection manager class is just a wrapper for getting the
> connection.  A configuration file identifies whether to get it from a
> JNDI lookup or from Oracle.

[...code snipped...]

> Here are the log files
> [25/Jul/2005 10:01:37:2] info: [25 Jul 2005 10:01:37] getting
[quoted text clipped - 11 lines]
> [25/Jul/2005 10:01:37:6] error: [25 Jul 2005 10:01:37]
> java.lang.NullPointerException

Signature

"Thomas:Fritsch$ops:de".replace(':','.').replace('$','@')

dschectman@yahoo.com - 25 Jul 2005 20:25 GMT
Thanks for the replies.  I added some more debugging to the code

loggerObj.info("Getting conn " + connName);
conn = new helper.DBConnectionManager().getDBConnection(connName);
loggerObj.info("Got it");
loggerObj.info(conn);
if (conn==null) throw new Exception("conn is null");
loggerObj.info(String.valueOf(conn.isClosed()));
loggerObj.info(String.valueOf(conn.getAutoCommit()));
loggerObj.info(conn.getClass());
String className = conn.getClass().getName();
loggerObj.info("Connection class Name ->" + className);

According to the log file, the exception occurs on conn.getClass() as
the booleans are recorded in the log file and the next entry is the
NullPointerException.

[25/Jul/2005 15:02:59:0] info: [25 Jul 2005 15:02:59] Got it
[25/Jul/2005 15:02:59:0] info: [25 Jul 2005 15:02:59]
com.netscape.server.jdbc.ConnectionProxy@11e831
[25/Jul/2005 15:02:59:0] info: [25 Jul 2005 15:02:59] false
[25/Jul/2005 15:02:59:0] info: [25 Jul 2005 15:02:59] true
[25/Jul/2005 15:02:59:0] error: [25 Jul 2005 15:02:59]
java.lang.NullPointerException

According to the stack trace the error occurred at line 29, which,
according to the editor, is
conn = new helper.DBConnectionManager().getDBConnection(connName);

[25/Jul/2005 15:02:59:0] error: [25 Jul 2005 15:02:59]
java.lang.NullPointerException
       at helper.DBConnectionHelper.getDBConnection(
DBConnectionHelper.java:29)
       at jsp.APPS.VxComponent.test._jspService(test.java:150)
       at org.apache.jasper.runtime.HttpJspBase.service(Unknown
Source)
       at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
       at
com.netscape.server.servlet.servletrunner.ServletInfo.service
(Unknown Source)
       at
com.netscape.server.servlet.servletrunner.ServletRunner.callJSP(Unknown
Source)
       at
com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.
callJspCompiler(Unknown Source)
       at
com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.
callUri(Unknown Source)
       at
com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.
callUriRestrictOutput(Unknown Source)
       at
com.netscape.server.servlet.platformhttp.PlatformRequestDispatcher.fo
rward(Unknown Source)
       at com.netscape.server.servlet.jsp.JSPRunner.service(Unknown
Source)
       at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
       at
com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
Source)
       at
com.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown
Source)
       at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
       at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
       at com.kivasoft.thread.ThreadBasic.run(Native Method)
       at java.lang.Thread.run(Thread.java:479)

> > I get a stange NullPointerException in getClass().getName(). ...
> How do you know that the NullPointerException happened in
[quoted text clipped - 33 lines]
> > [25/Jul/2005 10:01:37:6] error: [25 Jul 2005 10:01:37]
> > java.lang.NullPointerException
Thomas Fritsch - 25 Jul 2005 23:04 GMT
> Thanks for the replies.  I added some more debugging to the code
>
[quoted text clipped - 30 lines]
> helper.DBConnectionHelper.getDBConnection(DBConnectionHelper.java:29)
>        at jsp.APPS.VxComponent.test._jspService(test.java:150)
[...]
>        at java.lang.Thread.run(Thread.java:479)

You actually have 2 (two!) NullPointerException's:
(1) one at line 29 in method getDBConnection() of the DBConnectionManager
    (*not* DBConnectionHelper) class, as the exception stack trace shows
without doubt
(2) one near the place where you suspect it.But you decided to catch it
     without printing the stack trace, thus ignoring the line numbers you
would get there

The reason behind that is probably your somewhat screwed (sorry!) design.
You actually have 2 different classes (DBConnectionHelper and
DBConnectionManager), both with a getDBConnection method.
In your DBConnectionHelper.getDBConnection method you create a new instance
of DBConnectionManager and  call its getDBConnection method. O my
goodness....
You probably should redesign your code from scratch.
To make it clear, here is your current code with large parts stripped out:

public class DBConnectionHelper
{
  [...]

  public Connection getDBConnection(String connName)
  {
      [...]
      conn = new helper.DBConnectionManager().getDBConnection(  /*line 29*/
          connName);
      [...]
      return conn;
  }
}

Secondly: As John Currier has already recommended, you *really* should print
a stack trace in your catch clause. Look up the javadoc of class
org.apache.log4j.Category to find a method, which can take an Exception (or
Throwable) object as a parameter.

Signature

"TFritsch$t-online:de".replace(':','.').replace('$','@')

Thomas Fritsch - 26 Jul 2005 01:11 GMT
[...]
>> java.lang.NullPointerException
>>        at
[quoted text clipped - 7 lines]
>     (*not* DBConnectionHelper) class, as the exception stack trace shows
> without doubt
I was puzzled. Of course it is just the other way round:
(1) one at line 29 in method getDBConnection() of the DBConnectionHelper
   (*not* DBConnectionManager) class, as the exception stack trace shows
   without doubt
[...]
But the main issue still persists.

Signature

"TFritsch$t-online:de".replace(':','.').replace('$','@')

John Currier - 26 Jul 2005 14:34 GMT
> According to the stack trace the error occurred at line 29, which,
> according to the editor, is
[quoted text clipped - 5 lines]
>        at jsp.APPS.VxComponent.test._jspService(test.java:150)
>        at org.apache.jasper.runtime.HttpJspBase.service(Unknown Source)

That's not line 29 of your JSP.  It's line 29 of
DBConnectionHelper.java.

I won't even comment on doing database manipulations directly in a
JSP...

John
http://schemaspy.sourceforge.net
dschectman@yahoo.com - 27 Jul 2005 14:35 GMT
Thanks for the input.  This code is from a production application that
we inherited.  The same ambiguous code runs fine in production.  I have
traced the porblem to my setup.  I created a function that gets the
datasource with a JNDI lookup and prints the class associated with it.
1) If the object is cast to com.netscape.server.jdbc.ConnectionProxy,
getClass does not throw a null pointer exception
2) If the object is cast as Connection, getClass throws a null pointer
exception

The code compiles without any errors.  This tells me that something is
wrong with the runtime classpath or the implementation of
com.netscape.server.jdbc.ConnectionProxy.  The null pointer exception
may be related to a class cast exception between Connection and
com.netscape.server.jdbc.ConnectionProxy.

test.jsp:
<html>
<body>
Test datasource
<%
TestClass c = new TestClass();
c.foo();
%>
</body>
</html>

TestClass.java
import org.apache.log4j.Logger;
import java.sql.*;
import javax.naming.InitialContext;
import java.util.Hashtable;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.StringWriter;
import java.io.PrintWriter;

public class TestClass {
Logger loggerObj = getLogger("DBConnectionManager");
public void foo(String jndiName)
throws Exception
{
    Hashtable env = new Hashtable();
    InitialContext initialContext = new InitialContext(env);
    loggerObj.info("in foo");
    DataSource ds = (javax.sql.DataSource)
initialContext.lookup(jndiName);
    loggerObj.info("got datasource");
    Connection c =ds.getConnection();
    com.netscape.server.jdbc.ConnectionProxy csproxy =
(com.netscape.server.jdbc.ConnectionProxy) ds.getConnection();
    loggerObj.info("cl1 = " + csproxy.getClass().getName());
    loggerObj.info("cl2 = " +
((com.netscape.server.jdbc.ConnectionProxy)c).getClass().getName());
    loggerObj.info("cl2 = " + ((Connection)
csproxy).getClass().getName());
  }
}
John Currier - 29 Jul 2005 03:01 GMT
I'm confused as to why you posted the code, but didn't post the stack
trace.

What you cast the connection to should not result in any change in the
behavior of getClass().  That cast is not changing anything related to
getClass().

Casting is usually a questionable thing to do.  That is, you'd better
have a darn good reason for doing it.

With what you've given us to go on, I would bet that ds.getConnection()
is returning null.

John
http://schemaspy.sourceforge.net
dennishancy@eaton.com - 17 Aug 2005 14:46 GMT
I am having similar error messages that look like this:

java.lang.NullPointerException at euwPledge.doGet(Unknown Source) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:787)

Being new to Java, I have a few questions:

- Does the 787 refer to a line number?
- What's the best way to begin debugging this?
- What other information can I post here that would help get to the
root of the problem?

The really odd part is that I had one occasion when the code worked as
it should.  But that was only once.  Not sure if that suggests a code
issue or a configuration issue?

Any suggestions as to what I can look into would be greatly
appreciated.  Thanks.

Dennis Hancy
Eaton Corporation
Cleveland, OH
Roedy Green - 17 Aug 2005 15:58 GMT
>- Does the 787 refer to a line number?
>- What's the best way to begin debugging this?

yes. See
http://mindprod.com/jgloss/runerrormessages.html#NULLPOINTEREXCEPTION
Tor Iver Wilhelmsen - 17 Aug 2005 17:23 GMT
> - Does the 787 refer to a line number?

Yes.

> - What's the best way to begin debugging this?

Look for uses of the . operator; something in front of a . is null.
Try adding some tests for null.
Babu Kalakrishnan - 17 Aug 2005 18:25 GMT
> I am having similar error messages that look like this:
>
[quoted text clipped - 7 lines]
> - What other information can I post here that would help get to the
> root of the problem?

Yes - 787 indeed refers to a line number - but unfortunately it doesn't
tell you where the real problem lies - so no point starting your
debugging from there.

Make sure you compile the application with debugging informaton enabled.
If you're using plain javac for the compilation, the -g switch ought to
do it. If you're using an IDE, you'll need to find out the exact means
to enable it by looking at the documentation. (Most IDEs have it turned
on by default)

In any case, the "Unknown source" message generally means that that the
compilation was done with debugging set to none, and that's something
you don't ever want to do in the development phase of a project. (Very
similar to the try{..some code..} catch (Exception e) {} stuff you see
in a lot of code. In my view, if an exception occurred, you want to know
what it was and figure out why it occurred - no point hiding it)

BK
Andrew Thompson - 17 Aug 2005 18:35 GMT
> ...(Very
> similar to the try{..some code..} catch (Exception e) {} stuff you see
> in a lot of code. In my view, if an exception occurred, you want to know
> what it was and figure out why it occurred - no point hiding it)

Or, to put that in more words (with lots more colors) ..
<http://www.physci.org/codes/javafaq.jsp#stacktrace>

Signature

Andrew Thompson
physci.org 1point1c.org javasaver.com lensescapes.com athompson.info
"We're gonna' fuss and fight till daylight."
Koko Taylor 'Wang Dang Doodle'

Roedy Green - 20 Aug 2005 21:26 GMT
>In any case, the "Unknown source" message generally means that that the
>compilation was done with debugging set to none, and that's something
>you don't ever want to do in the development phase of a project.

Another explanation is that it occurred in Sun's code. You have to
look where you called sun's code. You likely passed it a null
parameter.

Someone pointed out recently that the JDK private JRE has debug turned
on and the public one has it turned off.
Andrea Desole - 18 Aug 2005 09:38 GMT
> I am having similar error messages that look like this:
>
[quoted text clipped - 4 lines]
>
> - Does the 787 refer to a line number?

yes (as everyone else said already)

> - What's the best way to begin debugging this?

if you want to use a real debugger, that can be a bit difficult. You
basically have to debug the entire application server. I have never used
iPlanet, so I don't know how to do that exaactly. The easiest thing I
can recommend is to find in the documentation how to start iPlanet in
debug mode, or how to set the flags used by the server virtual machine
when it's started. If you don't know what flags to use, you can easily
find them in the JDK documentation (search for the Xdebug and Xrunjdwp
options for the java command). If you succeed in starting the virtual
machine with the debug options, you can attach a debugger to it. Which
debugger is your choice.
Anyway, for the moment I would use normal log messages, as you have been
doing so far.

> - What other information can I post here that would help get to the
> root of the problem?

1) John is right: a class cast doesn't affect the getClass method
2) I noticed that in the stack trace you have euwPledge.doGet, instead
of TestClass.foo. I also noticed that in your JSP you call c.foo()
instead of c.foo(String), which means you shouldn't even able to compile
your JSP

So, if I'm not missing anything, I think you should really look at your
code.
If I'm missing something (besides the fact that I would like to know
what) you can try to dump the following values:

((com.netscape.server.jdbc.ConnectionProxy)c).getClass()
c.getClass()

they should give you the same value
dennishancy@eaton.com - 29 Aug 2005 16:53 GMT
In my continued attempts to figure out what's wrong with this, I've
noticed something else.

If I am logged into my application, then I get that nullPointer java
error when I click on the link.

However, if I am Not logged in, and key in the URL of the link directly
into my browser, the information shows up as expected.

Not sure what this means, but thought it might be useful information in
trying to figure this out.

Something is being set when logging out that enables the link to work.
But what could that be??

Dennis

> > I am having similar error messages that look like this:
> >
[quoted text clipped - 40 lines]
>
> they should give you the same value
Andrea Desole - 29 Aug 2005 18:15 GMT
> In my continued attempts to figure out what's wrong with this, I've
> noticed something else.
[quoted text clipped - 10 lines]
> Something is being set when logging out that enables the link to work.
> But what could that be??

If I'm not wrong this is the first time you mention log in and log out,
and a link. What's the value of the url of the link? How does the
application find out what the url is? And waht kind of information is
expected?
The information you gave is a bit incomplete and inconsistent. The
example you gave seems a good idea, but it just doesn't match. Even
assuming that this euwPledge you are calling is something internal in
iPlanet, you are still calling a method from your JSP that doesn't
exist. That might mean that you posted the wrong code, but also that you
have some problems with your classpath.
Maybe you should give one easy, clear, correct, readable piece of code,
with the necessary information.
And, to answer your last question: the way I look at it a relationship
with a log in/log out procedure looks unlikely, but, since I don't know
what is going on, I might (very roughly) guess that something is wrong
in processing some session scoped information that is added when someone
logs in, and is used to get the url that is used to build the link.
John Currier - 30 Aug 2005 02:44 GMT
Did you ever look at what's at line 29 of
helper.DBConnectionHelper.java?  As I said on July 26th, that's the
line that you should be looking at.

John Currier
http://schemaspy.sourceforge.net


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.