Update MySQL table from jsp - mysql

I have these in a jsp file. But these values are not updated in the mysql table. May be it is not commiting. How can i solve this ?
String passc1 = request.getParameter("passc1");
String accid = request.getParameter("accid");
int i = 0;
String sql =
" update customertb "
+ " set passwd = ?"
+ " where acc_no = ?;";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, passc1);
ps.setString(2, accid);
i = ps.executeUpdate();
} catch (Exception e) {
// do something with Exception here. Maybe just throw it up again
} finally {
con.close();
}
Stacktrace
Apr 01, 2012 11:29:02 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [] threw exception [An exception occurred processing JSP page /changepwd_done.jsp at line 81
e.printStackTrace();
} finally {
//con.close();
con.commit();
}
Stacktrace:] with root cause
java.sql.SQLException: Can't call commit when autocommit=true
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:933)
at com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1635)
at org.apache.jsp.changepwd_005fdone_jsp._jspService(changepwd_005fdone_jsp.java:160)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

Catch SQLException and check the console messages:
[...]
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, passc1);
ps.setString(2, accid);
i = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}

Related

How to differentiate between incorrect login credentials and server unavailable using JDBC

I'm writing a program to connect to a MariaDB database via JDBC. With the correct credentials (username/password) it connects fine. But I'm trying to produce the appropriate error messages when it doesn't connect and that's where I have an issue. I get the same exceptions regardless of whether the problem is that the server is unavailable (stopped) or that the credentials are incorrect.
In both cases it gives:
SQL State: 42000
Error Code: -1
Message: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
Cause: java.sql.SQLSyntaxErrorException: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
So I can't explain to my user whether they need to retype their password or contact IT because the server is down, because I can't differentiate between the two.
The SQL state tells me that it could either be syntax error or access rule violation. I couldn't find anything on the error code of '-1'.
How can I make this distinction here?
Edit
I've not had to produce a minimum reproducible example before, so hopefully this is close.
This is a JavaFX FXML project and this is the controller for the login screen. You'll see where I'm testing the credentials and the connection towards the bottom, plus I've commented the specific catch section that I'm struggling with.
public class ControllerLogin extends AnchorPane {
//Initialise java fields
public String UN;
public String PW;
private boolean credentialsAccepted;
//Initialise fx fields
#FXML private TextField username;
#FXML private PasswordField password;
//Initialise fx labels
#FXML private Label userMessage;
//Constructor creates an FXML loader, set its properties and attempts to load the FXML file.
public ControllerLogin() {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("/fxml/LoginScreen.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
}
catch (IOException exception) {
throw new RuntimeException(exception);
}
userMessage.setVisible(false);
}
//Getters for username and password.
public void getUsername(TextField name) {
UN = name.getText();
}
public void getPassword(PasswordField pass) {
PW = pass.getText();
}
//Event actions.
public void run(ActionEvent event) {
userMessage.setVisible(false);
getUsername(username);
getPassword(password);
//Check field inputs.
if (UN.isBlank()) {
userMessage.setText("Username cannot be blank");
userMessage.setVisible(true);
return;
} else if (PW.isBlank()) {
userMessage.setText("Password cannot be blank");
userMessage.setVisible(true);
return;
}
DataSourceFactory loginCheck = new DataSourceFactory();
Connection con = null;
try {
credentialsAccepted = false;
con = loginCheck.createMariaDBPoolDataSource(UN, PW).getConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT CURRENT_USER");
rs.first();
final String currentUser = rs.getString("CURRENT_USER");
if (currentUser.startsWith(UN + "#")) {
credentialsAccepted = true;
}
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println("Statement Error");
System.err.println("SQL State: " + ((SQLException)e).getSQLState());
System.err.println("Error Code: " + ((SQLException)e).getErrorCode());
System.err.println("Message: " + ((SQLException)e).getMessage());
System.err.println("Cause: " + ((SQLException)e).getCause());
return;
}
//The exception below does not tell me the difference between server offline
//and credentials incorrect, which is a problem for me because I want the
//user response message to be different depending on the outcome.
//I am not sure how to make it do what I want.
} catch (SQLException e) {
System.out.println("Login Failure");
System.err.println("SQL State: " + ((SQLException)e).getSQLState());
System.err.println("Error Code: " + ((SQLException)e).getErrorCode());
System.err.println("Message: " + ((SQLException)e).getMessage());
System.err.println("Cause: " + ((SQLException)e).getCause());
return;
}
if (credentialsAccepted) {
try {
Stage homeStage = new Stage();
ControllerHome home = new ControllerHome();
homeStage.setScene(new Scene(home));
homeStage.setTitle("Equipment Management Tool");
homeStage.setResizable(true);
homeStage.setWidth(1625);
homeStage.setHeight(925);
homeStage.setMaximized(true);
homeStage.show();
//Get the current stage (loginStage) and hide it so it disappears once you are logged in
Stage stage = (Stage) getScene().getWindow();
stage.hide();
} catch(Exception e) {
e.printStackTrace();
return;
}
return;
} else {
userMessage.setText("There was an unexpected error");
userMessage.setVisible(true);
return;
}
}
}
This is the data source class:
public class DataSourceFactory {
public DataSource createMariaDBPoolDataSource(String username, String password) {
Properties props = new Properties();
InputStream inputStream;
MariaDbPoolDataSource mariaDbPoolDS = null;
try {
inputStream = getClass().getResourceAsStream("/properties/db.properties");
props.load(inputStream);
mariaDbPoolDS = new MariaDbPoolDataSource();
mariaDbPoolDS.setUrl(props.getProperty("MARIADB_DB_URL"));
mariaDbPoolDS.setLoginTimeout(Integer.parseInt(props.getProperty("MARIADB_DB_LOGIN_TIMEOUT")));
mariaDbPoolDS.setUser(username);
mariaDbPoolDS.setPassword(password);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
return mariaDbPoolDS;
}
}
These are the stack traces returned with incorrect login details and with an uncontactable server, respectively.
java.sql.SQLSyntaxErrorException: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:62)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:153)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.MariaDbPoolDataSource.getConnection(MariaDbPoolDataSource.java:239)
at emtmodule/com.outlook.sensicalapp.emt.ControllerLogin.run(ControllerLogin.java:93)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8890)
at javafx.controls/com.sun.javafx.scene.control.behavior.TextFieldBehavior.fire(TextFieldBehavior.java:184)
at javafx.controls/com.sun.javafx.scene.control.behavior.TextInputControlBehavior.lambda$keyMapping$62(TextInputControlBehavior.java:330)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4070)
at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2121)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2597)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:547)
at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:971)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.sql.SQLSyntaxErrorException: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:62)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:171)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.pool.Pool.getConnection(Pool.java:413)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.MariaDbPoolDataSource.getConnection(MariaDbPoolDataSource.java:237)
... 58 more
java.sql.SQLSyntaxErrorException: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:62)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:153)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.MariaDbPoolDataSource.getConnection(MariaDbPoolDataSource.java:239)
at emtmodule/com.outlook.sensicalapp.emt.ControllerLogin.run(ControllerLogin.java:93)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8890)
at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3862)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2590)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.sql.SQLSyntaxErrorException: No connection available within the specified time (option 'connectTimeout': 5,000 ms)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:62)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:171)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.internal.util.pool.Pool.getConnection(Pool.java:413)
at org.mariadb.jdbc#2.6.0/org.mariadb.jdbc.MariaDbPoolDataSource.getConnection(MariaDbPoolDataSource.java:237)
... 58 more
Note: Because this is a work in progress there are a mix of different exception handling styles here. They will be fixed once the thing is working properly.
After a lot of Google-foo I was able to find the source of this particular issue.
It is a (now) known bug of MariaDB Connector/J.
Bug Report: https://jira.mariadb.org/browse/CONJ-885 and
https://github.com/mariadb-corporation/mariadb-connector-j/pull/172
A fix has been created and is now part of version 3.0.1-beta and 3.0.
2-rc of the connector.

