-1

This is not the same as NullPointerException because the problem is when it encounters with sql connection.

When I use checkUser() from another class, I get java.lang.NullPointerException at PreparedStatement pstmt = connect.prepareStatement(sql);

I have checked my sql server is running fine, the configs are correct and the getConnection() code make sense. I am really puzzled why it wouldn't connect to the database and throw the pointer exception.

May I please have some suggestions on how to get this working?

public class UserVerification {

  private static Connection connect = null;
  private static String host="localhost";
  private static String database="database";
  private static String username="root";
  private static String password="xxxx";


  public static Connection getConnection(){

   if(connect ==null){
            try{
             Class.forName("com.mysql.jdbc.Driver");
              String conn_string="jdbc:mysql://"+host+"/"+database;
              connect = DriverManager.getConnection(conn_string,username,password);
              return connect;
            }catch(Exception ex){

                ex.printStackTrace();
            }
        }else{
            return connect;
        }
      return connect;
    }

  public User checkUser(String user,String password){

      String sql="SELECT * FROM OFFICER  WHERE OUSERNAME='?' AND PASSWORDHASH=?";
      User u=null;
        try( Connection connect = getConnection(); 
             PreparedStatement pstmt = connect.prepareStatement(sql);
            ){  
             pstmt.setString(1,user);
             pstmt.setString(2,HashGenerator.getMD5Hash(password));
             try (ResultSet rs = pstmt.executeQuery();){
               while(rs.next()){             
                  String uname=rs.getString("USERNAME");        
                  String pass=rs.getString("PASSWORDHASH");     
                  u = new User(uname,pass);
                  break;
              }
             }
        }catch(SQLException ex){
            ex.printStackTrace();   
        }
        return u;
  }
}

StackTrace I get from the above code AND with getConnection() ex.printStactTrace();

