I am creating an appliaction which requires user authentication. I have one problem when I'm trying to log in. When I type a correct username and password, the onSuccess method is called. But when I type a wrong one, or empty fields, then the onFailure() method is NOT called.
I really want to know why this is happening. Because I wan't to display some sort of dialogbox when the username or password is incorrect.
This is the ClickHandler, which takes the username and password from the fields:
loginButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String username = usernameBox.getText();
String password = passwordBox.getText();
performUserConnection(username, password);
}
});
And this is the method that performs the user conenction, which as I said, works if I have a correct username/ password. It displays my alert message, but it does not display any alert message if it's not correct.
private static void performUserConnection(String username, String password) {
DBConnectionAsync rpcService = (DBConnectionAsync) GWT.create(DBConnection.class);
ServiceDefTarget target = (ServiceDefTarget) rpcService;
String moduleRelativeURL = GWT.getModuleBaseURL() + "DBConnectionImpl";
target.setServiceEntryPoint(moduleRelativeURL);
rpcService.authenticateUser(username, password, new AsyncCallback<User>() {
#Override
public void onSuccess(User user) {
Window.alert("TRALALA. Username: " + user.getUsername());
}
#Override
public void onFailure(Throwable caught) {
Window.alert("LALALALAL");
// DialogBox dialogBox = createDialogBox();
// dialogBox.setGlassEnabled(true);
// dialogBox.setAnimationEnabled(true);
// dialogBox.center();
// dialogBox.show();
}
});
}
UPDATE Server Part.
public class DBConnectionImpl extends RemoteServiceServlet implements DBConnection {
private static final long serialVersionUID = 1L;
private String URL = new String("jdbc:mysql://localhost:3306");
private String user = "root";
private String pass = "andrei";
private String schema = "administrare_bloc";
public DBConnectionImpl() {
}
private Connection getConnection() throws Exception {
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", pass);
props.setProperty("zeroDateTimeBehavior", "convertToNull");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL + "/" + schema, props);
return conn;
}
#Override
public User authenticateUser(String username, String password) throws Exception {
User returnUser = null;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
try {
String q = "select * from users where username=? and password=?";
stmt = conn.prepareStatement(q);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String user = rs.getString("username");
String pass = rs.getString("password");
String type = rs.getString("type");
returnUser = new User(id, user, pass, type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
rs.close();
stmt.close();
conn.close();
}
return returnUser;
}
}
Thanks in advance
The onFailure method will only be Called if you throw an exception on the server. Now you just return a null object if no user is found.
Related
In my SQL database single record consists of four rows: id, name, age and email. How to get a single record by typing in a JTextField id of that record? So later we can for example System.out.printIn(); it? I know that my question might be stupid for someone who is an SQL expert but I am only a beginner and after searching for this information in the tutorials I could not find it:(. Please help. Here is some of my source code:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("Statement needed to get the whole record by owning only an ID");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
If you are asking for only SQL statement it is: select * from yourtable where id = theIdThatIsfromTextFieldHere
Yet, if you simply google it you will find thousands of answers. here for instance.
The SQL Statement would be SELECT * FROM yourtable WHERE id = yourid. So to embed it into your code it would look something like this:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM {REPLACE WITH YOUR TABLE} WHERE id = "+idname);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
Just a Tip: Don't name you function "get" as this is a commonly used keyword in other programming languages that only causes confusion.
Try it:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
for(String string:get(id)){
System.out.println(string);
}
// get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
// You should replace "YourTableName" With table in databace that you work with it
PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = '" + idName+"'");
//If type of your id in database is Int write this code :
// int id= Integer.parseInt(idName);
//PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = " + idName);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
result.next();
//This array has all data in single recorde
array.add(result.getString("id"));
array.add(result.getString("name"));
array.add(result.getString("age"));
array.add(result.getString("email"));
// I removed this rows becuse you have only one record
// while(result.next()){
//
// array.add(result.getString("last"));
// }
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
I am trying to get the values that the main method would have produced and use them in the getConnection method. However when I try to access the getConnection method, null values are being returned.
I want to use the ConnectionManager class to connect to the database.
Code below.
public class ConnectionManager {
public static String database;
public static String dbuser;
public static String dbpassword;
public static void main(String args[]) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
database = prop.getProperty("database");
dbuser = prop.getProperty("dbuser");
dbpassword = prop.getProperty("dbpassword");
System.out.println(database);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String url = "jdbc:mysql://localhost:3306/" + database;
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = dbuser;
private static String password = dbpassword;
private static Connection con;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. For example:
System.out.println("Failed to create the database connection.");
System.out.println(url + " " + username + " " + password);
}
} catch (ClassNotFoundException ex) {
System.out.println("Your driver has not been found.");
}
return con;
}
}
You just have to call the getConnection() method with parameters.
public static Connection getConnection(String url, String username, String password) {
/* Your code here */
}
And then, call this method.
Connection connection = getConnection(url, username, password);
Static c fields are initialized once when the class is loaded. The Connection fields are set to the ConnectionManager fields once, when they are still null.
To "fix" your problem, have your code in Connection use the fields in ConnectionManager:
con = DriverManager.getConnection(url, ConnectionManager.dbuser, ConnectionManager.dbpassword);
You're getting null argument values in DriverManager.getConnection(url, username, password) calling cause you have declared them as static fields.
So you initialize them as nulls before you read the particular values from the config.properties
Let's follow the flow:
Static initialization step:
private static String username = dbuser; //username==null; dbuser==null;
private static String password = dbpassword; //password==null; dbpassword==null
private static Connection con; //con==null;
Method main execution:
database = (prop.getProperty("database"));
dbuser = (prop.getProperty("dbuser")); //dbuser="smth"; username==null
dbpassword = (prop.getProperty("dbpassword")); //dbpassword ="smth"; password==null
Method getConnection execution:
con = DriverManager.getConnection(url, username, password); //username==null; //password==null;
P.S.: As it was previously said, it's better to use function with arguments like this:
public static Connection getConnection(String url, String username, String password) {
/* Your code here */
}
I'm developing an application with YAWL 4. I need to add a codelet to an automatized task. I wrote a java class and added it following various tutorials, but nothing worked. The YAWL engine log gives an error, but it just says "error loading codelet x" without any details. I checked YAWL default codelets looking for errors but nothing come up (I just haven't implemented all methods, could be this?). Here is my code:
public class PrepareDataTaskCodelet extends AbstractCodelet {
private Connection connection;
private Statement statement;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private String user;
private String password;
private String getAllAppuser;
private String getAllDocument;
private String getAllRequest;
private String getAllRole;
private String tempQuery;
private Element inData;
private List<YParameter> inParams;
private List<YParameter> outParams;
private boolean cancelled;
public PrepareDataTaskCodelet() {
// TODO Auto-generated constructor stub
super();
connection = null;
statement = null;
preparedStatement = null;
resultSet = null;
user = null;
password = null;
tempQuery = null;
}
private ResultSet getSingleAppuser(String field, String data) throws SQLException{
tempQuery = getAllAppuser + "WHERE " + field + " = " + data;
connection.prepareStatement(tempQuery);
resultSet = preparedStatement.executeQuery();
return resultSet;
}
// controlla se รจ presente appuser con username e password. ritorna false se non viene trovato alcun appuser, true altrimenti
public boolean checkAppuser(String username, String password) throws SQLException{
tempQuery = getAllAppuser + "WHERE username = " + username + "AND password = " + password;
connection.prepareStatement(tempQuery);
resultSet = preparedStatement.executeQuery();
return (resultSet.first());
}
public void initConnection() throws Exception { // starts connection
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yawlConnection","root","root"); //default connection values
} finally {}
}
public PrepareDataTaskCodelet(String desc) {
super(desc);
// TODO Auto-generated constructor stub
}
#Override // TODO assegnare paramentri in ingresso (user e pw)
public Element execute(Element inData, List<YParameter> inParams, List<YParameter> outParams)
throws CodeletExecutionException {
// TODO Auto-generated method stub
setInputs(inData, inParams, outParams);
String username = "";
String password = "";
boolean isValidUser = false;
username = (String) getParameterValue("username");
password = (String) getParameterValue("password");
try {
initConnection();
isValidUser = checkAppuser(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setParameterValue("isValidUser", String.valueOf(isValidUser));
return getOutputData();
}
protected void setInputs(Element inData, List<YParameter> inParams, List<YParameter> outParams)
{
this.inData = inData;
this.inParams = inParams;
this.outParams = outParams;
}
public void cancel()
{
this.cancelled = true;
}
public List<YParameter> getRequiredParams() { // corretto
List<YParameter> params = new ArrayList<YParameter>();
YParameter param1 = new YParameter(null, YParameter._INPUT_PARAM_TYPE);
param1.setDataTypeAndName("String", "username", XSD_NAMESPACE);
param1.setDocumentation("appuser username");
params.add(param1);
YParameter param2 = new YParameter(null, YParameter._INPUT_PARAM_TYPE);
param2.setDataTypeAndName("String", "password", XSD_NAMESPACE);
param2.setDocumentation("appuser password");
params.add(param2);
YParameter param3 = new YParameter(null, YParameter._OUTPUT_PARAM_TYPE);
param3.setDataTypeAndName("boolean", "isValidUser", XSD_NAMESPACE);
param3.setDocumentation("check if current user has valid login data");
params.add(param3);
return params;
}
}
I noticed yawl uses .class files for codelets, but my codelet is a .java file, so I tryed to port it but I was unsuccessful. Does somebody have experience about Yawl 4 codelets? Or, can someone tell me how to use a .class file instead of .java?
I found out by myself. Libraries (except the java default) used by the class must be put in the same folder as the .class file. This was enough for the workflow editor to notice my codelet.
I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
modelclass md = new modelclass();
daoclass dao = new daoclass();
md.setName(name);
md.setPassword(password);
System.out.println("this just before the sql query on the main servlet page");
String sql = "Select * from USERADD where name = ? and password= ?";
String result = dao.guser(md, sql);
if (result.equals("success")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("fail.jsp");
}
}
This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {
public static String username = "NickNeo";
public static String password = "123123";
public static String driver = "com.ibm.db2.jcc.DB2Driver";
public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
public static Connection con = null;
public static PreparedStatement ps = null;
static {
try {
Class.forName(driver);
System.out.println("before connection");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successfullll......!!!!!!");
} catch(Exception e) {
e.printStackTrace();
}
}
public String guser(modelclass obj, String sql) {
try {
System.out.println("entry into try block");
ps=con.prepareStatement(sql);
ps.setString(1, obj.getName());
ps.setString(2, obj.getPassword());
System.out.println("before query");
ResultSet rs = ps.executeQuery();
System.out.println("query executed");
int i = 0;
while(rs.next()) {
System.out.println("entered into while loop");
++i;
}
if (i >= 1) {
return "success";
} else {
System.out.println("this is inside else of while block");
return "fail";
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("this is the most outer fail statement");
return "fail";
}
}
the rs is always empty. tried many things but still getting rs as empty. please help
I'm currently being thrown into the depths by my school and they are expecting me to program a simple login form using sql. They have given us brief examples on how they use JDBC and what it all is, but haven't really explained step by step how to use it on our own. Therefore i have snatched a bit of code from an example but i'm unable to get it working. I keep receiving an nullpointerexception and i can't figure out why :(
Here's the connection class:
package Database;
import java.sql.*;
public class MySQLConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost/corendon";
public static final String DBUSER = "root";
public static final String DBPASS = "simplepass";
private ResultSet result = null;
private int affectedRows = -1;
Connection conn = null;
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
}
}
public void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
}
conn = null;
}
public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException {
result = prdstmt.executeQuery();
return result;
}
public int performUpdate(PreparedStatement prdstmt) throws SQLException {
affectedRows = prdstmt.executeUpdate();
return affectedRows;
}
public Connection getConnection() {
return conn;
}
}
And here is the method i'm getting the exception in (in a different class):
MySQLConnection conn = new MySQLConnection();
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
prdstmt = conn.getConnection().prepareStatement(query);
prdstmt.setInt(1, id);
prdstmt.setString(2, pass);
rs = conn.performSelect(prdstmt);
while (rs.next()){
String tempPass = rs.getString("password");
int tempId = rs.getInt("id");
}
if(conn != null){
conn.closeConnection();
}
}
I'm getting the nullpointerexception on line:
prdstmt = conn.getConnection().prepareStatement(query);
Why does it throw an exception there, but not when i start the connection and also how do i solve this? Thanks in advance.
When you call startConnection(), you are throwing an Exception
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
//An exception occurs here, but you don't do anything about it
}
}
Therefore, when you call getConnection(), the conn variable is still null, which is throwing the NullPointerException.
Either make startConnection() throw an exception so that you're forced to deal with it (this is usually how most JDBC drivers work anyway), or check to see if the conn variable is null before you start using it.
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
if (conn.getConnection() == null) {
throw new SQLException("Connection is null!");
}
Or (what I think would personally be better)
public void startConnection() throws Exception {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
try {
conn.startConnection();
} catch (Exception e) {
throw new SQLException(e);
}
Also as a tip, you should probably avoid declaring your classes as the same name of other classes you are using. This is all happening in your own MySQLConnection class, but that could be confusing with the actual com.mysql.jdbc.MySQLConnection class.