Exception despite catch block

So I have the following pieces of code and like it says in the title, despite expecting the exception and catching it, it is escalated. This is gonna be a game and my whole communication to the gui about invalid turn is based on exceptions, so if this persists with my custom exceptions, i'm in trouble.
#Test
public void testLoadMoneyCards() {
File file = new File(MONEY_CARDS_PATH);
try {
System.out.println(ioController.loadCards(file));
} catch (IOException e) {
e.printStackTrace();
}
}
private Card parseCard(String[] properties,int id) throws IOException {
if (properties[0].equals("Wertung")) {
Score score = new Score();
score.setId(id);
try {
score.setType(Integer.parseInt(properties[1]) == 1 ? ScoreRound.FIRST : ScoreRound.SECOND);
} catch (NumberFormatException e) {throw new IOException("Card object could not be parsed");}
return score;
} else if (!properties[0].equals("Waehrung")) {
Money card = new Money();
card.setId(id);
card.setColor(parseMoneyColor(properties[0]));
try {
card.setValue(Integer.parseInt(properties[1]));
} catch (NumberFormatException e) {throw new IOException("Card object could not be parsed");}
return card;
}
return null;
}
java.io.IOException: Card object could not be parsed
at controller.IOController.parseCard(IOController.java:145)
at controller.IOController.loadCards(IOController.java:82)
at controller.IOControllerTest.testLoadMoneyCards(IOControllerTest.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.base/java.lang.Thread.run(Thread.java:835)

java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String

Exception is java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String
Printthis>>>>>>userName=user1&passKey=12345678
POST Response Code :: 200
jsonObj>>>>>>>>>>>>>>>>>>{"response":{"roleTitle":"Parent","roleId":146,"passKey":"12345678","id":1,"userName":"user1"},"errorCode":null,"error":false,"message":null}
Jan 04, 2018 4:33:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring-dispatcher] in context with path [/balihans] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String] with root cause
java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String
at com.swasth.general.controller.SwasthController.postLogin(SwasthController.java:2274)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
Here is my postLogin code
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView postLogin(HttpServletRequest request,HttpServletRequest response) throws IOException, JSONException {
ModelAndView addmodel = new ModelAndView("login");
String uri = "http://localhost:8080/login/api/";
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
String userName = request.getParameter("userName");
String passKey = request.getParameter("passKey");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("userName=" + userName + "&passKey=" + passKey).getBytes());
System.out.println("Printthis>>>>>>" + "userName=" + userName + "&passKey=" + passKey);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer responses = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responses.append(inputLine);
}
//System.out.println("responses>>>>>>>>>>>"+responses);
String str = responses.toString();
JSONObject jsonObj = new JSONObject(str);
System.out.println("jsonObj>>>>>>>>>>>>>>>>>>"+jsonObj);
String res = (String)jsonObj.get("errorCode");
// build a JSON object
List<PatentLoginInfo> PatentLoginInfoArray = new ArrayList<PatentLoginInfo>();
ObjectMapper mapper = new ObjectMapper();
RestTemplate restTemplate = new RestTemplate();
String res11 = (String)jsonObj.get("response");
String login = restTemplate.getForObject(uri, String.class);
JSONObject obj = new JSONObject(login);
JSONObject objects = obj.getJSONObject(res11);
System.out.println("objects>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+objects);
PatentLoginInfo patentLoginInfo = mapper.readValue(objects.toString(), PatentLoginInfo.class);
PatentLoginInfoArray.add(patentLoginInfo);
addmodel.addObject("theLogin", PatentLoginInfoArray);
if (res.equals("BVE000403")) { // success
addmodel = new ModelAndView("index");
addmodel.addObject("login Unsucessfull","Password is invalid");
return addmodel;
}
else{
addmodel = new ModelAndView("AnswerQuestion");
addmodel.addObject("login sucessfull");
return addmodel;
}
}
JSONObject has a specific inner constant for representing null objects: JSONObject.NULL
Before casting your JSONObject to a String, you may verify if it equals the NULL constant. Here an example:
//put words from JSON to array
for (int i = 0; i<wordsInJSONArray.length(); i++) {
Object o = wordsInJSONArray.get(i);
if (!JSONObject.NULL.equals(o)) {
String word = (String) o;
this.wordsArray[i] = word;
}
}
You could also use isNull()
Returns true if the associated value for the specified name is JsonValue.NULL. More here
So your code would be:
String code = jsonObj.isNull("errorCode") ? "" : jsonObj.getJsonString("errorCode");
It seems that "errorCode" is null from your print :
{"roleTitle":"Parent","roleId":146,"passKey":"12345678","id":1,"userName":"user1"},"errorCode":null,"error":false,"message":null}
So you need to check on null before casting to string
String res = (String)jsonObj.get("errorCode");
so apply the following validation and it will work :
String res = null;
if (!org.json.JSONObject.NULL.equals(jsonObj.opt("errorCode")) && jsonObj.getString("errorCode") != null) {
res = jsonObj.getString("errorCode");
}