org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [LoginServlet] in context with path [/project] threw exception
java.lang.NullPointerException
at UserVerification.checkUser(UserVerification.java:40)
at LoginServlet.doPost(LoginServlet.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Gavin
  • 11
  • 6
  • 1
    *"and the getConnection() code make sense"* No it doesn't. Returning `null` and ignoring the catched exception doesn't make any sense. – Tom Nov 05 '16 at 07:38
  • even if I change the null and try and printStackTrace. The exception is the same, the part has nothing to do with the error I am having. – Gavin Nov 05 '16 at 07:39
  • Do you have the mysql connectivity library included? – Rcordoval Nov 05 '16 at 07:50
  • I have mysql-connector-java-5.1.39-bin.jar in my libraries – Gavin Nov 05 '16 at 07:57
  • 1
    @Thrasher If he didn't it would be a different exception. Don't raise red herrings. – user207421 Nov 05 '16 at 08:27
  • 1
    **Obviously** `connect` is null. There is no other possibility. The basic problem here is that you are catching and ignoring the exception arising out of creating the connection and proceeding as though it hadn't happened. The `getConnection()` method should be declared to throw `SQLException`, and not catch any. NB The `Class.forName()` line has been unnecessary since 2007. – user207421 Nov 05 '16 at 08:44
  • @EJP i am sorry as I am really new to this but can you elaborate what you said? because I looked at the exception and still do not understand where the problem is. getConnection() isn't catching any exceptions. – Gavin Nov 05 '16 at 08:51
  • 1
    @Gavin `getConnection ()` is catching *all* exceptions. Have another look, and consider what happens to the return value variable if an exception is thrown. And then tell us what exception *was* thrown. – user207421 Nov 05 '16 at 08:55
  • @EJP I thought the exception I have now is thrown by the exception from public User checkUser(String user,String passsword). It says Nullpointer at line 40 which is the connect at getConnection(). Like I said earlier even if I remove the exception from getConnection() the same stack track comes up which implies the checkUser() is throwing the exception. – Gavin Nov 05 '16 at 08:58
  • 1
    I am askIng what exception was caught by `catch (Exception)` in `getConnection()`, whose existence you have completely overlooked. **Obviously** a prior exception was caught there, which caused the return value to be null, which caused the subsequent NPE. – user207421 Nov 05 '16 at 09:00
  • @EJP yes I understand your question completely now. But that is what I want to know, what is caught by the getConnection? because even if I return Null from that exception the same stack trace appears. – Gavin Nov 05 '16 at 09:03
  • 1
    No, that's what *I* am asking *you*. **Why** is it returning null? What was the exception that caused it? – user207421 Nov 05 '16 at 09:07
  • what is returning null? the getConnection() is returning null so checkUser cannot get connection. The exception is NullPointer at line 40. I am so confused – Gavin Nov 05 '16 at 09:10
  • Sigh sigh sigh. Your code is returning null to your code, because of an exception, and the null is causing another exception. The question only you can answer is what was the original exception? You have `catch Exception ex) { return null; }`. That is simply not good enough. You are throwing away the information that will solve this problem for you. – user207421 Nov 05 '16 at 09:13
  • NO NO, ok, let say I changed that alright? I will modify it in the code as well. I still get the same stack trace – Gavin Nov 05 '16 at 09:19
  • You can't possibly get the same stack trace from a different catch block. How many times do I have to state that there are two exceptions here? You're asking about the wrong one. – user207421 Nov 05 '16 at 09:25
  • I know that is not possible that is why I have concern on the situation. I am getting the exact stack trace from the above code. – Gavin Nov 05 '16 at 09:27
  • The 'above code' is *wrong.* That's what I've been telling you. You need to *fix* the above code *to print a stack trace from the catch block that returned null*, so we know what exception was caught there, which is what I was talking about 3/4 of an hour ago. Until you do that you are just wasting your own time and everybody else's. – user207421 Nov 05 '16 at 09:28
  • @EJP I finally understand what you meant, you are trying to say print the stack trace from getConnection() to find the problem. I am figuring out how to do that now – Gavin Nov 05 '16 at 09:37
  • Finally you have understood what I told you 43 minutes and six comments ago, – user207421 Nov 05 '16 at 09:39
  • You could have just told me that the printStackTrace from getConnection() is not printing out from the above code – Gavin Nov 05 '16 at 09:41
  • @EJP When I run the java file on my server the url appears to be "localhost/project/WEB-INF/classes/package/UserVerification.java" and I get 404. How do I change it so the url is not that? – Gavin Nov 05 '16 at 09:44

1 Answers1

-1

In getConnection you declare a new.Connection object with the same name connection and return it.So the static field connection is never populated. Remove that declaration and let the assignment for the static connection field. Moreover in the catch few lines later you return null and don't print the stack trace. Try to print that and see what happen

Massimo Petrus
  • 1,881
  • 2
  • 13
  • 26
  • Thanks for the suggestion, I have also changed the code to print stack trace. Same error. (java.lang.NullPointerException) so the getConnection does not catch any exceptions – Gavin Nov 05 '16 at 07:46
  • 1
    Mmm can you post the stack trace? – Massimo Petrus Nov 05 '16 at 07:54
  • I have added it to the question – Gavin Nov 05 '16 at 08:00
  • 1
    ..i meant the full stack trace including first rows – Massimo Petrus Nov 05 '16 at 08:39
  • @Gavin In other words including the exception itself, and also an indication as to which is line 40. – user207421 Nov 05 '16 at 08:41
  • @EJP sorry maybe it was unclear how I explained it. But line 40 is PreparedStatement pstmt = connect.prepareStatement(sql); which suggests the connection is null and cannot be made even though the getConnection() seems correct. – Gavin Nov 05 '16 at 08:44
  • try also to change your connection string with something like this DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=minty&password=greatsqldb"); – Massimo Petrus Nov 05 '16 at 08:52
  • @Massimo Why? He's already supplying the username and password. – user207421 Nov 05 '16 at 08:56
  • it's what MySql says, just to try all the possibilites :) http://dev.mysql.com/doc/connectors/en/connector-j-usagenotes-connect-drivermanager.html – Massimo Petrus Nov 05 '16 at 09:00
  • It's one of two ways of supplying the username and password, and he is using the other one. How would your suggestion change anything? Let alone cure an NPE? – user207421 Nov 05 '16 at 09:01
  • Assumed that the driver is in the CP, i'm wondering that in some way the driver manager is not giving the connection object, maybe the conn string is not the desired one for the specific mysql – Massimo Petrus Nov 05 '16 at 09:03
  • @Massimo *Of course* he is getting an exception creating the connection. My question to you is how is shifting the username and password from the API call to the URL going to change anything? – user207421 Nov 05 '16 at 09:09
  • i'm used to try all possibilities. However, the strange thing is that the exception does not come from the getConnection method – Massimo Petrus Nov 05 '16 at 09:18
  • 'Trying all possibilities' is not the same thing as solving the problem. You haven't answered any of my questions. It is obvious why the exception isn't coming from `getConnection()`: there is nothing there that *prints* a stack trace. *Which is the actual problem* at the moment. – user207421 Nov 05 '16 at 09:27
  • He said he added the exception print, but the problem remains and the exception seems not be printed from there..pls see the whole thread. So, maybe the stack trace is not the only one (i.e. there's some other exceptions not reported here ) ? I don't know. I feel i answered to your question. To be more clear. Maybe aa problem in the driver ? Maybe other ? I don't know. If a way is wrong maybe changing that way can lead to other possibilities. – Massimo Petrus Nov 05 '16 at 09:35
  • I have contributed about 75 comments to exactly the same effect, none of which appears in your answer above. My questions to you remain unanswered. If you don't know the answer you shouldn't be posting one. Guesswork is not appropriate. – user207421 Nov 05 '16 at 09:36
  • The question is why i told him to change conn url, right ? Ok, more explicitily yet . It could change the situation if there are some requirements from the driver to have username or pasword in the conn string. Or either bugs. The only way to exclude this is to try it. Exspecially in a point in which we don't have any stack trace from getConnection or there may be some previous exception (the one in getConnection) that maybe the user don't report, or there may be not It's the answer you needed ? – Massimo Petrus Nov 05 '16 at 09:42