Why would connecting to a MySQL database from Java get denied access? - java

I am trying to connect to MySQL from Java and I get the following error.
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:951)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1717)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2395)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.javawebtutor.jsf.LoginBean.dbData(LoginBean.java:63)
at com.javawebtutor.jsf.LoginBean.checkValidUser(LoginBean.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at org.apache.jasper.el.JspMethodExpression.invoke(JspMethodExpression.java:70)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
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:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2522)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2511)
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)
Exception Occured in the process :java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)"
Thank you for all help, I am very new to this. I am positive the password and username are correct so I am unsure where to go from here. Here is my code for connecting to the database:
package com.javawebtutor.jsf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="loginBean")
#SessionScoped
public class LoginBean {
private String userName;
private String password;
private String dbuserName;
private String dbpassword;
Connection connection;
Statement statement;
ResultSet resultSet;
String SQL;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDbuserName() {
return dbuserName;
}
public void setDbuserName(String dbuserName) {
this.dbuserName = dbuserName;
}
public String getDbpassword() {
return dbpassword;
}
public void setDbpassword(String dbpassword) {
this.dbpassword = dbpassword;
}
public void dbData(String userName)
{
Connection con = null;
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=pass;";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(conUrl);
//connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",user = "root","pass");
statement = connection.createStatement();
SQL = "Select * from USER_DETAIL where username like ('" + userName +"')";
resultSet = statement.executeQuery(SQL);
resultSet.next();
dbuserName = resultSet.getString(1).toString();
dbpassword = resultSet.getString(2).toString();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occured in the process :" + ex);
}
}
public String checkValidUser()
{
dbData(userName);
if(userName.equalsIgnoreCase(dbuserName))
{
if(password.equals(dbpassword))
return "success";
else
{
return "failure";
}
}
else
{
return "failure";
}
}
}

In MySQL server administration, users are specified with both allowable hostnames and passwords. If the root user was not set up to include localhsot as a client, it will deny logins on the local machine. See this question and its accepted answer for some details.

Can you try like this
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","pass");
As getConnection function requires 3 arguments : url+dbname , username , password.

Your password is wrong it seems.
You can try with empty password given below.
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=;";

Related

Unable to configure JAAS authentication

