Null pointer exception. How my connection object is pointing to null - java

The stacktrace
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1952)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1795)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at Store.<init>(Store.java:12)
at RegisterServlet.doGet(RegisterServlet.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:492)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Sep 01, 2020 9:06:08 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/Registration] threw exception
java.lang.NullPointerException
at Store.insertuser(Store.java:31)
at RegisterServlet.doGet(RegisterServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:492)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Store {
Connection connection;
Store() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String username = "sa";
String password = "123456abcd";
String url = "jdbc:sqlserver://localhost;databaseName=Register";
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean insertuser(String string1, String string2, String string3, String string4, String string5) throws SQLException{
String sql = "insert into dbo.Usertable values(?,?,?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(sql);//this is the place where connection is null
pstmt.setString(1, string1);
pstmt.setString(2, string2);
pstmt.setString(3, string3);
pstmt.setString(4, string4);
pstmt.setString(5, string5);
int i = pstmt.executeUpdate();
if (i > 0) {
return true;
}
return false;
}
}
i have a class store. I connect jdbc in init. I insert values in usertable in a method insertuser. My connection object is pointing to null. My usertable has five varchar values in a database called Register. Why my connection object is pointing to null.I have jdbc jar connected to my classpath.

If the Store constructor encounters any exception, it will print a stacktrace and return a partially constructed Store object with a null in the connection field.
That would explain what you are seeing. But we can't tell you the cause of the exception you are catching without seeing the (complete) stacktrace. Typical explanations for this kind of thing include:
Database driver JAR not the classpath (correctly)
Incorrect database driver JAR
Incorrect database credentials
Incorrect database host or port information
Network problems
Things you could fix:
As commenters pointed out, the exception handling in your constructor is broken. If you get an exception while setting up the connection, the constructor should terminate with an exception. The caller needs to deal with it, or allow it to propagate.
If you use DriverManager.getConnection you shouldn't need to use Class.forName to load the JDBC driver. The DriverManager infrastructure will find the driver for itself, based on what the jdbc URL says.

You need to add the jar file containing the class com.microsoft.sqlserver.jdbc.SQLServerDriver to your war file's WEB-INF/lib folder.

Related

Cassandra Exception : #Table annotation not found on the class

