I am creating a web application with JDBC. I have added my connector .jar file to the Tomcat/lib folder. I configured context.xml in META-INF and web.xml. But when I run my application I get this error. I can not figure out the reason of it. Maybe, some connection problems. So I would be very grateful if you helped me with that.
Servlet:
#WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DataSource ds;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
String url = "jdbc:mysql://localhost:3306/mysql/ebookshop";
String user = "***";
String pwd = "***";
try {
// Step 1: Create a database "Connection" object
// For MySQL
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ebookshop");
//
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = ds.getConnection(); // <<== Check
// For MS Access
// conn = DriverManager.getConnection("jdbc:odbc:ebookshopODBC");
// Step 2: Create a "Statement" object inside the "Connection"
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "SELECT * FROM books WHERE author = "
+ "'" + request.getParameter("author") + "'"
+ " AND qty > 0 ORDER BY author ASC, title ASC";
// Print an HTML page as output of query
out.println("<html><head><title>Query Results</title></head><body>");
out.println("<h2>Thank you for your query.</h2>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result
int count = 0;
while(rset.next()) {
// Print a paragraph <p>...</p> for each row
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
++count;
}
out.println("<p>==== " + count + " records found ====</p>");
out.println("</body></html>");
} catch (SQLException | NamingException | ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
out.close();
try {
// Step 5: Close the Statement and Connection
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
context.xml:
<Context antiJARLocking="true" path="/DBConnectionPoolTest">
<Resource name="jdbc/ebookshop"
auth="Container"
type="javax.sql.DataSource"
username="***" password="v"
driverclassname="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/ebookshop"
maxactive="10"
maxidle="4" />
</Context>
pom.xml:
<display-name>ebookshop</display-name>
<resource-ref>
<description>DB Connection Pool</description>
<res-ref-name>jdbc/ebookshop</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Eclipse output:
SEVERE: Servlet.service() for servlet [servlets.QueryServlet] in context with path [/ebookshop] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
at org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
at servlets.QueryServlet.doGet(QueryServlet.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Related
So thanks to the advices bellow I changed my first approach of using statements to using Prepared Statements , I also separated the verifyUser method from the ConnectDB to put it in a new user class (which is asked in my assignment).
Now I don't any NPE anymore but another one which is the Class Not Found Exception for the MySQL JDBC Driver.
The code is as follow for the Users class :
public class Users {
private String login;
private String password;
public Users(String login, String password) {
this.login = login;
this.password = password;
}
public String getUsername() {
return login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String login) {
this.login = login;
}
public boolean verifyUser(String login, String password) throws SQLException {
ConnectDB cdb = new ConnectDB();
Connection cn = DriverManager.getConnection(cdb.url, cdb.login, cdb.password);
PreparedStatement ps = cn.prepareStatement("SELECT password FROM users WHERE login LIKE ? ");
ps.setString(1,username);
ResultSet rs=ps.executeQuery();
rs.next();
if (rs.getString(2).equals(password)) {
System.out.println("TEST");
return true;
}
else
return false;
}
}
This is my ConnectDB class :
public class ConnectDB {
String url = "jdbc:mysql://localhost:3306/entreprise";
String login = "root";
String password = "kamoulox369";
Connection connection = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
public void getConnection() {
try {
Class.forName("com.example.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, login, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
And to put it all together , where it is used in the Servlet :
private void versIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
String login = request.getParameter("user");
String password = request.getParameter("password");
Users user = new Users(login,password);
ConnectDB cdb = new ConnectDB();
cdb.getConnection();
if (user.verifyUser(login, password)) {
RequestDispatcher rd = sc.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
And of course the Error I'm getting :
java.lang.ClassNotFoundException: com.example.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1138)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at com.example.ConnectDB.getConnection(ConnectDB.java:16)
at com.example.Servlet.versIndex(Servlet.java:111)
at com.example.Servlet.doPost(Servlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1388)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/entreprise
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at com.example.Users.verifyUser(Users.java:36)
at com.example.Servlet.versIndex(Servlet.java:113)
at com.example.Servlet.doPost(Servlet.java:41)
There’s nothing simple about servlets or jdbc. They’re both error-prone.
You have a concurrency issue, resource issues where you’re not closing anything (including stranding connections), and also a sql injection vulnerability.
Using static members here is disastrous. Each request executes on a different thread and they will all overwrite objects being used by other threads. Each request should be handled using local variables.
Database connections never get closed, your database will run out of connections and stop working at some point. Close all jdbc objects when you’re done with them.
Concatenating user-entered input into the sql you run allows the user to get in without a valid password or run arbitrary sql. Use PreparedStatement.
I am trying to display all users usernames from a Cassandra database using an AJAX script in the jsp page.This would display a list of the users usernames when a view all button is clicked. However the Server throws a Null pointer exception on Session session = cluster.connect("");
java.lang.NullPointerException
User.searchAll(User.java:87)
Search.doGet(Search.java:82)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Model
public class User {
Cluster cluster;
public User() {
}
public java.util.LinkedList<ProfileBean> searchAll(){
Session session = cluster.connect("instagrim");
LinkedList<ProfileBean> profileBeanList = new LinkedList();
String cqlQuery = "select * from userprofiles";
PreparedStatement ps = session.prepare(cqlQuery);
ResultSet rs;
BoundStatement bs = new BoundStatement(ps);
rs = session.execute(bs.bind());
if(rs.isExhausted()){
System.out.println("Profile not found");
}
else
{
for (Row row : rs){
ProfileBean profile = new ProfileBean();
profile.setLogin(row.getString("login"));
profileBeanList.add(profile);
}
}
session.close();
return profileBeanList;
}
Servlet
public class Search extends HttpServlet {
Cluster cluster = null;
public void init(ServletConfig config)
{
cluster = CassandraHosts.getCluster();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User us = new User();
String output ="";
LinkedList<ProfileBean> profileBeanList = new LinkedList();
profileBeanList = us.searchAll();
for (int i=0;i<profileBeanList.size();i++)
{
output="<p>"+profileBeanList.get(i).getLogin() +"</p>";
}
response.getWriter().write(output);
RequestDispatcher rd = request.getRequestDispatcher("search.jsp");
rd.forward(request,response);
}
cluster is null, therefore it does not have a connect method. The system lets you know about the situation with the error message.
The solution is to make sure that cluster is properly initialized before you try to connect.
I have this jsp document (below). Basically, when user types in the textbox, I want to show an error if the username exists in the database/ length<5, etc.
I want these errors to be simultaneously displayed without any refresh through jQuery/AJAX. I did this but it doesn't seem to be working. Here, CheckAvailability and Success are servlets and CheckAVailability checks the existence in database.
the JSP file:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.11.3.js"></script>
<script>
$(document).ready(function() {
$('#username').keyup(function() {
var name = $('#username').val();
$.get('CheckAvailability?username='+name,function(responseText){
$('#status').text(responseText);});});
</script>
</head>
<body>
<form id="login_form" ><input type="text" placeholder="username" name="username" class="style-4" required="required" action="Success"/>
<div id="status"> </div>
CheckAvailability Servlet
public class CheckAvailability extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn=null;
Statement s=null;
ResultSet rs=null;
PreparedStatement ps;
try {
//make connection
String userid = request.getParameter("username");
String arr;
Class.forName("oracle.jdbc.OracleDriver");
if (userid.equals("")) {
arr = "Error: User name cannot be empty";
} else if(userid.length()<5){
arr="Error: Username cannot be less than 5 characters.";
}
else
{
String table="user1.app_users";
String p = "alpha";//database password
String query = "select userid from " + table + " where userid='" + userid + "'";
String url = "jdbc:oracle:thin:system/" + p + "#localhost:1521:XE";
conn = DriverManager.getConnection(url);
s = conn.createStatement();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
if (!rs.next()) {
arr="UserID <b>" + userid + "</b> is available.";
} else {
arr= "Error: UserID <b>" + userid + "</b> is already in use.";
}
}
response.setContentType("text/plain");
response.getWriter().write(arr);
}catch (SQLException se) {
out.println("Error ->" + se.getMessage());
} catch(ClassNotFoundException ce)
{
out.println("Error ->" + ce.getMessage());
}finally {
out.close();
}
}
}
But this isn't displaying anything as I type in the text box. The servlet did fire on hitting on submit. What didn't happen was that the text didn't display alongside. The code executes, no error in my IDE on that. I can't exclusively run the servlet, it gives the error: 'HTTP method GET is not supported by this URL', i.e. when I run it with parameters. I took the input inside as in, String username="user12", and that didn't run either. Can anybody point out my mistake? I'm new to jQuery/AJAX.
This worked for me:
$(document).ready(function() {
$('#userid').keyup(function(event) {
var user=$('#userid').val();
$.get('CheckValidity',{username:user},function(responseText) {
$('#status').text(responseText);
});
});
});
Had to use a different JQuery.
Overrride doGet, because javax.servlet.http.HttpServlet doesn't have any processRequest method.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("hi " + req.getParameter("username"));
}
Read this
Anyway.. how are you declaring your servlet? Through annotations? In web.xml? And what's the URL pattern?
if using web.xml:
<servlet>
<servlet-name>CheckAvailability Servlet</servlet-name>
<servlet-class>your.package.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability Servlet</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
if using annotations:
#WebServlet("/CheckAvailability")
public class Serv extends HttpServlet {
// ...
}
I am trying to insert some values into an Oracle Database 10g Express Edition retrieved through a form. Here is the code,
package com.cid_org.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Collection;
//import java.util.Iterator;
import java.util.Map;
public class CrimeReportPOJO {
private Map<String,String[]> complaintFormData;
private Connection connection;
private int complaintID=0;
public CrimeReportPOJO(Map<String,String[]> complaintFormData,Connection connection){
this.complaintFormData = complaintFormData;
this.connection = connection;
sendCrimeData();
}
private void sendCrimeData(){
try{
String query_VICTIM_DETAILS ="INSERT INTO VICTIM_DETAILS ("+
"VICTIM_FIRST_NAME,"+
"VICTIM_MIDDLE_NAME,"+
"VICTIM_LAST_NAME,"+
"VICTIM_UID_NO,"+
"VICTIM_AGE,"+
"VICTIM_GENDER,"+
"VICTIM_ADDRESS,"+
"NEAREST_POLICE_CHOWKI,"+
"VICTIM_ZIP_CODE,"+
"VICTIM_PHONE_NO,"+
"VICTIM_EMAIL_ADDRESS,"+
"COMPLAINT_ID)"+
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
String query_VICTIMIZER_DETAILS ="INSERT INTO VICTIM_DETAILS ("+
"VICTIMIZER_BUSINESS_NAME,"+
"VICTIMIZER_FIRST_NAME,"+
"VICTIMIZER_MIDDLE_NAME,"+
"VICTIMIZER_LAST_NAME,"+
"VICTIMIZER_GENDER,"+
"VICTIMIZER_ADDRESS,"+
"VICTIMIZER_ZIP_CODE,"+
"VICTIMIZER_PHONE_NO,"+
"VICTIMIZER_EMAIL_ADDRESS,"+
"COMPLAINT_ID)"+
"VALUES(?,?,?,?,?,?,?,?,?,?)";
String query_COMPLAINT_DESCRIPTION ="INSERT INTO COMPLAINT_DESCRIPTION ("+
"COMPLAINT_ID,"+
"COMPLAINT_DESC,"+
"COMPLAINT_TIME_STAMP)"+
"VALUES(?,?,?)";
String query_COMPLAINT_COUNT_DETAILS ="INSERT INTO COMPLAINT_COUNT_DETAILS("+
"VICTIM_UID_NO,"+
"COMPLAINT_COUNT)"+
"VALUES(?,?)";
PreparedStatement ps = connection.prepareStatement(query_VICTIM_DETAILS);
/*Now, lets extract the data to be inserted from the map object
* and call the setString() methods on those values */
/*Collection<String[]> c = complaintFormData.values();
Iterator<String[]> it = c.iterator();
int i=1;
while(it.hasNext()){
String[] s = it.next();
ps.setObject(i, (Object)s[0] );
i++;
}*/
String[] s= complaintFormData.get("personal_first_name");
System.out.println(s[0]);
System.out.println(s);
ps.setString(1,s[0]);
s= complaintFormData.get("personal_middle_name");
ps.setString(2,s[0]);
s= complaintFormData.get("personal_last_name");
ps.setString(3,s[0]);
s= complaintFormData.get("personal_aadhar_card_no");
System.out.println(Integer.parseInt(s[0]));
ps.setInt(4,Integer.parseInt(s[0]) );
s= complaintFormData.get("personal_age");
ps.setInt(5,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_gender");
ps.setString(6,s[0]);
s= complaintFormData.get("personal_address");
ps.setString(7,s[0]);
s= complaintFormData.get("police_chowki");
ps.setString(8,s[0]);
s= complaintFormData.get("personal_zip_code");
ps.setInt(9,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_phone_no");
ps.setInt(10,Integer.parseInt(s[0]));
s= complaintFormData.get("personal_email_id");
ps.setString(11,s[0] );
System.out.println(s[0]);
/*To insert complaint ID into the last column COMPLAINT_ID I am
* calling getComplaintID() method which tells me whether its the
* first time I am inserting into the database or there are already
* complaints registered*/
complaintID = getComplaintID();
System.out.println(complaintID);
if(complaintID==-2){
//First time
ps.setInt(12,1);
}
else{
ps.setInt(12,++complaintID);
}
ps.executeUpdate(query_VICTIM_DETAILS);
}catch(Exception e){
e.printStackTrace(System.out);
System.out.println(e);
}
}
private int getComplaintID(){
String query = "SELECT MAX(COMPLAINT_ID)"+
"FROM COMPLAINT_DESCRIPTION";
try {
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
else{
/*-2 indicates that the table is empty and the first
**complaint is being registered*/
return -2;
}
} catch (SQLException e) {
e.printStackTrace();
}
/*The syntax compels to return an integer value*/
return -1;
}
}
The problem is that I am getting the following exception:
java.sql.SQLException: ORA-01008: not all variables bound
The stack trace is:
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1169)
at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1615)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1580)
at com.cid_org.model.CrimeReportPOJO.sendCrimeData(CrimeReportPOJO.java:130)
at com.cid_org.model.CrimeReportPOJO.<init>(CrimeReportPOJO.java:20)
at com.cid_org.controller.CrimeReportControllerServlet.doPost(CrimeReportControllerServlet.java:52)
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(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Here is the VICTIM_DETAILS table:
http://i.stack.imgur.com/1TEIK.png
and here is the COMPLAINT_DESCRIPTION table,
http://i.stack.imgur.com/qxvPN.png
What I have tried: I inserted the following statement
System.out.println(complaintID);
after calling the getComplaintID() method and the output that I got on the console matches what is actually already in the table(I have cross checked it) and this indicates that the code reaches there successfully which also indicates that getComplaintID() method successfully executed.
Also, I left no value as null in the form and all the values were constraint to the table format.
Perhaps just try calling executeUpdate() with no parameters. You've already set the query string when you created the PreparedStatement.
ps.executeUpdate()
I have created companies nodes from mysql database using this code
public class EnterCompaniesToNeo4j {
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
ConnectionStrings c=new ConnectionStrings();
String CONN_STRING=c.getConnString();
String USERNAME=c.getUsername();
String PASSWORD=c.getPassword();
Connection conn=null;
PreparedStatement stmt=null;
int counter=0;
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1");
Transaction tx = graphDB.beginTx();
Node n = null;
try
{
stmt=conn.prepareStatement("select * from companies where node_id IS NULL", ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// stmt.setString(1, "100641318");
rs=stmt.executeQuery();
while(rs.next())
{
// deo gde se kreira nod
counter=counter+1;
n = graphDB.createNode();
n.setProperty( "taxnumber", rs.getString("tax_number"));
n.setProperty( "name", rs.getString("name"));
n.setProperty( "email", rs.getString("email"));
long br;
br=n.getId();
rs.updateLong("node_id",br);
rs.updateRow();
//System.out.println(n.getProperty("taxnumber"));
//System.out.println(n.getId()+"");
System.out.println(rs.getString("name"));
}
tx.success();
}
catch ( Exception e )
{
tx.failure();
}
finally
{
tx.finish();
stmt.close();
rs.close();
conn.close();
}
//ExecutionEngine engine = new ExecutionEngine( graphDB );
//ExecutionResult result = engine.execute( "start n=node(2) return n, n.taxnumber,n.name" );//vracanje noda 1
//ExecutionResult result = engine.execute( "START n = node(*) DELETE n" ); //brisanje svih nodova
//System.out.println(result.toString());
System.out.println(""+counter);
graphDB.shutdown();
}
}
Now I want to enable users to insert relationships after they are logged in , I do it from servlet like this
public class InputDebtDataToNeo4j extends HttpServlet {
GraphDatabaseService graphDB = new GraphDatabaseFactory().newEmbeddedDatabase("build\\web\\NEO4J databases\\db1");
Transaction tx = graphDB.beginTx();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList<InputData> l111 = new ArrayList<InputData>();
ArrayList<InputData> l222 = new ArrayList<InputData>();
HttpSession session=request.getSession(true);
l111= (ArrayList<InputData>) session.getAttribute("hasdata");
l222=(ArrayList<InputData>) session.getAttribute("hasnotdata");
//put ka Neo4j bazi
long mynodenumber;
mynodenumber = Long.parseLong(session.getAttribute("node_id").toString());
try {
for (InputData element : l111)
{
ExecutionEngine engine = new ExecutionEngine( graphDB );
ExecutionResult result = engine.execute( "START a=node("+mynodenumber+"), b=node("+element.getNodeidnumber()+") CREATE a-[r:OWE{amount:"+element.getDebtamount()+"}]->b RETURN r" );//vracanje noda 1
out.println("Relacija "+result.toString()+"</br>");
out.println("Taks broj "+element.getTaxnumberdata()+"</br>");
out.println("Node Broj "+element.getNodeidnumber()+"</br>");
out.println("Iznos duga "+String.valueOf(element.getDebtamount())+"</br>");
out.println("Moj node broj "+mynodenumber+"</br>");
}
//response.sendRedirect("DebtSolutions.jsp");
tx.success();
}
catch(Exception e )
{
tx.failure();
out.println(e.toString());
}
finally {
tx.finish();
graphDB.shutdown();
out.close();
}
}
And for a result I get this error message
type Exception report
message Error instantiating servlet class servlets.InputDebtDataToNeo4j
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class servlets.InputDebtDataToNeo4j
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
root cause
java.lang.IllegalStateException: Database locked.
org.neo4j.kernel.InternalAbstractGraphDatabase.create(InternalAbstractGraphDatabase.java:289)
org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:227)
org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:79)
org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:70)
org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:205)
org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:56)
servlets.InputDebtDataToNeo4j.<init>(InputDebtDataToNeo4j.java:30)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:525)
java.lang.Class.newInstance0(Class.java:372)
java.lang.Class.newInstance(Class.java:325)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)
What should I do in my servlet to make it work ...
You would want to have the graph database as a singleton.
So either you declare your GraphDatabaseService static in your servlet (remember there is a new servlet instance created per request (or at least as many as there are threads/pooled).
Or you have it injected, or you store it in the Application-Context. Or use a ServletContextListener that creates the graph database on startup and shuts it down correctly at shutdown.