Is it possible to add the data in to the sugarorm db by this method? I want to validate if the user is already in db, if yes then display "user available" else I want to insert the value in the database.Can some one help me with this validation?
private void postDataToSQLite() {
User.find(User.class, "email = ? and password = ?", email, password);
You Need to change the if condition. You are currently checking the user already exits or not. But issue is you trying compare two string using "==" this. But if you need to compare two string you have to use "equals"
Current Code
if (user.getEmail() != textInputEditTextEmail.getText().toString().trim() || user.getPassword() != textInputEditTextPassword.getText().toString().trim()) {
New Code
if (!user.getEmail().equals(textInputEditTextEmail.getText().toString().trim()) || !user.getPassword().equals(textInputEditTextPassword.getText().toString().trim()) ) {
Related
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.
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 !!
}
While working with objects, I am trying to compare one field of a queried object to the current user using the app
I was using an IF loop
if( ParseUser.CurrentUser() == object.getString("User"))
{
Do this
}
However, ParseUser.CurrentUser does not return in string format. So I declared a varible and tried that
String parseUser = ParseUser.CurrentUser.toString();
However, the string contains a completely different value then what the parse user for that particular user is called on the Parse server. Does something different happen on the server? Is there a correct way to return the ParseUser.CurrentUser in a string form?
ParseUser.getCurrentUser() returns a ParseUser Object, not a String. So what you want to do is compare the ObjectId of the current user object to your user String.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null && currentUser.getObjectId().equals(object.getString("User")){
//do stuff
}
Hope that helps..
Edit: Apparently the question wasn't clear so...
How do I find the password for a user in the datastore and check if it is equal to the password given to the method if that makes sense.
end of edit.
I have the following code for checking if the username exists, now I just need to check the password is correct for the given username.
public boolean Login(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username", FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users").setFilter(usernamefilter).setKeysOnly();
Entity theUser = datastore.prepare(validuserquery).asSingleEntity();
System.out.println(usernamein);
System.out.println(validuserquery);
System.out.println(theUser);
if(theUser == null) {
System.out.println("Username not found");
return false;
}
return true;
}
I am struggling to work out how I would do this even as pseudo code and I am really new to GAE and datastore but its for my A-Levels
I thought this addition would do it but theUser.getProperty("password") is null i don't really know what the user is in this code but i do know all the users in my data store have a password so none of them should be null
if(theUser == null) {
System.out.println("Username not found");
return false;
}
System.out.println(theUser.getProperty("password"));
if(passwordin.equals(theUser.getProperty("password"))){
return true;
}
return false;
If anything doesnt make sense or if you need more info tell me please as i do really need help :(
The setKeysOnly was my suggestion on a separate Q (and you haven't accepted my A there so it's, ahem, peculiar to see you use it here!) where you wanted just to check if the username was present or not.
With that you don't get any properties.
Remove it and the properties will be there (in your first Q you had a projection, which is fine if your user entity is large and you only need the password property out of many -- but it's an optimization, just like setKeysOnly is, and you hopefully know the rule -- first make it work, then make it fast!-).
I am trying to find a simple method to check to see if a user's input meets a couple criteria for an email address. I've read through many threads on this subject and most seem to want to validate the email address too. I'm not trying to build some super duper email address validator/checker. I'm trying to build a method that checks for these things:
The string entered by the user contains the '#' sign.
There are at least two characters before the '#' sign.
There is a '.' after the at sign followed by only three characters. The domain name can be as long as needed, but the string must end with "._ _ _". As in ".com" or ".net"...
I understand that this is not an all encompassing email address checker. That's not what I want though. I want just something this simple. I know that this is probably a routine question but I can't figure it out even after reading all of the seriously crazy ways of validating an email address.
This is the code I have so far: (Don't worry I already know it's pretty pathetic.... )
public static void checkEmail()
{
validEmail(emailAddresses);
if(validEmail(emailAddresses))
{
}
}
public static boolean validEmail(String email) {
return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{3}");
}
The javax.mail package provides a class just for this: InternetAddress. Use this constructor which allows you to enforce RFC822 compliance.
Not perfect, but gets the job done.
static boolean validEmail(String email) {
// editing to make requirements listed
// return email.matches("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}");
return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{3}");
}
void checkEmails() {
for(String email : emailAddresses) {
if(validEmail(email)) {
// it's a good email - do something good with it
}
else {
// it's a bad email - do something... bad to it? sounds dirty...
}
}
}
int indexOfAt = email.indexOf('#');
// first check :
if (indexOfAt < 0) {
// error
}
// second check :
if (indexOfAt < 2) {
// error
}
// third check :
int indexOfLastDot = email.lastIndexOf('.');
if (indexOfLastDot < indexOfAt || indexOfLastDot != (email.length() - 4)) {
// error
}
Read http://download.oracle.com/javase/6/docs/api/java/lang/String.html for the documentation of the String methods.