I am new to cassandra database. I am trying to map a table to a java class.
My java class:
#Table("user")
public class User implements Serializable
{
#PrimaryKey
#Column(value = "id")
private int id;
#Column(value = "first_name")
private String firstName;
//setters and getters
}
Dao class:
public class UserDaoImpl {
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("agtr_api");
MappingManager manager = new MappingManager(session);
Mapper<User> mapper = manager.mapper(User.class);
public User getUserById(int id){
User u = mapper.get(id);
return u;
}
}
When i run my application on server, It throws following exception:
SEVERE: Servlet.service() for servlet [spring] in context with path
[/aggregator-api] threw exception [Request processing failed; nested
exception is java.lang.IllegalArgumentException: #Table annotation was
not found on class com.data.User] with root cause
java.lang.IllegalArgumentException: #Table annotation was not found on
class com.data.User at
com.datastax.driver.mapping.AnnotationChecks.getTypeAnnotation(AnnotationChecks.java:43)
at
com.datastax.driver.mapping.AnnotationParser.parseEntity(AnnotationParser.java:76)
at
com.datastax.driver.mapping.MappingManager.getMapper(MappingManager.java:226)
at
com.datastax.driver.mapping.MappingManager.mapper(MappingManager.java:182)
at com.etl.aapi.common.dao.UserDaoImpl.(UserDaoImpl.java:19)
at
com.etl.aapi.common.controller.UserController.a(UserController.java:13)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
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:218)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
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:958)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
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(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
You can declare also you keyspace name. Try to use the complete syntax as below:
#Table(keyspace = "yourKeyspace", name = "yourTable")
The "#Annotation" error is misleading as you rightly guess and the exception does not directly tell what is the actual error. The underlying problem would always be in your Domain/Model class fields/columns definition such as column name missing, miss match etc, always watch out your Domain/Model class.
Besides, If you use Achilles library and #Table annotation from Achilles, you will not get correct error. As a workaround you can additionally use #Table annotation from DataStax driver which will try to throw you more details in the exception stack trace.

Jasper Reports Dynamic Reports - DRException in HTTPServlets [duplicate]

This question already has answers here:
What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?
(15 answers)
Closed 4 years ago.
I have a servlet that calls the Jasper report class.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ReportGeneratorModel.generateReport();
response.sendRedirect("report.jsp");
}
The ReportGeneratorModel calls a MYSQL database and then generates a report.
public static void generateReport() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cleanhandsreport?"+"user=Manager&password=PASSWORD");
} catch (SQLException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
JasperReportBuilder report = DynamicReports.report();//a new report
report
.columns(
Columns.column("HospitalID", "HospitalID", DataTypes.stringType()),
Columns.column("GroupID", "GroupID", DataTypes.stringType()),
Columns.column("HandWashViolation", "HandWashViolation", DataTypes.stringType()))
.title(//title of the report
Components.text("CleanHands Report")
.setHorizontalAlignment(HorizontalAlignment.CENTER))
.pageFooter(Components.pageXofY())//show page number on the page footer
.setDataSource("SELECT HospitalID, GroupID, Time, HandWashViolation FROM report",
connection);
try {
//show the report
report.show();
//export the report to a pdf file
report.toPdf(new FileOutputStream("report.pdf"));
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I am receiving the following error
Jan 31, 2015 2:56:44 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [rbccps.cleanhands.report.controller.ReportHomeServletController] in context with path [/CleanHandsReport] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: net.sf.dynamicreports.report.exception.DRException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at rbccps.cleanhands.report.controller.ReportHomeServletController.doPost(ReportHomeServletController.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
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)
I have all the jar files from the dynamicreports-4.0.0/lib folder and also the dynamicreports-core-4.0.0.jar in my Classpath.
When I try the report as an stand alone Java Application, everything works fine.
I tried to add some logs in the generateReport() method. None of them is getting printed, even though they are placed at the top of the method.
Any pointers on the problem is much appreciated.
I got the web application running. The problem was with the jar file placement. For a web-app, all the jars should be placed within the WEB-INF/lib directory for Tomcat to read/recognize the jars.
I Kindly request the Admins to CLOSE the question. Cheers.

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException while deleting a record in mysql

Following code is raising Syntax Error exception
I was using Ajax calls in the back end to do CRUD operations on tables
public class CrudDao {
private Connection connection;
private String table;
public CrudDao(Connection con, String table) {
this.connection = con;
this.table = table;
}
public void deleteUser(int RECORDID) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("delete from " + table
+ "where USERID=?");
preparedStatement.setInt(1, RECORDID);
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
}
}
}
In the above code i have written only delete method which is throwing the com.mysql.jdbc.exceptions.MySQLSyntaxErrorException
the trace of the exception is
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USERID=102' at line 1
{"Result":"OK"}
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3176)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1153)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303)
at com.symp.CrudDao.deleteUser(CrudDao.java:33)
at com.symp.CRUDController.service(CRUDController.java:82)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
You need to have space between table name and your where clause.
"delete from " + table + " where USERID=?"
Currently your sql script looks like
delete from tablenamewhere USERID=102
try changing
PreparedStatement preparedStatement = connection
.prepareStatement("delete from " + table
+ "where USERID=?");
to
PreparedStatement preparedStatement = connection
.prepareStatement("delete from " + table
+ " where USERID=?");
Your table name and the keyword where were running together with no space between!

NullPointerException unstoppable

