1

Following on from my previous question I have found the culprit in my code is this object

I have an object called "conn" from the class Connection in Java.

In my old code which works there is no highlighting of the objects name. As you can see below.

enter image description here

However in my newer version of code on Eclipse which does not work due to that object being null all the time the object is highlighted.

enter image description here

My DatabaseLogic class

    package org.ari;

//class dependencies
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DatabaseLogic
{
    private static Connection conn;

    public static String openDatabase() throws IOException, SQLException,
            NamingException
    {


        // context class gives naming standards of the surrounding environment
        // of the servlet i.e. the web server ,
        // allowing the servlet to interface with the web servers resources
        Context initialContext = new InitialContext();
        Context envContext = (Context) initialContext.lookup("java:comp/env");
        // servlet looks up for a connection pool called "jdbc/POOL"
        DataSource ds = (DataSource) envContext.lookup("jdbc/POOL");
        // connection is then made/requests to connection pool

        String result = ds.toString();


        try
        {
            conn = ds.getConnection();
        }
        catch (SQLException e)
        {
            System.out.println( e.toString());          
        }


        return result;
    }

    public static void closeDatabase()
    {
        try
        {
            conn.close();
        }
        catch (SQLException e)
        {

        }
    }

    // queryId is the parameter to be used for querying for relevant records
    // - possibly change name to make it less specific e.g. recordid
    public static String getData(String queryId, int requestNumber)
            throws SQLException
    {
        String result = "";
        if (queryId != null)
        {
            try
            {

                if (conn == null)
                { 
                    //result = "We are in here";
                    result = openDatabase(); 
                }

                // prepare a statement for use in query

                Statement stmt = conn.createStatement();
                // query parameratised with queryId
                String qry = "SELECT RECORD_ID, USER_ID, OPERATION_CD, BUSCOMP_NAME, OPERATION_DT, FIELD_NAME, OLD_VAL, NEW_VAL, AUDIT_LOG, ROW_ID, BC_BASE_TBL FROM S_AUDIT_ITEM WHERE RECORD_ID='"
                        + queryId + "'";
                ResultSet results = stmt.executeQuery(qry);
                result = XMLBuilder.xmlBuilder(results, queryId,
                        requestNumber);
                // close the connection
                stmt.close();
                results.close();
            }
            catch (Exception e)
            {
                // log.error("Cannot connect to database :" + e);


            }
        }
        else
        {
            // not sure if ever reached
            result = "The query parameter  is a null value";
        }
        return result;
    }

}

What does this highlighting mean, I am guessing eclipse is treating this object in a different way and this is why this object is no longer functioning as it should.

How do I fix this, any ideas? I have tried restoring my older version of code but this highlighting is still the same.

I am guessing it is some setting somewhere in the IDE.

Thanks

Community
  • 1
  • 1
tomaytotomato
  • 3,788
  • 16
  • 64
  • 119
  • 3
    The IDE just helps you write Java code. What matters is the code, and not how it's highlighted. If there is a problem, it's caused by the code you write, not by how Eclipse highlights it. The fact that it highlights it differently might indicate that it's telling you that you have a potential bug, but without seeing the code, and the stack trace of the exception you get, it's impossible to say. – JB Nizet Dec 24 '12 at 12:12
  • Can you post a working `DatabaseLogic` class? – Azodious Dec 24 '12 at 12:13
  • @JBNizet if you click on the hyperlink in my question it takes you to my previous one where I am wanting to know why this object is null when it should be getting set. Thanks – tomaytotomato Dec 24 '12 at 12:14
  • I will post the class code again. – tomaytotomato Dec 24 '12 at 12:14
  • 2
    So, what's the stack trace of the exception? And please, NEVER `catch (Exception)`, and never ignore an exception like you're doing. You're hiding the problem to yourself, making it very hard to diagnose. – JB Nizet Dec 24 '12 at 12:17
  • http://stackoverflow.com/questions/14020824/nullpointerexception-with-connection-object-creating-sql-statement -- > conn.createStatement() – tomaytotomato Dec 24 '12 at 12:19

1 Answers1

3

So, you get a NullPointerException when executing

conn.createStatement();

This means that conn is null.

Where is conn initialized? Just before, in the call to openDatabase().

How does openDatabase() initialize the variable?

    try
    {
        conn = ds.getConnection();
    }
    catch (SQLException e)
    {
        System.out.println( e.toString());          
    }

The abobe indicates that either ds.getConnection() returns a connection, and conn can't be null (but it is), or conn is null because ds.getConnection() throws a SQLException, but you continue as if nothing happened, just displaying the toString() of the exception that was thrown. The above should be rewritten as the following:

conn = ds.getConnection();

That way, you wouldn't ignore the SQLException. It would propagate to the caller, and would be identified as a SQLException, with a clear error message, indicating where the problem comes from in the code, rather than an obscure NullPointerException happening later, and being much harder to diagnose.

Let the exception propagate, or at the very least, replace the code by:

try {
    conn = ds.getConnection();
}
catch (SQLException e) {
    throw new RuntimeException("Something really bad happened, and it makes no sense to continue further, so I'll throw a runtime exception wrapping the original cause", e);
}

Now you just need to get the stack trace of the SQLException thrown by ds.getConnection(), and understand what it's error message means.


Note that I suspect that the exception is not thrown by conn.createStatement(), but by some other exception that you also ignore in the following:

catch (Exception e)
{
    // log.error("Cannot connect to database :" + e);
}

Once again, don't catch the exception. Let it propagate. By catching it, you make it very hard for yourself to notice the problem, and impossible to diagnose it.

If you can't handle an exception, don't catch it.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks, the runtimeexception message you gave is not appearing in my web server log files or output on the browser. Where does it go? – tomaytotomato Dec 24 '12 at 12:47
  • It goes to the `catch(Exception) { }` block, which catches every possible exception and ignores it, as if nothing bad happened, as I explain in the second part of the answer. – JB Nizet Dec 24 '12 at 12:49
  • but how do i get that to appear on the browser as outputted html? – tomaytotomato Dec 24 '12 at 12:50
  • Let it propagate. Don't catch it. Anywhere. And your web container will generate an Error 500, which usually contains the stack trace of the exception. – JB Nizet Dec 24 '12 at 12:52
  • Ok I am now getting an interesting error which I think indicates its not my servlet but database or JDBC pool . java.sql.SQLException: READ_COMMITTED and SERIALIZABLE are the only valid transaction levels – tomaytotomato Dec 24 '12 at 12:53
  • This message indicates that the pool is configured to use an isolation level that your database doesn't support. Check the pool configuration. – JB Nizet Dec 24 '12 at 12:57
  • I knew it wasnt my code, it was a config problem with the connection pool ! Thanks for all the help. – tomaytotomato Dec 24 '12 at 12:57
  • It's a config problem, but your exception handling is completely broken. Remember: 1. don't catch an exception if you can't handle it. 2. Almost never catch Exception. 3. Never ignore exceptions. 4. If you MUST catch a checked exception but can't handle it, then wrap it into a RuntimeException and throw this runtime exception. Follow these 4 rules, and you'll have a robust, easy to debug application. – JB Nizet Dec 24 '12 at 13:00