I want to use JAAS authentication for my Web application. I can't figure out where the error lies. I don't get any error messages but the login part is not working.
I have a Html page (index.html) as front page. When logging in it get username and password and takes it to the servlet.
index.html
<html>
<head>
<title>Login
</title>
</head>
<body>
<br><br>
<center>
<h1>Railway Reservation</h1>
<br><br>
<form action="Authentication" method="post">
User Name:<input type="text" name="user"><br><br>
Password:<input type="password" name="pass"><br><br>
<input type="submit" value="Login">
</form>
</center>
</body>
</html>
Authentication.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.security.auth.login.*;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class Authentication extends HttpServlet
{
public Authentication()
{
super();
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("hiii");
String user = request.getParameter("user");
String password = request.getParameter("pass");
pw.println(user + " " + password );
if((user!=null)&&(password!=null))
{
pw.println("if");
CBHandler cbhandler = new CBHandler(user,password);
boolean authFlag = true;
try
{
HttpSession session = request.getSession();
session.setAttribute("username",user);
pw.println("inside try block");
System.setProperty("java.security.auth.login.config","jaas.config");
LoginContext loginContext = new LoginContext("Railway",cbhandler);
loginContext.login();
pw.println("try ");
}
catch(LoginException e)
{
pw.println(e);
e.printStackTrace();
authFlag = false;
pw.println("hello");
}
if(authFlag)
{
pw.println(user + " " + password);
pw.println("Authentication success...");
Connection con = DB.getDBconnection();
if(con!=null)
{
String sql = "select role from login where uname=?";
try
{
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
rs.next();
String role = rs.getString("role");
if(role.equals("user"))
response.sendRedirect("user.jsp");
else
response.sendRedirect("admin.jsp");
}
catch(Exception e)
{
pw.println(e);
}
}
}
else
pw.println("Authentication failed...");
}
else
{
pw.println("Invalid authentication...");
}
}
}
CBHandler.java
import java.io.*;
import javax.security.auth.callback.*;
public class CBHandler implements CallbackHandler
{
private String user = null;
private String password = null;
public CBHandler(String user,String password)
{
this.user = user;
this.password = password;
}
#Override
public void handle(Callback[] callbackArray) throws IOException,UnsupportedCallbackException
{
int counter = 0;
while(counter < callbackArray.length)
{
if(callbackArray[counter] instanceof NameCallback)
{
NameCallback nameCallback = (NameCallback)callbackArray[counter++];
nameCallback.setName(user);
}
else if(callbackArray[counter] instanceof PasswordCallback)
{
PasswordCallback passwordCallback = (PasswordCallback)callbackArray[counter++];
passwordCallback.setPassword(password.toCharArray());
}
}
}
}
LoginMod.java
import java.util.*;
import java.sql.*;
import java.io.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.* ;
import javax.security.auth.spi.LoginModule;
public class LoginMod implements LoginModule
{
private CallbackHandler callbackHandler = null;
private boolean successFlag = false;
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,Map<String,?> sharedState,Map<String,?> options)
{
this.callbackHandler = callbackHandler;
}
#Override
public boolean login() throws LoginException
{
Callback[] callbackArray = new Callback[2];
callbackArray[0] = new NameCallback("User Name: ");
callbackArray[1] = new PasswordCallback("Password : ",false);
try
{
callbackHandler.handle(callbackArray);
}
catch(IOException e)
{
e.printStackTrace();
}
catch(UnsupportedCallbackException e)
{
e.printStackTrace();
}
String name = ((NameCallback) callbackArray[0]).getName();
String password = new String(((PasswordCallback) callbackArray[1]).getPassword());
if((name.equals("root"))&&(password.equals("root")))
{
System.out.println("auth success");
successFlag = true;
}
else
{
successFlag = false;
throw new FailedLoginException ("auth failed");
}
return successFlag;
}
#Override
public boolean commit() throws LoginException
{
return successFlag;
}
#Override
public boolean abort() throws LoginException
{
return false;
}
#Override
public boolean logout() throws LoginException
{
return false;
}
}
jaas.config
Railway
{
LoginMod required debug=true;
};
When I run this code I get this as Output
hiii root root if inside try block
This is the error I get
HTTP Status 500 – Internal Server Error
Type Exception Report
Message java.io.IOException: jaas.config (No such file or directory)
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.SecurityException: java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.ioException(Unknown Source)
sun.security.provider.ConfigFile$Spi.init(Unknown Source)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
The place I was going wrong was giving the location of the configuration file in java.security file, which is present in C:\Program Files\Java\jre1.8.0_77\lib\security\java.security.
When copying the path of the jaas.config file in Windows the path is given with backward slashes( / ), which should be replaced with forward slashes( \ ).
For example, it should be like login.config.url.1=file:D:/mani/java/sample_jaas.config and not as login.config.url.1=file:D:\mani\java\sample_jaas.config
I guess it will be helpful for someone.

How can I solve java.lang.Class.forName(Unknown Source) error?