I am currently working on a small addresstable with vaadin, just to get to know vaadin a little. I have run into a problem, where I want to sort the entries of my table manually. The problem is, that I get a NullPointerException when i try to do this:
item.getItemProperty(Columns.NAME).getValue()
I have tried a few things here. I checked item and item isn't null, neither is item.getItemProperty(Columns.NAME) null. So when I try to make an if I still get a NullPointerException
if(item.getItemProperty(Columns.NAME).getValue() == null){}
The value is null and I understand that, but I want to give this value to an other item and I have no idea how to.
SEVERE: Servlet.service() for servlet [com.example.addresstable.AddresstableUI$Servlet] in context with path [/Addresstable] threw exception [com.vaadin.server.ServiceException: java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.vaadin.data.util.IndexedContainer$IndexedContainerProperty.getValue(IndexedContainer.java:898)
at com.example.addresstable.AddressTable.addAddressToTable(AddressTable.java:114)
at com.example.addresstable.AddresstableUI.init(AddresstableUI.java:26)
at com.vaadin.ui.UI.doInit(UI.java:639)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1402)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:305)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
IndexedContainer's Items are IndexedContainerItem.
When call it's getItemProperty the result is never null:
#Override
public Property getItemProperty(Object id) {
return new IndexedContainerProperty(itemId, id);
}
But when you call Property's getValue it may be null if there is no itemId or propertyId:
#Override
public T getValue() {
return (T) items.get(itemId).get(propertyId);
}
Probably it is a Vaadin bug: link
EDIT
If you want to check the container contains the item, you can do this:
public class MyIndexedContainer extends IndexedContainer {
#Override
public Item getUnfilteredItem(Object itemId) { // make it public
return super.getUnfilteredItem(itemId);
}
}
then
Table table = new Table();
MyIndexedContainer mic = new MyIndexedContainer();
table.setContainerDataSource(mic);
//...
// check that the container contains the item
if (mic.getUnfilteredItem(item) != null) {
//...
}

No Database selected SQLException using Datasource

I have created a webapp using servlets. I am establishing a connection to a MySQL database using a DataSource object and get the following stacktrace when I load the webpage:
java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2832)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2781)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1569)
at uk.co.morleys.TestimonialService.countTestimonials(TestimonialService.java:106)
at uk.co.morleys.TestimonialService.getPaginationDetails(TestimonialService.java:122)
at uk.co.morleys.HomeController.doGet(HomeController.java:77)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This is the TestimonialService.java file:
public class TestimonialService {
ResultSet rs;
DataSource ds;
public TestimonialService(){
rs = null;
ds = DataSourceFactory.getMySQLDataSource();
}
public int countTestimonials() throws SQLException{
int count = 0;
try(Connection con = ds.getConnection()){
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM morleys_testimonial WHERE isActive=1");
while(rs.next()){
count = rs.getInt(1);
}
}catch(SQLException e){
e.printStackTrace();
}
return count;
}
}
This is the DataSourceFactory.java where I establish a connection to the database:
public class DataSourceFactory {
public static DataSource getMySQLDataSource() {
MysqlDataSource mysqlDS = null;
try {
mysqlDS = new MysqlDataSource();
mysqlDS.setURL("jdbc:mysql://hostname/");
mysqlDS.setDatabaseName("dbname");
mysqlDS.setUser("user");
mysqlDS.setPassword("password");
} catch (Exception e) {
throw new IllegalStateException(e);
}
return mysqlDS;
}
}
Question Am I not selecting the database with setDatabaseName()? If not how do I do this?
Why dont you simply try this
mysqlDS.setURL("jdbc:mysql://hostname/dbname");
instead of
mysqlDS.setDatabaseName("dbname");
Are you providing port number along with the hostname? If not try giving portnumber as well.
Additionally make sure you have Mysql JDBC Driver
You can follow any of these tutorial for creating MysqlDataSource:
http://www.journaldev.com/2509/jdbc-datasource-example-oracle-mysql-and-apache-dbcp-tutorial
or
http://www.herongyang.com/JDBC/MySQL-JDBC-Driver-DataSource.html

Categories

Resources