In the below code i want to make "OrgLoginId" case insensitive. For example if OrgLoginId value is 'NSE' and in table org_loginid='Nse' then also I should get the result. Pls help me..
My Code:
public String getLoginId(String OrgLoginId) {
LOGGER.info("Inside getLoginId method : start");
List result=null;
String loginId=null;
try
{
org.hibernate.Session session= sessionFactory.openSession();
String SQL_QUERY = "select org_loginid from users where org_loginid='"+OrgLoginId+"'";
Query query = session.createSQLQuery(SQL_QUERY);
result=query.list();
loginId=(String)result.get(0);
}
catch (Exception e) {
return null;
}
return loginId;
}
Related
I am new to PostgreSQL and Java and seem to be unable to write to the database with the following transaction. The transaction try block was removed in efforts to test all cases.
'''
public void transaction_return(int cid, String movie_id) throws Exception {
begin_transaction();
int has_movie = helper_who_has_this_movie(movie_id);
(new BufferedReader(new InputStreamReader(System.in))).readLine();
return_mov_stmt.clearParameters();
return_mov_stmt.setInt(1,cid);
return_mov_stmt.setString(2,movie_id);
return_mov_stmt.executeUpdate();
System.out.println("has_movie" + has_movie);
if (has_movie != cid) {
rollback_transaction();
System.out.println("You are not currently renting this movie.");
} else {
commit_transaction();
}
}
'''
I am wondering if this is doing anything to the database.
The following is a seemingly identical transaction (in terms of syntax) that writes to the database. I cannot discern any difference.
'''
public void transaction_choose_plan(int cid, int pid) throws Exception {
try {
begin_transaction();
update_plan_stmt.clearParameters();
update_plan_stmt.setInt(1,pid);
update_plan_stmt.setInt(2,cid);
update_plan_stmt.executeUpdate();
// rollback while > max_rent
int mov_2_rent = mov_2_rent_remaining(cid);
if (mov_2_rent < 0) {
rollback_transaction();
System.out
.println("You can switch to this plan after returning some movies.");
} else {
commit_transaction();
}
} catch (SQLException e) {
try {
rollback_transaction();
} catch (SQLException se) {
}
}
}
'''
The PreparedStatements are as follows:
'''
private String update_plan_sql = "UPDATE mem_cust SET pid = ? WHERE cid = ?";
private PreparedStatement update_plan_stmt;
private String return_mov_sql = "UPDATE his_rent SET status_rent = 'closed' WHERE cid = ? AND movie_id = ?";
private PreparedStatement return_mov_stmt;
'''
I am writing a program that acts as a service and picks up emails from the email queue table, processes them and sends them out. Here is something along how I did it, and it does work fine.
MySqlConnect con = new MySqlConnect();
public PreparedStatement preparedStatement = null;
public Connection con1 = con.connect();
//pick up queue and send email
public void email() throws Exception {
try {
while(true) {
String sql = "SELECT id,user,subject,recipient,content FROM emailqueue WHERE status='Pending' ";
PreparedStatement statement = con1.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
String subject = rs.getString("subject");
String recipient = rs.getString("recipient");
String content = rs.getString("content");
String id = rs.getString("id");
String username = rs.getString("user");
String emailStatus = "DONE";
String errormsg = sendEmail(recipient, subject, content, id,username);
if (!errormsg.equals("")) {
emailStatus = "FAILED";
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
statement.close();
rs.close();
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: "+e.toString());
}
con1.close();
Thread.sleep(2000);
}
Now, I am clearly using JDBC to obtain the result set in the loop and process them as shown. Of course, I also need to specify my database connection in MySqlConnect.java properties. While all this works perfectly fine, I was wondering is there another way of achieving the same goal without using JDBC, i.e. specifying the connection properties?
I was thinking of Java Persistence. I am new to this.
Edit
I have been told to use JPA to achieve this and I have written it in this way:
public void email() throws Exception {
try {
while(true) {
String sql = "select p.id,p.user,p.subject,p.recipient,p.content from Emailqueue p where " +
"status='Pending'";
List<Object[]> list = em.createQuery(sql).getResultList();
for (Object[] obj : list) {
System.out.println(obj[0]);
System.out.println(obj[1]);
System.out.println(obj[2]);
System.out.println(obj[3]);
System.out.println(obj[4]);
}
}
} catch(Exception e) {
e.printStackTrace();
TerminalLogger.printMsg("Exception: " + e.toString());
}
From here, I would pass the parameters I want to the method. Is this way feasible?
Edit 2
Did it a bit different like below:
String id = ejbCon.getSettingsFacade().getid();
String username = ejbCon.getSettingsFacade().getUser();
String subject = ejbCon.getSettingsFacade().getSubject();
String recipient = ejbCon.getSettingsFacade().getRecipient();
String content = ejbCon.getSettingsFacade().getContent();
String errormsg = sendEmail(recipient, subject, content, id,username);
public String getContent() {
try {
String sql="Select content FROM emailqueue WHERE status='Pending'";
if (em == null) {
throw new Exception("could not found subject");
}
return (String) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Just a bit idea of how the method looks like, the other methods follow the same concept.
List<EmailQueue> emailList = em.createQuery(sql).getResultList();
for (EmailQueue obj : emailList) {
String emailStatus = "DONE";
String errormsg=sendEmail(obj.getRecipient(), obj.getSubject, obj.getContent(),obj.getId(),obj.getUsername());
if (!errormsg.equals("")) {
emailStatus = "FAILED"
}
TerminalLogger.printMsg("Status : " + emailStatus);
}
}
Before using JPA ,you must read about it WHY JPA
As discussed in the comments above, Spring Batch and Spring JPA is a good choice for your use-case,
you can follow and study about on the internet and follow the official document
Spring JPA tutorial link
Spring Batch tutorial link
Happy Learning, Hope more users would suggest other good options that you can choose from and apply to your use-case post evaluating their pros and cons
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
I have been trying to redirect the user that has logged into the system to their respective page after checking their email and password. But i am not sure about the logic behind that coding and when i try it it just response with the else statement. I have tried the validation of the email and password and that works fine and redirects to the correct page, but when i add the user type condition it doesnt work
I have tried including nested if statements, but i am not sure about its logic,it always executes the else statement.
loginControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email=request.getParameter("email");
String password=request.getParameter("pwrd");
User theUser=loginDbUtil.gettype(email);
if(loginDbUtil.check(email, password))
{
String p="pharmacist";
if(theUser.getType()==p)
{
// HttpSession session=request.getSession();
// session.setAttribute("email", email);
response.sendRedirect("medicine.jsp");
}
else
{
response.sendRedirect("index.jsp");
}
}else
{
response.sendRedirect("index.jsp");
}
}
}
loginDbUtil.java
public boolean check(String email,String password)
{
Connection myConn=null;
PreparedStatement myStmt=null;
ResultSet rs=null;
try
{
//get db connection
myConn=dataSource.getConnection();
//sql statemtn
String sql="select email,pass from usertab where email=? and pass=? ";
myStmt=myConn.prepareStatement(sql);
//set the param values for user
myStmt.setString(1, email);
myStmt.setString(2, password);
rs=myStmt.executeQuery();
if(rs.next())
{
return true;
}
}catch(Exception e)
{
e.printStackTrace();
}
return false;
}
public User gettype(String email) {
User type=null;
Connection myConn=null;
PreparedStatement myStmt=null;
ResultSet rs=null;
try
{
//get db connection
myConn=dataSource.getConnection();
//sql statemtn
String sql="select type from usertab where email=? ";
myStmt=myConn.prepareStatement(sql);
//set the param values for user
myStmt.setString(1, email);
rs=myStmt.executeQuery();
if(rs.next())
{
String t=rs.getString("type");
type =new User(t);
}
}catch(Exception e)
{
e.printStackTrace();
}
return type;
}
}
What i want is after the email and password is checked then next check for the users data type and redirect them to the correct page
In your loginControllerServlet.java change this to
if(theUser.getType()==p)
to this
if(theUser.getType().equals(p))
According to your logic, I think first of all, you should put the attribute type as an int, there will be less chances to have a type like Pharmacist and pharmacist.
Then to communicate with database check is correct, but I don't think the same about you getType method, this is what I would suggest to you :
1st : Create one bean (object) User as you seem to have done and put getters and setters, and put a constructor with all the attributes as parameters.
Example :
class User {
private int id;
private String mail;
private String password;
private int type;
public User() {
}
public User(int id, String mail, String password, int type) {
this.id = id;
this.mail = mail;
this.password = password;
this.type = type;
}
// Getters and setters
}
Then you check mail would return directly a user object, so you should have
class userDB {
public User login(String mail, String password) {
User user = new User();
String query = "select * from user where mail = ? and password = ?";
try {
PreparedStatement prep = conn.prepareStatement(query);
prep.setString(1,mail);
prep.setString(2,password);
ResultSet res = res.executeQuery();
if(res.first) {
user = new User(res.getInt("id"),res.getString("mail"),res.getString("password"),res.getInt("type"));
return user;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
And then in you Servlet you can write:
class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse respons) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher(your_jsp_relative_path).forward(request, respons);
}
public void doPost(HttpServletRequest request, HttpServletResponse respons) throws ServletException, IOException {
String mail = (String) request.getParameter("mail');
String password = (String) request.getParameter("mail');
User user = new UserDB().login(mail, password);
if(user != null){
int type = user.getType();
switch(type){
case 0 :
respons.sendRedirect("type_0_page");
break;
case 1 :
respons.sendRedirect("type_1_page");
break;
case 2 :
respons.sendRedirect("type_2_page");
break;
default :
repons.sendRedirect("/error500.jsp");
break;
}
}else{
this.getServletContext().getRequestDispatcher(your_jsp_relative_path).forward(request, respons);
}
}
}
This question already has answers here:
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 5 years ago.
I have a database and it has a table user which consists of many attributes like name ,email,etc. Also it has username and password in VARCHAR datatype. I wrote two classes LoginModel and Controller. controller has method loginit through which it checks if login method from LoginModel returns true or not. I am not able to find out why LoginModel always returns false. Please help.
Here are my methods :
from class LoginModel
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
return false;
}
}
from class Controller
public void loginit() throws SQLException {
String userid = uid.getText();
String userpass = upass.getText();
try {
if (loginmodel.login(userid, userpass)) {
lblstatus.setText("YES");
}
else
lblstatus.setText("Invalid");
} catch (SQLException e) {
lblstatus.setText("No");
e.printStackTrace();
}
}
It is a JavaFX application. userid and userpass are ids of text-field and password-field respectively. lblstatus is label which always shows Invalid, can't figure out why!
Here is snapshot of my database
remove return false from the finally block. It will executed in case of execption and in case you get no exception.
finally {
preparedStatement.close();
resultSet.close();
return false;
}
Change your code to:
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
}
return false;
}
i have to update some rows in database using Hibernate and Struts2:
the method DAO where i put the requete is:
public void modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{Query query = session.createQuery("Update Processus set selectionne = '1' where"+cond );
// query.setString("idproc",idprocessus);
// query.setLong("idsi", identifiantsi);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
In my action class where i call the DAO, i specify the cond:
public String update(){
cond="id_processus="+checked;
procdao.modifier(cond);
return SUCCESS;
}
can u help me it doens't show any error in the console but the row's value don't change!!!!
Following code could be helpful: Processus Table name selectionne and idproc are column name
You need to execute the query
To check the number of updated rows.
public Boolean modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Boolean returnValue = false;
try {
Query query = session.createQuery("Update Processus set selectionne = '1' where idproc=:cond");
query.setString("cond", cond);
int noOfUpdate = query.executeUpdate();
returnValue = (noOfUpdate > 0);
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return returnValue;
}