I'm new to connecting to MySQL using JDBC with tomcat. I've been following an excellent tutorial here but am struggling. I have ensured my EC2 security group is configured to MYSQL port 3306 0.0.0.0/0 and HTTP port 80 0.0.0.0/0. I'm currently getting the error: Name [jdbc/bbytesting] is not bound in this Context. Unable to find [jdbc].
Here is stacktrace:
javax.naming.NameNotFoundException: Name [jdbc/bbytesting] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.youtube.dao.MySQL308tube.MySQL308tubeConn(MySQL308tube.java:31)
at com.youtube.rest.status.V1_status.returnDatabaseStatus(V1_status.java:61)
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:483)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
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)
Here are the steps I've performed up to this point:
Downloaded MySQL JDBC Driver and put in lib folder
JDBC Resource Configuration
<Context>
<Resource name="jdbc/bbytesting" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="username" password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://awsurl:3306/bbytesting">
</Context>
Return database status code:
public String returnDatabaseStatus() throws Exception {
PreparedStatement query = null;
String myString = null;
String returnString = null;
Connection conn = null;
try {
conn = MySQL308tube.MySQL308tubeConn().getConnection();
query = conn.prepareStatement("select to_char(sysdate, 'YYYY-MM-DD HH24:MI:SS') DATETIME " + "from sys.dual");
ResultSet rs = query.executeQuery();
while (rs.next()) {
myString = rs.getString("DATETIME");
}
query.close();
returnString = "<p>Database Status</p> "
+ "<Database Date/Time return: " + myString + "</p>";
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (conn != null) conn.close();
}
return returnString;
}
Here is connection class code:
public class MySQL308tube {
private static DataSource MySQL308tube = null;
private static Context context = null;
public static DataSource MySQL308tubeConn() throws Exception {
if(MySQL308tube != null) {
return MySQL308tube;
}
try {
if (context == null) {
context = new InitialContext();
}
MySQL308tube = (DataSource) context.lookup("jdbc/bbytesting");
}
catch (Exception e) {
e.printStackTrace();
}
return MySQL308tube;
}
}
The exception explains it perfectly: That's why you should never, ever have empty catch blocks.
Your JNDI data source lookup is failing. You need to prepend it with "java:/comp/env", like these Tomcat docs tell you to:
https://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html
You are using awsurl in the connection URL which needs extra permissions for the user. If your application and database runs on the same server, refer by localhost or 127.0.0.1.
If you would need to make your application access this server by awsurl, go to mysql prompt as mysql root user and execute GRANT:
For global access.
GRANT ALL ON bbytesting.* TO '<user>'#'%' IDENTIFIED BY '<password>'
For access from particular IP address (possibly IP of server where you run your application)
GRANT ALL ON bbytesting.* TO '<user>'#'<ip_address>' IDENTIFIED BY '<password>'
Also, I recommend you to test accessing database from the server you run your application using command:
mysql -u user_name -ppassword -h db_server_ip
No space between switch -p and password
You may need to install mysql-client package to run mysql command.
Related
I'm writing a Java program that queries an SQL database, and pulls out my query, to see if a username and password exist in my database. My code is:
My code is:
public UserInfo getUserExists(final String userEmail) throws SQLException, ClassNotFoundException {
if (!isBlank(userEmail)) {
Connection conn;
Statement stmt;
try{
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("Connecting to DB...");
conn = DriverManager.getConnection("jdbc:mariadb://10.0.0.0:3306/mydb","myusername", "mypassword");
System.out.println("Connected to DB successfully");
System.out.println("querying if user is valid");
stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT IF (EXISTS(select user_email, user_pass, meta_value from myorg_users left join myorg_usermeta on ( myorg_users.id = myorg_usermeta.user_id) where meta_value LIKE '%\"administrator\"%' and meta_key=\"myorg_capabilities\" AND user_email="+userEmail+"),1,0) AS result;");
int result = 0;
System.out.println(rs);
while(rs.next()){
result = Integer.parseInt(rs.getString("result"));
System.out.println("result is " + result);
}
conn.close();
if(result == 1){
UserInfo SYSTEM_USER = new UserInfo.Builder(UserInfo.Username.valueOf("SYSTEM_USER")).withFirstName("System").withLastName("User").withEmail(userEmail).withUserId("sample").build();
System.out.println(SYSTEM_USER);
return SYSTEM_USER;
}
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
} else {
throw new AuthenticationException("user does not exists in system");
}
System.out.println("executed new user exists");
return null;
}
However, when I run my API, I get this, and I KNOW the password/username are correct -
java.sql.SQLSyntaxErrorException: Access denied for user 'myusername'#'10.%' to database 'mydb'
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:163)
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:106)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1036)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:490)
at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:144)
at org.mariadb.jdbc.Driver.connect(Driver.java:90)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.intuit.wasabi.authentication.impl.DefaultAuthentication.getUserExists(DefaultAuthentication.java:168)
at com.intuit.wasabi.api.AuthenticationResource.getUserExists(AuthenticationResource.java:214)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at com.google.inject.servlet.ServletDefinition.doServiceImpl(ServletDefinition.java:287)
at com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:277)
at com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:182)
at com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:91)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:85)
at com.intuit.autumn.web.WebFilter.doFilter(WebFilter.java:65)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:82)
at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:119)
at com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:133)
at com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:130)
at com.google.inject.servlet.GuiceFilter$Context.call(GuiceFilter.java:203)
at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:130)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1160)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1092)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:518)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:244)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:246)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:156)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: Access denied for user 'myusername'#'10.%' to database 'mydb'
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.authentication(AbstractConnectProtocol.java:787)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.handleConnectionPhases(AbstractConnectProtocol.java:713)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connect(AbstractConnectProtocol.java:402)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1032)
... 59 more
What is going on? I've run this query in the DB and it works in MariaDB. Why can't I achieve what I need in Java?
well java aside, are you ssure you going to access your db on 10.0.0.0 ? I would make an educated guess your MariaDB is configured to listen on loopback interface (127.0.0.1) so if your MariaDB isnt configured to listen an other interface you would get a connection refused kinda case. So i would start to check this if you are sure you can do it in the phpmyadmin (i guess you use that and it might be accessed over localhost?). and 10.0.0.0 shouldnt be a possible ip.
I have a Java web service project as a RESTful API for my sqlite database.
My project structure is:
FirstWebService
-- Java Resources
-- JavaScript Resources
-- build
-- target
-- web content
pom.xml
words.db
my code for accessing the database is
JSONObject obj = new JSONObject();
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
try{
con = DriverManager.getConnection("jdbc:sqlite:Words.db");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("select word, de, ar from Arabic where de=\"Erfolg\"");
while(res.next()){
obj.put("word", res.getString("word"));
obj.put("de", res.getString("de"));
obj.put("ar", res.getString("ar"));
}
}
catch(Exception ex){
ex.printStackTrace();
}
finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
however, when executing the code i get these errors
java.lang.UnsatisfiedLinkError: Native Library C:\Users\abosamir\AppData\Local\Temp\sqlite-3.7.2-sqlitejdbc.dll already loaded in another classloader
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: Arabic)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.throwex(DB.java:374)
at org.sqlite.NestedDB.prepare(NestedDB.java:134)
at org.sqlite.DB.prepare(DB.java:123)
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at com.crunchify.restjersey.TestName.convert(TestName.java:47)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:745)
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)
I believe it has to do with the path of the database. My database has the table and it is full of data. Besides, the sql command is functional and correct.
My Sqlite Driver in pom.xml file is
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
I have run into a problem that I have been trying to figure out for days:
I added my driver: mysql-connector-java-5.1.40.jar to build path.
web-inf lib folder, apache tomcat lib folder. And also I have it in web app libaries.
However when I just run a main class and run it works, it is something to do with the web app?
This is my code:
This is the servlet class, that I use to connect to my database
package sql;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
#WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbUtil sql = new DbUtil();
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (sql.addToAccountToDatabase(username, password, email)) {
System.out.println("Gongratz");
} else {
System.out.println("mhhh ?");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
}
this is the second class how i make connection
package sql;
import java.sql.*;
public class DbUtil {
public Connection getConnection() {
Connection connect = null;
try {
String url = "jdbc:mysql://hidden:3306/hidden";
connect = DriverManager.getConnection(url, "hidden", "hidden");
return connect;
} catch (Exception e) {
System.out.println("Cannot connect to database");
e.printStackTrace();
}
return connect;
}
public boolean addToAccountToDatabase(String username, String password, String email) {
try {
String query = "INSERT INTO Account (username, password, email) VALUES (?, ?,?)";
PreparedStatement pStat = getConnection().prepareStatement(query);
pStat.setString(1, username);
pStat.setString(2, password);
pStat.setString(3, email);
pStat.executeUpdate();
return true;
} catch (Exception e) {
System.out.println("User already exists");
e.printStackTrace();
return false;
}
}
}
And I get this error:
Cannot connect to database
java.sql.SQLException: No suitable driver found for jdbc:mysql://192.185.227.214:3306/ratekas9_illegalminds
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sql.DbUtil.getConnection(DbUtil.java:15)
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
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(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)
User already exists
java.lang.NullPointerException
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
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(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)
mhhh ?
Because the String "jdbc:mysql" doesn't declare the driver Class itself, but only the name registered by a potential driver. You have to force the JVM to load the Driver class with a :
Class.forName("com.mysql.jdbc.Driver").newInstance();
before starting the JDBC connection.
You need 3 steps to solve your problem:
Add this code before connection Class.forName("com.mysql.jdbc.Driver");
Add 'JConnector.jar' into your project and build path.
Don't try enter same person because there is error in stack trace "User all ready exist ".
Adding the JAR file into your CLASSPATH (for compilation needs) / project's BUILDPATH and also under your project's WEB-INF/lib folder (for runtime references, i.e., when you deploy your application to an application server). For further reference, please go through this link
Class.forName("com.mysql.jdbc.Driver");
This is no longer required as per Official Java documentation here, but it is a mandatory step if you are using prior versions of JDBC 4.0.
This question can provide you lot many details on this regards.
Hope all these details help you resolve your issue!
I don't understand why I am getting this error.. In my web application I have used many methods where I execute insert, select, update etc where all of them works correctly without errors... Now I want to implement a delete action. So, I have:
public void deleteBox(Label label)
throws SQLException, ClassNotFoundException {
System.out.println("Deleting box from BOXES");
sq = "DELETE FROM BOXES WHERE product=? AND version=? AND productionD=? AND AA=?";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
PreparedStatement stm = c.prepareStatement(sq);
stm.setString(1, label.getProduct());
stm.setString(2, label.getVersion());
stm.setString(3, label.getDateProduction());
stm.setString(4, label.getPacketNumber());
stm.executeUpdate();
} catch (SQLException e) {
System.out.println("hereeee error: " + e.getMessage());
e.printStackTrace();
} finally {
if (stm != null)
stm.close(); //<---
if (c != null)
c.close();
}
}
where path and typeDB are defined as:
private final String path = "jdbc:sqlite:C:\\DB_LABELS\\labels.sqlite";
private final String typeDB= "org.sqlite.JDBC";
and in the start of the class:
private Connection c = null;
PreparedStatement stm = null;
This method is called from the servlet here:
try{
Label box = (Label) session.getAttribute("boxFound");
action.deleteBox(box); //here I call the method
//some other stuff here..
action.addTransaction(box, "extract", timeStamp1, user.getId());
old = action.searchQuantityOfPackage(box);
}catch(SQLException | ClassNotFoundException e){
System.err.println("Exception at extract. More: " + e);
}
When it is executed I get an error:
Deleting box from BOXES
Exception at extract. More: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
and all the other commands aren't executed inside the try. I don't understand why is this happening. As I said in the begging I use the same setting for other sql actions so both path and typeDB must be defined correctly. If I delete action.deleteBox(box); no error is happening, so sth is happening in this method...
ALSO
I forgot to mention that the delete of the row in the table BOXES is happening despite the error!
I add also the ful stack trace
Exception at extract. More: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at gr.products.labelInventory.ActionsDB.deleteBox(ActionsDB.java:557)
at gr.products.labelInventory.Inventory.processRequest(Inventory.java:285)
at gr.products.labelInventory.Inventory.doGet(Inventory.java:652)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at gr.products.labelInventory.LogFilter.doFilter(LogFilter.java:22)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
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:724)
this line at gr.products.labelInventory.ActionsDB.deleteBox(ActionsDB.java:557) points to the <-- i put in the code.
I am trying to call a rest controller using get call which reads files from file system and return InputStream of that file.
client side code:
website = new URL(configurationFileUrl + "/stream/" + key.getReportRawDataId());
URLConnection connection = website.openConnection();
connection.setConnectTimeout(60 * 1000);
connection.setReadTimeout(60 * 1000);
stream = connection.getInputStream();
The controller code:
#RestController
#RequestMapping(value = "/blueprintConfig", produces = {"application/octet-stream", "application/json"}, headers = "Accept=*/*")
public class ReportConfigurationController {
#ResponseBody
#RequestMapping(value = "/stream/{id:.+}", method = RequestMethod.GET)
public ResponseEntity<?> getFilesAsStream(#PathVariable("id") String id) throws Exception {
return configurationService.getFilesAsStream(id);
}
}
service:
#Override
public ResponseEntity<?> getFilesAsStream(String id) throws Exception {
String filePath = resourcePath + id;
InputStream is = null;
try {
is = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
LOGGER.error("can not read file: {}", e);
}
return new ResponseEntity<InputStream>(is, HttpStatus.OK);
}
while debugging I see the service is returning inputstream without any exception, but client side is throwing below IO exception:
java.io.IOException: Server returned HTTP response code: 406 for URL: http://localhost:8091/blueprintConfig/stream/1_check.png
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
at com.jasper.wrapper.service.ReportServiceImpl.putInCache(ReportServiceImpl.java:128)
at com.jasper.wrapper.service.ReportServiceImpl.populateCache(ReportServiceImpl.java:110)
at com.jasper.wrapper.service.ReportServiceImpl.lambda$generateReport$0(ReportServiceImpl.java:64)
at com.jasper.wrapper.service.ReportServiceImpl$$Lambda$8/819977316.accept(Unknown Source)
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:676)
at com.jasper.wrapper.service.ReportServiceImpl.generateReport(ReportServiceImpl.java:64)
at com.jasper.wrapper.controller.JasperReportController.generateReport(JasperReportController.java:27)
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:497)
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.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
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)
what is wrong I am doing here I tried setting
connection.setRequestProperty("accept", "application/octet-stream");
but no luck, could you please help
406 means your client isn't accepting the response it got from the server, so the server is unaware (ergo no error on the server).
It really depends on what the server is saying the data is.
Just telnet into your server:
telnet localhost:8091
and emit a:
GET /blueprintConfig/stream/1_check.png HTTP/1.1
(press return key twice)
Then look at the response headers to find out what your server is sending back to the client.
Alternatively, if you have curl installed, just do:
curl -I http://localhost:8091/blueprintConfig/stream/1_check.png
And look at the headers.
I have set the interceptor for the Rest Template code as below:
ClientHttpRequestInterceptor acceptHeaderPdf = getClientHttpRequestInterceptor(APPLICATION_STREAM);
<-- here APPLICTION_STREAM is my header externalized variable you can use your headers like application/pdf ... -->
restTemplate.setInterceptors(singletonList(acceptHeaderPdf));
private ClientHttpRequestInterceptor getClientHttpRequestInterceptor(String applicationJson) {
return new AcceptHeaderHttpRequestInterceptor(
applicationJson);
}
class AcceptHeaderHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerValue;
public AcceptHeaderHttpRequestInterceptor(String headerValue) {
this.headerValue = headerValue;
}
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
requestWrapper.getHeaders().setAccept(singletonList(MediaType.valueOf(headerValue)));
return execution.execute(requestWrapper, body);
}
}