So according to the Java API, Set::contains
returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))
So ... why is it this method returns false even IF the set contains exactly one element that is equal to creds
?
private boolean validate(Credentials creds){
Set<Credentials> acceptedUsers = getAcceptedUsers();
return acceptedUsers.contains(creds);
}
More specifically, I inserted some printlns
private boolean validate(Credentials creds){
Set<Credentials> acceptedUsers = getAcceptedUsers();
System.out.print("accepted users: ");
System.out.println(acceptedUsers);
System.out.print("accessing user: ");
System.out.println(creds);
System.out.println("items are equal: " + acceptedUsers.stream().map(c -> c.equals(creds)).collect(Collectors.toSet()));
System.out.println("access ok: " + (acceptedUsers.contains(creds) ? "YES" : "NO"));
return acceptedUsers.contains(creds);
}
and this is what it had to say:
accepted users: [[
foo
FCDE2B2EDBA56BF408601FB721FE9B5C338D10EE429EA04FAE5511B68FBF8FB9
]]
accessing user: [
foo
FCDE2B2EDBA56BF408601FB721FE9B5C338D10EE429EA04FAE5511B68FBF8FB9
]
items are equal: [true]
access ok: NO
getAcceptedUsers
currently returns a dummy set
private Set<Credentials> getAcceptedUsers(){
return new HashSet<Credentials>(){{add(new Credentials("foo","bar", false));}};
}
and Credentials
is implemented as
class Credentials{
final String username;
final String password;
public Credentials(String username, String password, boolean isPasswordHashed) {
this.username = username;
if(isPasswordHashed) this.password = password;
else {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
md.update(password.getBytes());
byte[] hash = md.digest();
this.password = (new HexBinaryAdapter()).marshal(hash);
}
}
@Override
public boolean equals(Object obj) {
if(obj == null) return false;
if(!(obj instanceof Credentials)) return false;
Credentials other = (Credentials)obj;
return this.username.equals(other.username) && this.password.equals(other.password);
}
@Override
public String toString() {
return String.format("[\n\t%s\n\t%s\n]", username,password);
}
}