Facing null pointer exception while using mockito

I am using Mockito for testing. Getting nullpointerexcpetion with message as null
TestMethod
// build request
RequestObject requestObject = new RequestObject();
String accountNumber = "12345628928";
String accountId = "dc23362e-f46f-4cce-b49a-cd10d737f483";
requestObject.setAccountId(accountId);
requestObject.setAccountNumber(accountNumber);
String firstName = "test";
String middlename = "test";
String lastName = "test";
String gender = "M";
String dob = "01-JUN-2016";
String emailaddress = "test#test.com";
String prefferedLanguageCode = "1";
String preffredname = "test";
String prefix = "Mr.";
String suffix = "Jr";
String minor = "1";
String deathDate = "09-SEP-2009";
String deathInformationDate = "14-OCT-2010";
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setMiddleName(middlename);
customer.setLastName(lastName);
customer.setGender(gender);
customer.setDob(dob);
customer.setEmail(emailaddress);
customer.setPreferredLanguageCode(prefferedLanguageCode);
customer.setPreferredName(preffredname);
customer.setPrefix(prefix);
customer.setSuffix(suffix);
customer.setMinor(minor);
customer.setDeathDate(deathDate);
customer.setDeathInformedDate(deathInformationDate);
requestObject.setCustomer(customer);
IdObject idObject = new IdObject();
idObject.setAccountId(UUID.fromString(accountId));
List<PersonAccount> personAccount = new ArrayList<PersonAccount>();
PersonAccount personAccount1 = new PersonAccount();
personAccount1.setFirstName("First name in testing");
personAccount.add(personAccount1);
// mock external call
when(sessionFactory.openSession()).thenReturn(session);
when(session.beginTransaction()).thenReturn(transaction);
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);
when(query.list()).thenReturn(personAccount);
when(query.executeUpdate()).thenReturn(1);
// Call the testing method
idObject = customerDAOImpl.updateCustomerRecord(requestObject);
//check the assertion
assertEquals("dc23362e-f46f-4cce-b49a-cd10d737f483", idObject.getAccountId().toString());
// verify the mock call
verify(customerDAOImpl, times(1)).updateCustomerRecord(requestObject);
and my
UpdateMethod
`
private void updateAccountInformation(RequestObject requestObject, Session session)
throws CustomerDataException{
try{
Query queryForPersonAccount = session.createQuery(SQLConstants.FETCH_PERSON_ACCT);
queryForPersonAccount.setParameter(Constants.ACCOUNTID, UUID.fromString(requestObject.getAccountId().toUpperCase()));
#SuppressWarnings("unchecked")
List<PersonAccount> listpersonAccount = (List<PersonAccount>) queryForPersonAccount.list();
if (CollectionUtils.isNotEmpty(listpersonAccount)) {
PersonAccount personAccount = listpersonAccount.get(0);
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);
updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase()));
updateQuery.setParameter(Constants.UPDATED_BY_NAME, Constants.PCF);
updateQuery.setParameter(Constants.END_TIMESTAMP,DateUtil.dateDDMMMYY());
updateQuery.executeUpdate();
updatePersonAccount(session,personAccount, requestObject);
}else{
throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
}
}catch(Exception ex)
{
LOGGER.error(Constants.PATIENT_FETCH_EXCEPTION, ex);
throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
}
}`
I am getting nuppointerexception at line updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase())).
I can see the accountID is available in the requestObject when I debug.
Following is the stacktrace. Help is apprecited :)
ava.lang.NullPointerException: null
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateAccountInformation(CustomerDAOImpl.java:312)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomer(CustomerDAOImpl.java:285)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerInformations(CustomerDAOImpl.java:180)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerRecord(CustomerDAOImpl.java:141)
at com.cardinalhealth.chh.dao.CustomerDAOImplTest.testUpdateCustomerRecordforCustomerObject(CustomerDAOImplTest.java:452)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Your stubbing of session.createQuery:
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);
And what your code actually calls right before you get the exception:
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);
So createQuery is stubbed to return a query when called with a different constant.
Meaning your production code will return null from createQuery and the next line then throws your NPE.

