JavaFX Sqlite check TextField wether its empty - java

I am struggling right now to check all my InputFields wether they == "".
I found many solutions here but somehow it doesnt work.
I have a RegistrationModal and a RegistrationController.
In the modal I tryed to check the fields like that:
public boolean RegisterUser(String user, String vorname, String nachname) throws SQLException {
PreparedStatement preparedStatement = null;
if (user == "" || vorname == "" || nachname == "") {
System.out.println("Fill in all fields");
return false;
}
// Here follows the SQL query the prepared statement and exequte
}
But it it never uses this if statement, I have no idea why?
I also tryed to catch the empty element in the controller:
public void Absenden(ActionEvent event) {
try {
if (registerModel.RegisterUser(txt_user.getText(), txt_vorname.getText(),
txt_nachname.getText())) {
if (registerModel.RegisterUser(txt_user.getText().trim().isEmpty(), txt_vorname.getText().trim().isEmpty(),
txt_nachname.getText().trim().isEmpty())) {
System.out.println("False! Do something?");
}
// Here opens the new window with a notification Registration was successfull
((Node) event.getSource()).getScene().getWindow().hide();
}
Here I had errors so thats why two if statement which already seems weird, I had to autogenerate a new method in model to make this work with booleans, but still it never used this if statement.
I tryed to give only relevant code, otherwise it would be much more.
Maybe someone has an idea.
Thanks

Your condition will fail if it has one or more spaces as inputs.
You should always trim() and then check if the length is 0
i.e
user.trim().length==0
also If you want to check contents always use equals instead of ==

You should have try like this
if(use.trim.length<0)
{
// todo code !!
}

Related

Optimize the several multiple OR conditions in IF statement

I am new to java and trying to learn a better way of coding.Please let me know if I can replace the multiple OR conditions in the below ELSE IF statement with any other way to execute based on the username passed in the calling method :
public void verifyPermissions(String user, String level2, String Folder) {
if (user.equalsIgnoreCase("ABC_Username")) {
verifyXYZPermission(Folder);
verifyNoPermissionToDelete();
}
else if (user.equalsIgnoreCase("DEF_Username") || user.equalsIgnoreCase("GHI_Username")
|| user.equalsIgnoreCase("JKL_Username") || user.equalsIgnoreCase("MNO_Username")
|| user.equalsIgnoreCase("PQR_Username") || user.equalsIgnoreCase("STU_Username")
|| user.equalsIgnoreCase("VWX_Username")) {
if (user.equalsIgnoreCase("GHI_Username")) {
verifyNoPermissionToCreate(user, Folder, level2);
verifyNoPermissionToUpdate(Folder);
} else {
verifyCreatePermission(level2);
verifyPermisssionToUpdate(Folder);
}
}
}
Here's one way: define a Set<String> with the possible username values before the if block, and check against it. Notice how all the strings were lower-cased to avoid trouble:
Set<String> userNames = new HashSet<>();
userNames.add("def_username");
userNames.add("ghi_username");
userNames.add("jkl_username");
userNames.add("mno_username");
userNames.add("pqr_username");
userNames.add("stu_username");
userNames.add("vwx_username");
// assuming `user` is non-null
user = user.trim().toLowerCase();
if (user.equals("abc_username")) {
verifyXYZPermission(Folder);
verifyNoPermissionToDelete();
} else if (userNames.contains(user)) {
if (user.equals("ghi_username")) {
verifyNoPermissionToCreate(user, Folder, level2);
verifyNoPermissionToUpdate(Folder);
} else {
verifyCreatePermission(level2);
verifyPermisssionToUpdate(Folder);
}
}
Use a switch-case statement.
In the case blocks for each user you can then execute the appropriate permissions.
https://www.w3schools.com/java/java_switch.asp
user_lc=user.toLowerCase();
switch (user_lc){
case "abc_user":
//execute code
break;
case "def_user":
//execute code
break;
}
It's highly opinionated I guess. Here are various approaches I can think of:
OR as you have done, or
regex to reduce lines of code, or
switch-case, or
Using a Collection such as List or Set.
It's all based on author's choice.

Exceptions or null in java

I have the next doubt. According to good practices of java, how to manage the cases in which the object can not be found and we want to know why.
For example, if someone has problems logging in our system and we want to inform them exactly what is the problem, we cannot return null because we lose the reason for not being able to log in. For example:
public User login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
//getUserPassword return null if doesn't exist an user with username and password return null
User user = getUserPassword(username,password);
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
LOGGER.info("There is no such username and password: " + username);
} else if (usernameEmpty) {
LOGGER.info("Username can not be empty ");
} else if (passwordEmpty) {
LOGGER.info("Password can not be empty ");
}
return user;
}
I can think of two options with pros and cons to resolve it.
The first one consists in using Exceptions but I think that is not a good idea use different scenarios than expected like exceptions. For that reason, I discard it.
The second one is involve the object (User) in another object to manage the differents posibilities. For example, use something like this:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private String exceptionMessage;
//getters / setters / ..
}
public EntityObject<User> login(String username, String password) {
boolean usernameEmpty = (credentials.getUsername()==null || credentials.getUsername().isEmpty());
boolean passwordEmpty = (credentials.getPassword()==null || credentials.getPassword().isEmpty());
User user = getUserPassword(username,password);
EntityObject<User> entity = null;
if (!usernameEmpty && !passwordEmpty && user!=null) {
LOGGER.info("Found " + username);
entity = new EntityObject<User>(user);
} else if (!usernameEmpty && !passwordEmpty && user==null) {
entity = new EntityObject<User>("There is no such username and password: " + username);
} else if (usernameEmpty) {
entity = new EntityObject<User>("Username can not be empty ");
} else if (passwordEmpty) {
entity = new EntityObject<User>("Password can not be empty ");
}
return entity;
}
I like more this second option than the first one but i don't like that i have to change the method signature to return a different class (EntityObject) than the usual (User).
What is the usual? How is it usually managed?
many thanks
An exception should be used when there is something exceptional happening in the system. For a normal flow and something that is expected to happen you should avoid using exceptions.
Following the good SOLID principals your method should do just one thing. So if it is a method to find user by username and password I would say the best would be to return null (or empty optional if using optionals). The reason is not lost. Actually it is pretty clear - there is not such user found with the supplied username and password (this reason includes the problem with empty username and it's the user of the method's fault to supply empty username to a login method). Adding complex logic to the method and additional entities for such things will make your code harder to maintain and to understand. This method's job is not to handle validation anyway.
If that class is used by a website or its some kind of API then they can handle the validation (if username or password is empty).
For me, second options look better. Probably, to know what was the error instead of writing messages in java code, you can create enum with possible scenarios and resolve it in the Front-end code, if you really need a message, you can create constructor inside enum to store it. It will simplify support and work with an object in the future. Plus, adding more scenarios will not hurt you much.
Basic version:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD, NO_USERNAME, USER_DOES_NOT_EXIST, SUCCESS
}
}
Version with enum constructor:
public class EntityObject<t> {
//Is used to return the entity or entities if everything was fine
private t entity;
//Is used to inform of any checked exception
private enum auth {
NO_PASSWORD("Password cannot be empty"),
NO_USERNAME("Username cannot be empty"),
USER_OR_PASSWORD_DOES_NOT_EXIST("No such username or password exist"),
SUCCESS("OK");
public String message;
public auth(String message) {
this.message = message;
}
}
}
I would say that the second approach is pretty fine. If I were you I would do that.
If you really don't want to change the return value, you can add another method that checks if a user can log in:
public static final String SUCCESS = "Success"
public String checkLoginError(String username, String password) {
// do all the checks and return the error message
// return SUCCESS if no error
}
Now the login method can then be one line:
return getUserPassword(username,password);
And you can use it like this:
String loginResult = checkLoginError(...);
if (loginResult.equals(SUCCESS)) {
User loggedInUser = login(...)
} else {
// do stuff with the error message stored in loginResult
}
It seems like your problem is stemming from a method which is responsible for multiple concerns.
I'd argue that the login method shouldn't be checking whether these values are blank. There is presumably some kind of UI (graphical or not) which is taking a username and password - this should be the layer performing validation on the user input.
The login method should only be concerned with whether the given credentials match a user in your system or not. There's only two outcomes - yes or no. For this purpose, you can use Optional<User>. It should tolerate the strings being empty as this will never match a user anyway (presumably it's impossible for a user to exist in such a state).
Here's some pseudo-code:
void loginButtonPressed()
{
if (usernameTextBox.text().isEmpty())
{
errorPanel.add("Username cannot be blank");
}
else if (passwordTextBox.text().isEmpty())
{
errorPanel.add("Password cannot be blank");
}
else
{
login(usernameTextBox.text(), passwordTextBox.text());
// assign above result to a local variable and do something...
}
}
public Optional<User> login(String username, String password)
{
Optional<User> user = Optional.ofNullable(getUserPassword(username, password));
user.ifPresentOrElse(
user -> LOGGER.info("Found " + username),
() -> LOGGER.info("Not found")
);
return user;
}
Java's null values are one of the worst aspects of the language, as you cannot really tell if a method is receiving a null value until it happens. If you are using an IDE (I hope so) you can check if it can control whether you are passing a null value where there shouldn't be one (IntelliJ can do this by adding the #NotNull annotation to the method's parameters).
Since it can be dangerous, it is better to avoid passing nulls around, as it will certainly lead to an error as soon as your code gets a bit complex.
Also, I think it would be reasonable to check for null values only if there is a concrete chance that there could be one.
If you want to express that a value can be present or not, it's better to use Optional<T>. If, for some reason, a null value could be passed instead of a real value, you could create an utility method whose only concern is to verify that the parameters are correct:
public Optional<EntityObject<User>> login(String username, String password) {
//isNotNull shouldn't be necessary unless you can't validate your parameters
//before passing them to the method.
//If you can, it's not necessary to return an Optional
if (isNotNull(username, password)) {
//Since I don't know if a password must always be present or not
//I'm assuming that getUserPassword returns an Optional
return Optional.of(new EntityObject<User>(getUserPassword(username,password).orElse(AN_EMPTY_USER)));
} else {
return Optional.Empty();
}
}
Anyway, I think that validating the input shouldn't be a concern of the login method, even if you don't want to use Optional; it should be done in another method instead.

java jsp if statement

Following code gives me a big headache. Why does my if ignore rs.next() == true?
System.out.println(rs.next());
if (rs.next() == true) {
System.out.println("1");
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("success.jsp");
} else {
System.out.println("2");
out.println("Invalid password <a href='index.jsp'>try again</a>");
}
Console:
#1 SELECT * FROM users where username = 'test' and password = 'test'
#2 true
#3 2
What am I doing here wrong?
What am I doing here wrong?
You're calling next() twice. The first call returns true, but presumably the second returns false - which makes sense, if your query only returns a single result.
If you really want to print the value out for diagnostic purposes, save it in a local variable:
boolean nextResult = rs.next();
System.out.println(nextResult);
if (nextResult) {
...
} else {
...
}
Calling ResultSet#next() advances the underlying cursor. Assuming the username is really unique, if found the first call to next() will return true and advance the cursor. When the second call is made, the cursor has already exhausted all its data, so it returns false. If you want to use this value, you need to keep it instead of calling next() multiple times. E.g.:
boolean hasNext = rs.next();
System.out.println(hasNext);
if (hasNext) {
// Do stuff...
i did not get your problem exactly but first of all we should not write if statements like this
if (rs.next() == true) {
its wrong practice to check like this if(boolVar == true) it should be like this
if(boolVar){

Method retake in Java

I'm developing a project in which i have a method to know if a JTextField is empty or not, but i was wondering if a way to implement that method just once and send several JTextFields components to check if they are empty or not exists, if so, could you please tell me how?, here's my sample code.
public static void Vacio(JTextField txt){
if(txt.getText().trim().equals(null)==true){/*Message*/}
}
Also i would like to know if i could improve the method using some Lambda Expressions, beforehand.
Use :
if(txt.getText().trim().length()==0)
//Do something
Your code will not work because a blank string("") is not a null String. I simply check if the trimmed length() of TextField is 0.
A sample function:
public boolean isEmpty(JTextField jtf)
{
try{
jtf.getText();
}catch(NullPointerException e){return true;}
if(jtf.getText().trim().length() == 0)
return true;
return false;
}
I cannot imagine how adding Lambda expressions can improve what you're trying to do (?).
Anyway, to check for an empty String I'd probably use:
field.getText().trim().isEmpty()
You don't need to check for null but you do need to catch NullPointerException in the event that the underlying document in the JTextField is null.
For the other part of your quesiton, if you really want to check multiple JTextFields in one method you could pass them as a variable length argument list:
public static void vacio(JTextField... fields) {
for(JTextField field : fields) {
try {
if( field.getText().trim().isEmpty() ) {
// do something
}
}
catch(NullPointerException ex) {
// handle exception (maybe log it?)
}
}
}
and call it like:
vacio(field1, field2, field3);
But, generally speaking, keeping functions brief and only doing one thing is usually better than trying to make a function do too much.
One final aside, your method is named Vacio but java naming conventions suggest you should compose method names using mixed case letters, beginning with a lower case letter and starting each subsequent word with an upper case letter.
Check explicitly for null and then compare with "".
public static void Vacio(JTextField txt){
String str = null;
try {
str = txt.getText();
}
catch (NullPointerException npe) {
System.out.println("The document is null!");
return;
}
if(str.trim().equals("")==true){/*Message*/}
}

Returning a null array string in java

I am having a java class where I am executing a query and assigning the query result to an string array, finally return the array.
Everything works fine. But I want to return "no data" if the db values are empty (not the whole array). what can I do for this?
Code:
query="select `t1`,`t2`,`t3` from test";
PreparedStatement pre = conn.prepareStatement(query);
ResultSet res = pre.executeQuery();
String val[][] = new String[res.getRow()][3];
while (res.next()) {
val[i][0] = res.getString(1);
val[i][1] = res.getString(2);
val[i][2] = res.getString(3);
i++;
}
res.close();
conn.close();
pre.close();
return (val);
(Where I want the val[1][1] to be "No Data" if res.getString(2) is null).
No Data seems to be a value you display more than a logical value.
So you should decide of a special value and display it in a special way. We usually call this a sentry value.
This value could be null or a string that can't be in your db. (maybe it doesn't apply here as everything is often possible in a db).
Also note that it could be attractive to use an exception instead of this special value but it is actually a very poor use of exceptions, mostly for performance issues and hence it is a design to avoid if possible except if this value can lead to problems for your clients classes.
try this way
val[i][0] = (res.getString(1)!=null & !res.getString(1).equals(""))?res.getString(1).equals(""):"No Data";
val[i][1] = (res.getString(1)!=null & !res.getString(2).equals(""))?res.getString(3).equals(""):"No Data";
val[i][2] = (res.getString(1)!=null & !res.getString(3).equals(""))?res.getString(3).equals(""):"No Data";
use the only one "&" what happen when you check the condition with && first it will check for the first i.e. rs.getString(1)!=null if this is null or not it will check for the another condition i.e. rs.getString(1).equal("") so if you check and it will null then in second condition it will cause the error for NullPointerException.
while if you use only one & then it will check first condition if that was true then only it go for check the another condition otherwise not.
Add small helper methods like this:
public static String getValue(String value) {
return getValue(value, "No Data");
}
public static String getValue(String value, String default) {
return value == null ? default : value;
}
Use it like this:
val[i][0] = getValue(res.getString(1)); // standard
val[i][0] = getValue(res.getString(1), "NULL"); // with custom default message

Categories

Resources