public String generateURLSafeToken(String username, char[] password) throws CredentialTokenException {
this.tokenValid = false;
String token = null;
if ((username.length() < 1) || (username == null)) {
throw new CredentialTokenException("Username cannot be an empty string or null.");
}
if ((password.length < 1) || (password == null)) {
throw new CredentialTokenException("Password cannot be an empty or null.");
}
I am facing this error in line 4 and line 7 (username == null and password == null)
And I need this part in my code. I am trying isEmpty() instead of null but facing problems in that also . What is an alternate way or the solution to fix this SONAR error
The conditions which always evaluates to false are username == null and password == null.
Let's take the example of username. The operator || is short-circuiting meaning it won't evaluate the right hand side if the left hand side is true. Basically, there are 2 cases:
username given is not null. The condition username.length() < 1 is evaluated
true, we return directly and enter the if branchfalse, we try to evaluate username == null. But since the username given is not null, this always evaluate to false.username given is null. The condition username.length() < 1 is evaluated. This actually stops right there: it will throw a NullPointerException and will not evaluate the right hand side.Therefore, you can see that whenever the username == null condition was actually evaluated, the result was always false. This is what the SonarQube warning is telling you.
The solution here is to reverse your 2 conditions. Consider having
if (username == null || username.length() < 1)
instead. If you start over and go through each case, you'll notice that none of the expressions will always have the same result:
username given is not null. First condition clearly evaluates to false and the second is evaluated, which may return true or false.username given is null. The first condition clearly evaluated to true and short-circuits.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With