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.
Related
We have an old client application that is deployed on JBoss 4.2.3 and written in JAVA EJB2. It has classes that depend on JBoss's security libraries, an Oracle DataSource and ANT as build method. Now there is a need of upgrading the application server because JBoss 4 no longer has life support and we are required to upgrade to Wildfly(Version 8.2 in our case). Naturally we are having a lot of problems during the process and working tirelessly just to go no further from where we are.
I just would like to get community's thoughts on this process. Is it worth the effort to upgrade JBoss or should one just re-write the client from scratch with a newer technology e.g Spring? What is the best practice in a situation like this?
By the way this client is not a big application, it is used by only 6 users.
As proposed by Michele Dorigatti, Here are some more details on the project:
I already spent an estimate of 15 m/d on the upgrade proces.
We are required to implement the solution in 3 weeks from now on.
The app itself isn't that large, it consists of 1 login screen and 1 main view. There are several functionalities which would make up to maybe 15-20 use cases.
The team for the project consists of 2 developers (One being me), who have another project on their hand.
The app functions mainly on Oracle stored procedures and works maybe on 5-10 DB tables.
Also here is an example code snippet from the app
package tr.com.splogin;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.AbstractServerLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.sql.DataSource;
import java.security.Principal;
import java.security.acl.Group;
import java.sql.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class SPLoginModule extends AbstractServerLoginModule {
private static final int USER_LOCKEDOUT = 23;
private static final int USER_VALFAIL = 24;
private static final int USER_MAXATTEMPTS = 25;
private static final String ROLE_GROUP_NAME = "Roles";
private static final String ID_GROUP_NAME = "Id";
private static Logger logger = LoggerFactory.getLogger(SPLoginModule.class);
private static final SimplePrincipal GUEST = new SimplePrincipal("guest");
private static boolean initialized = false;
private static boolean initFailed = false;
private static Connection conn;
private static CallableStatement cs;
private static PreparedStatement ps;
private static ResultSet rs;
/**
* The principal to use when a null username and password are seen
*/
private static Principal unauthenticatedIdentity;
private static Map options;
/**
* The roles of the authenticated user
*/
private Group[] roleSets;
/**
* The proof of login identity
*/
private char[] credential;
/**
* The login identity
*/
private Principal identity;
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
logger.info("initialize start");
System.out.println("initialize start");
super.initialize(subject, callbackHandler, sharedState, options);
if (!initialized) {
this.options = options;
init(options);
initialized = true;
}
logger.info("initialize stop");
}
private String getUsername() {
String username = null;
if (getIdentity() != null)
username = getIdentity().getName();
return username;
}
public boolean login() throws LoginException {
System.out.println("login is called.");
String[] info = getUsernameAndPassword();
String username = info[0];
String password = info[1];
logger.info(username);
logger.info(password);
super.loginOk = false;
if (username == null && password == null) {
identity = unauthenticatedIdentity;
Group roles = new SimpleGroup(ROLE_GROUP_NAME);
Set groups = new HashSet();
groups.add(roles);
roles.addMember(GUEST);
roleSets = new Group[groups.size()];
groups.toArray(roleSets);
logger.info("Authenticating as unauthenticatedIdentity=" + identity);
}
if (identity == null) {
identity = new SimplePrincipal(username);
login(username, password);
}
super.loginOk = true;
logger.info("User '" + identity + "' authenticated, loginOk=" + loginOk);
return true;
}
public Principal getIdentity() {
return identity;
}
public Group[] getRoleSets() {
return roleSets;
}
private void login(String username, String password) throws LoginException {
System.out.println("login is called.");
try {
int userIdCode = 3;
int resultCode = 4;
int result, userId;
cs.setString(1, username);
cs.setString(2, password);
cs.registerOutParameter(userIdCode, Types.INTEGER);
cs.registerOutParameter(resultCode, Types.INTEGER);
cs.execute();
result = cs.getInt(resultCode);
if (result == 0) {
userId = cs.getInt(userIdCode);
logger.info("Id: " + userId);
Group roles = new SimpleGroup(ROLE_GROUP_NAME);
Group id = new SimpleGroup(ID_GROUP_NAME);
Set groups = new HashSet();
String roleName;
groups.add(roles);
groups.add(id);
ps.setInt(1, userId);
rs = ps.executeQuery();
id.addMember(new SimplePrincipal((new Integer(userId)).toString()));
while (rs.next()) {
roleName = rs.getString(1);
logger.debug("Action: " + roleName);
roles.addMember(new SimplePrincipal(roleName));
}
roles.addMember(GUEST);
roleSets = new Group[groups.size()];
groups.toArray(roleSets);
} else {
String message = new String();
roleSets = new Group[0];
switch (result) {
case USER_VALFAIL:
System.out.println("login is failed.");
message = new String("Login failed");
break;
case USER_LOCKEDOUT:
message = new String("User is locked out");
break;
case USER_MAXATTEMPTS:
message = new String("Max number of attempts reached, user is locked out");
break;
default:
message = new String("Unkown failed login error with code: " + result);
break;
}
logger.info("Error result code: " + result);
logger.info("Error message: " + message);
throw new FailedLoginException(message);
}
} catch (SQLException e) {
logger.error(e.toString());
init(options);
if (!initFailed)
login(username, password);
} finally {
try {
if (rs != null)
rs.close();
} catch (SQLException e1) {
logger.error(e1.toString());
}
}
}
private void init(Map options) {
logger.info("init");
try {
if (cs != null)
cs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
logger.error(e.toString());
}
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/OracleDS");
conn = ds.getConnection();
String sp_login = "{call admin_pck.pc_login(?,?,?,?)}";
String query_user_action = "select aa.name from admin_user au,admin_role ar,admin_action aa,admin_user_role aur,admin_role_action ara,owner o where au.id=? and aur.id_admin_user=au.id and aa.id=ara.id_admin_action and ara.id_admin_role=ar.id and ar.id=aur.id_role and o.id=aur.id_owner and o.id=au.id_primary_owner order by aa.name";
cs = conn.prepareCall(sp_login);
ps = conn.prepareStatement(query_user_action);
String name = (String) options.get("unauthenticatedIdentity");
if (name != null) {
unauthenticatedIdentity = new SimplePrincipal(name);
logger.info("Saw unauthenticatedIdentity=" + name);
}
initFailed = false;
} catch (NamingException e) {
logger.error(e.toString());
initFailed = true;
} catch (SQLException e) {
logger.error(e.toString());
initFailed = true;
}
}
/**
* Called by login() to acquire the username and password strings for
* authentication. This method does no validation of either.
*
* #return String[], [0] = username, [1] = password
* #throws LoginException thrown if CallbackHandler is not set or fails.
*/
protected String[] getUsernameAndPassword() throws LoginException {
String[] info = {null, null};
// prompt for a username and password
if (callbackHandler == null) {
throw new LoginException("Error: no CallbackHandler available to collect authentication information");
}
NameCallback nc = new NameCallback("User name: ");
PasswordCallback pc = new PasswordCallback("Password: ", false);
Callback[] callbacks = {nc, pc};
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = nc.getName();
char[] tmpPassword = pc.getPassword();
if (tmpPassword != null) {
credential = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
pc.clearPassword();
password = new String(credential);
}
} catch (java.io.IOException e) {
throw new LoginException(e.toString());
} catch (UnsupportedCallbackException e) {
throw new LoginException("CallbackHandler does not support: " + e.getCallback());
}
info[0] = username;
info[1] = password;
return info;
}
}
I have to do a Login form with Java, using three layer architecture and a database, I'm using SQL Server.
In my DA class I have this code: Basically what I'm trying to do is to send the jText user and jText password to the setPassword and setUser from the BL class.
u.setLogin(jtxtUsuario.getText());
u.setContrasenia(jtxtPassword.getText());
DA.DB.getConexion();
if (DA.DB.getStatus()) {
new jfrmInterno().setVisible(true);
}else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
In my BL class I have this code: In the method "validarUsuario" im sending the user and pass to the "setUsuario" method in the DA class.
public void setLogin(String login) {
if(login != null && login.length() > 3) {
_login = login;
}else {
_login = "Usuario Incorrecto";
}
}
public String getLogin() {
return _login;
}
public void setContrasenia(String contrasenia) {
if(contrasenia != null && contrasenia.length() > 6) {
_contrasenia = contrasenia;
}else {
_contrasenia = "Contraseña Incorrecta";
}
}
public String getContrasenia() {
return _contrasenia;
}
public void validarUsuario() {
admin.setUsuario(getLogin(), getContrasenia());
}
public Colegio() {
this("","");
}
public Colegio(String login, String contrasenia) {
setLogin(login);
setContrasenia(contrasenia);
}
}
The problem I have is in the DA class, I dont know how I can use the jText user and password and validate it against the user and password I have in the DB from the DA class. I create a method in the DA class called "setUsuario" which receives the user and password from the jText, but after that I dont know what else I can do, the idea is if the user and password are correct it should open a new Jframe.
public static Connection getConexion() {
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
status = true;
}catch (SQLException e) {
}
return cn;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
In your DA class, you have to check if there is a record exists or not in the database like this,
public static boolean getConexion() { // change it to boolean because it returns boolean value
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (rs.next) {
status = true;
}
} catch (SQLException e) {
}
return status;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
And in your view, you can pass the values to setUsuario() method and then call the getConexion() method which returns true if the user exists as shown below,
DA.DB.setUsuario(jtxtUsuario.getText(), jtxtPassword.getText());
if (DA.DB.getConexion()) {
new jfrmInterno().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
And I can't see the DA.DB.getStatus() method, so I have coded inside the getConexion() method to show what you are missing and this is not a GOOD PRACTICE to code inside the Database Connection and it should be in a separate class.
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 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.
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