RESTeasy Database connection: NullPointer

I have a RESTeasy service thats running on JBOSS AS 7, that is trying to create a connection with a local database (mysql server).
The data source is properly defined in the JBOSS management and connects fine (a JSF app can connect fine with it and it can modify the database), however when I try to connect in my RESTeasy service, it gives me a nullPointerException and I can't seem to figure out why. kumonobs is the database in question. The error occurs in the persist method, which is called through a post request. Any help would be much appreciated, if any additional information is needed please ask!
#Path("/RSAndroid")
#ApplicationScoped
public class HelloWorldResource implements Serializable{
#Resource(mappedName = "java:jboss/datasources/kumonobs")
private static DataSource dataSource;
private static ArrayList<Student> students = new ArrayList<Student>();
#GET()
#Produces("text/plain")
public String sayHello() {
return stringStudents(students);
}
#POST()
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String postStudent(#FormParam("Student ID") String student){
Date date = new Date();
Student kumonstudent = new Student(student, date);
studentCheck(kumonstudent);
System.out.println(kumonstudent.toString());
return "OK";
}
public String stringStudents(ArrayList<Student> s){
String students = "";
for(Student student : s){
students += student.toString();
}
return students;
}
public void studentCheck(Student student){
boolean checkIn = true;
int count = 0;
for(Student s : students){
count++;
//If Student has been found in the list.
if(s.getStudentID().equals(student.getStudentID())){
//remove the student from the list.
students.remove(count-1);
// ** DO DATABASE STUFF HERE FOR REMOVING STUDENT **
checkIn = false;
break;
}
}
//If student needs to be checked in, add to list.
if(checkIn){
System.out.println(student.getDate());
students.add(student);
// ** DO DATABASE STUFF HERE FOR ADDING STUDENT **
persist(student);
}
}
//Insert student into database table.
public void persist(Student student) {
PreparedStatement stmt = null;
Connection connection = null;
try {
try {
connection = dataSource.getConnection(); //ERROR OCCURS HERE NULLPOINTER
try {
System.out.println("Fourth");
stmt = connection.prepareStatement(
"INSERT INTO checkin VALUES (?, ?)");
stmt.setString(1, "A00105010");
stmt.setString(2, "Sample Name");
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
} finally {
if (connection != null) {
connection.close();
}
}
} catch (SQLException ex) {
System.out.println("Error in persist ");
ex.printStackTrace();
}
}
}
Stack
14:29:22,040 INFO [stdout] (http--0.0.0.0-8080-1) 2012-11-06
14:29:22,040 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host]. [/AndroidRS].[Resteasy]] (http--0.0.0.0-8080-1) Servlet.service() for servlet R
esteasy threw exception: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:340) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:214) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:190) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:540) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:502) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:119) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50) [resteasy-jaxrs-2.3.2.Final.jar:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_27]
Caused by: java.lang.NullPointerException
at org.jboss.samples.rs.webservices.HelloWorldResource.persist(HelloWorldResource.java:92) [classes:]
at org.jboss.samples.rs.webservices.HelloWorldResource.studentCheck(HelloWorldResource.java:81) [classes:]
at org.jboss.samples.rs.webservices.HelloWorldResource.postStudent(HelloWorldResource.java:44) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_27]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_27]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_27]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_27]
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:155) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:257) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:222) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:211) [resteasy-jaxrs-2.3.2.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:525) [resteasy-jaxrs-2.3.2.Final.jar:]
... 19 more
Found the solution, instead of the Annotation to the datasource use:
String strDSName = "java:jboss/datasources/thenamehere";
ctx = new InitialContext();
dataSource = (javax.sql.DataSource) ctx.lookup(strDSName);