I am trying to make a project on Servlets using JDBC. But there are some persistent errors in the error log like java.lang.Class.forName(Unknown Source), java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source), java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source), java.lang.Thread.run(Unknown Source) etc. How can I solve such errors from happening?
I am using Apache Tomcat v7.0, mySQL Community Server v5.7 and Eclipse IDE.
This my error log:
java.lang.ClassNotFoundException: com.mysql.driver.JDBC
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Register.register(Register.java:10)
at RegisterServlet.doPost(RegisterServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
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:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java: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: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)
This is the JDBC file code(Register.java):
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Register {
public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static final Pattern VALID_PHONE_NUMBER_REGEX = Pattern.compile("[7-9][0-9]\\d{9}"); // ,Pattern.CASE_INSENSITIVE);
public static int register(String name,String user,String pass,String cpass,String email, String phone,String city,String state) throws ClassNotFoundException{
int status=0;
try{
Class.forName("com.mysql.driver.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:localhost:8080/Diary.db");
System.out.println("Database connected successfully!!");
PreparedStatement ps=con.prepareStatement("INSERT INTO Trial(name, user, pass, email, phone, city, state, authorized) values(?,?,?,?,?,?,?,?)");
if(pass!=null && cpass!=null && phone!=null && name!=null && user!=null && city!=null && state!=null){
Matcher matcher1 = VALID_EMAIL_ADDRESS_REGEX .matcher(email);
Matcher matcher2 = VALID_PHONE_NUMBER_REGEX .matcher(phone);
if((pass==cpass) && (matcher1.find()) && (matcher2.find())){
ps.setString(1,name);
ps.setString(2,user);
ps.setString(3,pass);
ps.setString(4,email);
ps.setString(5,phone);
ps.setString(6,city);
ps.setString(7,state);
ps.setString(8,"yes");
status=ps.executeUpdate();
}
else{
status = 0;
}
}
}catch(SQLException e){e.getMessage();}
return status;
}
}
This is my servlet (RegisterSevlet.java):
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int status;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("name");
String user=req.getParameter("user");
String pass=req.getParameter("pass");
String cpass=req.getParameter("cpass");
String email=req.getParameter("email");
String phone=req.getParameter("phone");
String city=req.getParameter("city");
String state=req.getParameter("state");
try {
status = Register.register(name, user, pass, cpass, email, phone, city, state);
if(status > 0){
out.print("<p>You are successfully registered!</p>");
req.getRequestDispatcher("login.html").include(req, res);
}
else if(status == 0){
out.println("<p>Enter the information correctly!</p>");
res.sendRedirect("register.html");
}
req.getRequestDispatcher("#").include(req, res);
out.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`Class.forName()`
throws ClassNotFoundException
You need to include multicatch statement for that (same catch for SQLException and ClassNotFoundException)
You can modify your catch statement to this:
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
Try this. You can use a multicatch statement wherever you need to catch multiple exceptions.
This exception is thrown whenever a class existed at compile time but not at run time.
Please check that at runtime ur classpath is correct and you are pointing to the library in question (in ur case the mysql connector jar).

java.lang.NoClassDefFoundError: com/microsoft/sqlserver/jdbc/SQLServerDataSource

This error is produced by launching the jar file in cmd with "G:\Orchid\OrchidFX.jar". When launching the application through IntelliJ everything runs just fine. Also, in File->ProjectStructure we have added sqljdbc4.jar to the library.
The Error:
javafx.fxml.LoadException:
file:/G:/Orchid/OrchidFX.jar!/DatabaseSettingsForm.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at fxproject.ApplicationSplashScreen.loadDatabaseScreen(ApplicationSplashScreen.java:35)
at fxproject.ApplicationSplashScreen.start(ApplicationSplashScreen.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
... 19 more
Caused by: java.lang.NoClassDefFoundError: com/microsoft/sqlserver/jdbc/SQLServerDataSource
at fxproject.OrchidDataSource.setDataSourceSettings(OrchidDataSource.java:56)
at fxproject.OrchidDataSource.<init>(OrchidDataSource.java:50)
at DataSettingsController.initialize(DataSettingsController.java:34)
... 28 more
Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDataSource
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 31 more
OrchidDataSource.java:
package fxproject;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class OrchidDataSource
{
private final String driverType = "jdbc";
private final String dbmsType = "sqlserver";
private String hostname = "192.168.1.173";
private int portNumber = 1433;
private String databaseName = "OrchidDB";
private final String propertyValue = "user=Blah;password=blahblah";
private String username = "blah"; //andrew
private String password = "password";
public String getHostname()
{
return hostname;
}
public int getPortNumber()
{
return portNumber;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public String getDatabaseName()
{
return databaseName;
}
private SQLServerDataSource dataSource;
private static OrchidDataSource orchidDataSource;
public OrchidDataSource()
{
setDataSourceSettings();
setCurrentDataSource(this);
}
private void setDataSourceSettings()
{
dataSource = new SQLServerDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setServerName(hostname);
dataSource.setPortNumber(portNumber);
dataSource.setDatabaseName(databaseName);
}
public void setDataSourceSettings(String username, String password, String hostname, int portNumber, String databaseName)
{
this.username = username;
this.password = password;
this.hostname = hostname;
this.portNumber = portNumber;
this.databaseName = databaseName;
setDataSourceSettings();
}
public void setCurrentDataSource(OrchidDataSource orchidDataSource)
{
this.orchidDataSource = orchidDataSource;
}
public static OrchidDataSource getCurrentDataSource()
{
return orchidDataSource;
}
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
}
}
DataSettingsController:
package fxproject;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.sql.Connection;
public class DataSettingsController
{
public static final String VIEWCONTROLLER_TITLE= "DataSettings";
#FXML
TextField fieldhostname;
#FXML
TextField fieldportnumber;
#FXML
TextField fielddatabasename;
#FXML
TextField fieldusername;
#FXML
PasswordField fieldpassword;
public DataSettingsController()
{
}
#FXML
public void initialize()
{
OrchidDataSource dataSource = new OrchidDataSource();
fieldhostname.setText(dataSource.getHostname());
fieldportnumber.setText(String.valueOf(dataSource.getPortNumber()));
fielddatabasename.setText(dataSource.getDatabaseName());
fieldusername.setText(dataSource.getUsername());
fieldpassword.setText(dataSource.getPassword());
}
#FXML
protected void handleButtonSubmit(ActionEvent e)
{
try
{
OrchidDataSource dataSource = new OrchidDataSource();
dataSource.setDataSourceSettings(fieldusername.getText(),
fieldpassword.getText(),
fieldhostname.getText(),
Integer.parseInt(fieldportnumber.getText()),
fielddatabasename.getText());
Connection connection = OrchidDataSource.getCurrentDataSource().getConnection();
connection.prepareStatement("{call SelectClientStatus()}").executeQuery(); ///low data query to test connection
new MainSystem();
Node source = (Node) e.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
catch(Exception ae)
{
new OrchidAlertBox("Error", "Database cannot be reached.");
}
}
}

java.lang.IllegalStateException: consumer key/secret pair already set

I'm using Spring framework to login with twitter into my website, I'm actually learning from this tutorial.
So i followed this question and changed my source accordingly below:
#RequestMapping("/welcome")
#Controller
public class HelloController {
private final String CONSUMER_KEY = "xxxx";
private final String CONSUMER_SECRET = "xxxx";
ConfigurationBuilder confBuilder = new ConfigurationBuilder()
.setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET);
Configuration configuration = confBuilder.build();
TwitterFactory factory = new TwitterFactory(configuration);
Twitter twitter = factory.getInstance();
#Autowired
private MyAccessToken accestoken;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(HttpServletResponse response,HttpServletRequest request) {
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
RequestToken requestToken;
try {
String callbackURL = "http://127.0.0.1:8080/cwitter/callback";
System.out.println("callback url is " + callbackURL);
requestToken = twitter.getOAuthRequestToken(callbackURL);
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
accestoken.setTokensecret(tokenSecret);
accestoken.setToken(token);
String authUrl = requestToken.getAuthorizationURL();
request.setAttribute("authUrl", authUrl);
} catch (TwitterException e) {
e.printStackTrace();
}
return "login";
}
#RequestMapping(value = "/{username}/test1",method=RequestMethod.GET)
public String test1(#PathVariable String username,#RequestParam("userdetails") String userDetails,ModelMap model){
System.out.println("test1 " + username + "\t" + userDetails);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
#RequestMapping(value = "/callback",method=RequestMethod.GET)
public String test1(HttpServletRequest request, ModelMap model){
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
System.out.println(twitter);
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
String verifier = request.getParameter("oauth_verifier");
Enumeration attrList = request.getSession().getAttributeNames();
while(attrList.hasMoreElements()){
System.out.println(request.getSession().getAttribute((String)attrList.nextElement()));
}
try {
System.out.println(twitter.getOAuthAccessToken(requestToken, verifier));
request.getSession().removeAttribute("requestToken");
// twitter.setOAuthAccessToken(accessToken);
User user = twitter.verifyCredentials();
model.addAttribute("message", user.getName());
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "hello";
}
}
So, I simply tried to run all my project but it says the following logs:
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/cwitter] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: consumer key/secret pair already set.] with root cause
java.lang.IllegalStateException: consumer key/secret pair already set.
at twitter4j.TwitterBaseImpl.setOAuthConsumer(TwitterBaseImpl.java:281)
at com.common.controller.HelloController.printWelcome(HelloController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
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:51)
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:221)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:107)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:90)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1012)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:642)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1555)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please let know, What's wrong here?
Any kind of help would be appreciated!!

Java EE Connection with MySql ERROR

I try to connect to mysql database on my Java EE project but i get an error and I do not know where is the problem.
And this is SERVLET, CLASS AND ERRORS
The Java EE Servlet:
package com.hopital.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hopital.database.Recup_Insert;
import com.hopital.forms.Connections;
#WebServlet("/hopital")
public class hopital extends HttpServlet {
private static final long serialVersionUID = 1L;
public hopital() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//extrait les cookies
Cookie[] cookies= request.getCookies();
if(cookies != null){
for(Cookie cookie: cookies){
if(cookie.getName().equals("login")){
request.setAttribute("login", cookie.getValue());
}
}
}
//session
HttpSession session= request.getSession();
String login= (String) session.getAttribute("login");
request.setAttribute("login", login);
//extrait les chambers
Recup_Insert tableChamber= new Recup_Insert();
request.setAttribute("chambres",tableChamber.recup_chmabre());
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//verification de champs
Connections form= new Connections();
form.verifie(request);
request.setAttribute("form", form);
//stocke les champs entre
String login=request.getParameter("login");
String pass=request.getParameter("pass");
//cree un cookies
Cookie cookie=new Cookie("login",login);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
// cree un session sur login et mot de passe
HttpSession session= request.getSession();
session.setAttribute("login", login);
session.setAttribute("pass", pass);
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
}
My class that contain the database connexion:
package com.hopital.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.hopital.projet.chamber;
public class Recup_Insert {
public List<chamber> recup_chmabre(){
List<chamber> chambers= new ArrayList<chamber>();
//charger les drivers
try{
Class.forName("com.mysql.jdbc.Driver");
}catch( ClassNotFoundException e){
}
//Connexion
Connection connexion=null;
Statement statement=null;
ResultSet resultat = null;
try {
connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/hopital", "root", "3636");
statement= connexion.createStatement();
resultat= statement.executeQuery("SELECT * FROM CHAMBER;");
while(resultat.next()){
int etage = resultat.getInt("etage");
int ID_pat = resultat.getInt("ID_pat");
int num = resultat.getInt("num");
int nom_lits = resultat.getInt("nom_lits");
int occupee = resultat.getInt("occupee");
chamber chamber = new chamber();
chamber.setEtage(etage);
chamber.setID_pat(ID_pat);
chamber.setNum(num);
chamber.setOccupee(occupee);
chamber.setNom_lits(nom_lits);
chambers.add(chamber);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if(resultat != null)resultat.close();
if(statement != null)statement.close();
if(connexion != null)connexion.close();
}catch(SQLException ignore){
}
}
return chambers;
}
}
AND THIS IS THE ERRORS AFTER RUNING:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2252)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.hopital.database.Recup_Insert.recup_chmabre(Recup_Insert.java:29)
at com.hopital.servlet.hopital.doGet(hopital.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
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: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.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:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
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)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 39 more
Check connection URL and credentials. Try connecting with the same parameters using some SQL client.
You got this error because you cannot connect to database.
Most probably you didn't start you server. Check either it running or not, then double check port where it is running. Also check spelling on table name in database it should be "hopital".
Check For mysql-connector-java-5.1.21-bin.jar file added to Properties=>libraries=>
if not then add external jar=>mysql-connector-java-5.1.21-bin.jar
also check port number of tomcat server and mysql.

Categories

Resources