Skip to content

Commit

Permalink
chore: Avoid comparing potential nulls
Browse files Browse the repository at this point in the history
  • Loading branch information
david-mackessy committed Oct 25, 2024
1 parent fef14c6 commit 2b4f747
Show file tree
Hide file tree
Showing 63 changed files with 129 additions and 113 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public static QueryOperator fromString(String string) {
}

// To still support NE operator until it gets removed
if (string.trim().equals("NE")) {
if ("NE".equals(string.trim())) {
return NEQ;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ public interface HasPath {
String getPath();

default boolean isKeyPath() {
return getPath().equals("_");
return "_".equals(getPath());
}

default boolean isValuePath() {
return getPath().equals(".");
return ".".equals(getPath());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static List<String> removeCustomFilters(List<String> filters) {
ListIterator<String> filterIterator = filters.listIterator();
while (filterIterator.hasNext()) {
String[] filterSplit = filterIterator.next().split(":");
if (filterSplit[1].equals("in") && filterSplit[0].equals("mentions")) {
if ("in".equals(filterSplit[1]) && "mentions".equals(filterSplit[0])) {
mentions.add(filterSplit[2]);
filterIterator.remove();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,6 @@ public static Instant maxDelayedExecutionTime(
private static boolean isUndefinedCronExpression(String cronExpression) {
return cronExpression == null
|| cronExpression.isEmpty()
|| cronExpression.equals("* * * * * ?");
|| "* * * * * ?".equals(cronExpression);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public enum ValueTypeMapping {
ValueTypeMapping::booleanConverter, ValueTypeMapping::booleanJsonExtractor, Boolean.class);

private static final UnaryOperator<String> BOOLEAN_JSON_EXTRACTOR =
value -> value.equalsIgnoreCase("true") ? "1" : "0";
value -> "true".equalsIgnoreCase(value) ? "1" : "0";

private final Function<String, Object> converter;
@Getter private final UnaryOperator<String> selectTransformer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ private void installApp(App app) {

@Override
public boolean isAccessible(App app) {
return app.getKey().equals("login")
return "login".equals(app.getKey())
|| CurrentUserUtil.hasAnyAuthority(
List.of(
Authorities.ALL.toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ public List<DataApprovalStatus> getDataApprovalStatuses(
final String[] approved = highestApproved == null ? null : highestApproved.split(SQL_CONCAT);
final int level = approved == null ? 0 : Integer.parseInt(approved[0]) - MAX_APPROVAL_LEVEL;
final boolean accepted =
approved == null ? false : approved[1].substring(0, 1).equalsIgnoreCase("t");
approved == null ? false : "t".equalsIgnoreCase(approved[1].substring(0, 1));
final long approvedOrgUnitId = approved == null ? 0 : Long.parseLong(approved[2]);

// null if not approved
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,11 +403,11 @@ private static boolean isAllField(String path) {
}

private boolean isDisplayShortName(String path) {
return path.equals("displayShortName") || path.endsWith(".displayShortName");
return "displayShortName".equals(path) || path.endsWith(".displayShortName");
}

private boolean isDisplayNameField(String path) {
return path.equals("displayName") || path.endsWith(".displayName");
return "displayName".equals(path) || path.endsWith(".displayName");
}

private static <T> List<T> map1to1(List<T> from, Predicate<T> when, UnaryOperator<T> then) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public List<T> query(Query query) {
? CurrentUserUtil.getCurrentUsername()
: "system-process";

if (!username.equals("system-process") && shareable && !query.isSkipSharing()) {
if (!"system-process".equals(username) && shareable && !query.isSkipSharing()) {

UserDetails userDetails =
query.getCurrentUserDetails() != null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ private static Property getProperty(
? jobType.getRelativeApiElements().get(field.getName())
: "";

if (relativeApiElements != null && !relativeApiElements.equals("")) {
if (relativeApiElements != null && !"".equals(relativeApiElements)) {

Check notice

Code scanning / CodeQL

Inefficient empty string test Note

Inefficient comparison to empty string, check for zero length instead.
property.setRelativeApiEndpoint(relativeApiElements);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void check(org.springframework.security.core.userdetails.UserDetails user

boolean userToImpersonateIsSuper =
userToImpersonate.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ALL"));
.anyMatch(grantedAuthority -> "ALL".equals(grantedAuthority.getAuthority()));

if ((!currentUser.isSuper() && userToImpersonateIsSuper)) {
throw new InsufficientAuthenticationException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)
return false;
}
String isEnabled = getConfiguration().getProperty(ConfigurationKey.OIDC_OAUTH2_LOGIN_ENABLED);
return isEnabled.equalsIgnoreCase("on");
return "on".equalsIgnoreCase(isEnabled);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,9 @@ private boolean storeDataValue(
targetValue = Integer.parseInt(targetDataValue.getValue());
}

if (operation.equals("+")) {
if ("+".equals(operation)) {
targetValue = targetValue + Integer.parseInt(value);
} else if (operation.equals("-")) {
} else if ("-".equals(operation)) {
targetValue = targetValue - Integer.parseInt(value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public class Options {
public Options(Map<String, String> options) {
this.options = options;
this.assumeTrue =
options.get("assumeTrue") == null || options.get("assumeTrue").equalsIgnoreCase("true");
options.get("assumeTrue") == null || "true".equalsIgnoreCase(options.get("assumeTrue"));
}

public Options() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public List<BaseDimensionalItemObject> getExpressionItems(DataDimensionItem data
* @return true when the expression is valid
*/
public boolean isValidExpressionItems(String expression) {
if (trimToNull(expression) == null || trimToEmpty(expression).equalsIgnoreCase("null")) {
if (trimToNull(expression) == null || "null".equalsIgnoreCase(trimToEmpty(expression))) {
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,9 @@ private static String fieldValueFormat(String[] strArrFldName, String fldValue)
int fieldType = Integer.parseInt(strArrFldName[3].substring(1));

if (fieldType == PdfFieldCell.TYPE_CHECKBOX) {
if (fldValue.compareTo("On") == 0) {
if ("On".compareTo(fldValue) == 0) {
fldValue = "true";
} else if (fldValue.compareTo("Off") == 0) {
} else if ("Off".compareTo(fldValue) == 0) {
fldValue = null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ private static List<FieldPath> expandField(String field, String prefix) {
token = fieldSplit[idx];

if ((containsAny(token, ":", "~", "|"))) {
if (token.equals(":")) {
if (":".equals(token)) {
idx++;
}

Expand Down Expand Up @@ -120,8 +120,8 @@ private static List<FieldPath> expandField(String field, String prefix) {
transformerParameters.add(transformerNameBuilder.toString());
break;
} else if (isFieldSeparator(token)
|| (token.equals("]") && !insideParameters)
|| (token.equals("[") && !insideParameters)) {
|| ("]".equals(token) && !insideParameters)
|| ("[".equals(token) && !insideParameters)) {
idx--;
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ private void applyAccess(
object,
fieldPaths,
isSkipSharing,
s -> s.equals("access") || s.endsWith(".access"),
s -> "access".equals(s) || s.endsWith(".access"),
o -> {
if (o instanceof IdentifiableObject identifiableObject) {
identifiableObject.setAccess(aclService.getAccess(identifiableObject, userDetails));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ private ComplexNode getProperties(Property currentProperty, Object object, List<
private boolean isBaseIdentifiableObjectIdOnly(
@Nonnull Object object, @Nonnull List<String> fields) {
return fields.size() == 1
&& fields.get(0).equals("id")
&& "id".equals(fields.get(0))
&& object instanceof BaseIdentifiableObject;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,57 +54,57 @@ public FieldMap parse(String fields) {

// if we reach a field transformer, parse it out here (necessary to
// allow for () to be used to handle transformer parameters)
if ((c.equals(":") && fieldSplit[i + 1].equals(":")) || c.equals("~") || c.equals("|")) {
if ((":".equals(c) && ":".equals(fieldSplit[i + 1])) || "~".equals(c) || "|".equals(c)) {

Check failure

Code scanning / CodeQL

Array index out of bounds Error

This array access might be out of bounds, as the index might be equal to the array length.
boolean insideParameters = false;

for (; i < fieldSplit.length; i++) {
c = fieldSplit[i];

if (StringUtils.isAlphanumeric(c) || c.equals(":") || c.equals("~") || c.equals("|")) {
if (StringUtils.isAlphanumeric(c) || ":".equals(c) || "~".equals(c) || "|".equals(c)) {
builder.append(c);
} else if (c.equals("(")) // start parameter
} else if ("(".equals(c)) // start parameter
{
insideParameters = true;
builder.append(c);
} else if (insideParameters && c.equals(";")) // allow
} else if (insideParameters && ";".equals(c)) // allow
// parameter
// separator
{
builder.append(c);
} else if ((insideParameters && c.equals(")"))) // end
} else if ((insideParameters && ")".equals(c))) // end
{
builder.append(c);
break;
} else if (c.equals(",") || (c.equals("[") && !insideParameters)) // rewind
} else if (",".equals(c) || ("[".equals(c) && !insideParameters)) // rewind
// and
// break
{
i--;
break;
}
}
} else if (c.equals(",")) {
} else if (",".equals(c)) {
putInMap(fieldMap, joinedWithPrefix(builder, prefixList));
builder = new StringBuilder();
} else if (c.equals("[") || c.equals("(")) {
} else if ("[".equals(c) || "(".equals(c)) {
prefixList.add(builder.toString());
builder = new StringBuilder();
} else if (c.equals("]") || c.equals(")")) {
} else if ("]".equals(c) || ")".equals(c)) {
if (!builder.toString().isEmpty()) {
putInMap(fieldMap, joinedWithPrefix(builder, prefixList));
}

prefixList.remove(prefixList.size() - 1);
builder = new StringBuilder();
} else if (StringUtils.isAlphanumeric(c)
|| c.equals("*")
|| c.equals(":")
|| c.equals(";")
|| c.equals("~")
|| c.equals("!")
|| c.equals("|")
|| c.equals("{")
|| c.equals("}")) {
|| "*".equals(c)
|| ":".equals(c)
|| ";".equals(c)
|| "~".equals(c)
|| "!".equals(c)
|| "|".equals(c)
|| "{".equals(c)
|| "}".equals(c)) {
builder.append(c);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ public enum Defaults {
EXCLUDE;

public boolean isExclude() {
return this.name().equals("EXCLUDE");
return "EXCLUDE".equals(this.name());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ public class ReferenceTrackerEntity {
private final String parentUid;

public boolean isRoot() {
return this.parentUid.equals("ROOT");
return "ROOT".equals(this.parentUid);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public void migrate(final Context context) throws Exception {
+ "WHERE table_name = 'jobconfiguration' AND column_name = 'jobtype';";
try (Statement stmt = context.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(sql); ) {
if (rs.next() && rs.getString("data_type").equals("bytea")) {
if (rs.next() && "bytea".equals(rs.getString("data_type"))) {
continueWithMigration = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private void migrateJobStatusColumn(final Context context) throws Exception {
boolean continueWithMigration = false;
try (Statement stmt = context.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(CHECK_JOB_STATUS_DATA_TYPE_SQL); ) {
if (rs.next() && rs.getString("data_type").equals("bytea")) {
if (rs.next() && "bytea".equals(rs.getString("data_type"))) {
continueWithMigration = true;
}
}
Expand Down Expand Up @@ -142,7 +142,7 @@ private void migrateLastExecutedStatusColumn(final Context context) throws Excep
boolean continueWithMigration = false;
try (Statement stmt = context.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(CHECK_LAST_EXECUTED_STATUS_DATA_TYPE_SQL); ) {
if (rs.next() && rs.getString("data_type").equals("bytea")) {
if (rs.next() && "bytea".equals(rs.getString("data_type"))) {
continueWithMigration = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public void migrate(final Context context) throws Exception {
boolean continueWithMigration = false;
try (Statement stmt = context.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(CHECK_SYSTEM_SETTING_VALUE_TYPE_SQL); ) {
if (rs.next() && rs.getString("data_type").equals("bytea")) {
if (rs.next() && "bytea".equals(rs.getString("data_type"))) {
continueWithMigration = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,12 @@ private static void executeAfterMethod(MethodExecutionContext executionContext)
String packageName = className.substring(0, pos);

if (className.contains("org.hisp.dhis.cacheinvalidation.KnownTransactionsService")
|| methodName.equals("getSingleResult")
|| methodName.equals("doFilterInternal")) {
|| "getSingleResult".equals(methodName)
|| "doFilterInternal".equals(methodName)) {
break;
}

if (packageName.startsWith("org.hisp.dhis") && !methodName.equals("executeAfterMethod")) {
if (packageName.startsWith("org.hisp.dhis") && !"executeAfterMethod".equals(methodName)) {
StackTraceElement nextElement = stackTrace[i - 1];
String methodName1 = nextElement.getMethodName();
String className1 = nextElement.getClassName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private Properties getAdditionalProperties(DhisConfigurationProvider dhisConfig)
"hibernate.current_session_context_class",
"org.springframework.orm.hibernate5.SpringSessionContext");

if (dhisConfig.getProperty(USE_SECOND_LEVEL_CACHE).equals("true")) {
if ("true".equals(dhisConfig.getProperty(USE_SECOND_LEVEL_CACHE))) {
properties.put(AvailableSettings.USE_SECOND_LEVEL_CACHE, "true");
properties.put(AvailableSettings.CACHE_REGION_FACTORY, JCacheRegionFactory.class.getName());
properties.put(AvailableSettings.USE_QUERY_CACHE, dhisConfig.getProperty(USE_QUERY_CACHE));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public Connection connect(String s, Properties properties) throws SQLException {

@Override
public boolean acceptsURL(String url) throws SQLException {
return url.equals("jdbc:fake:db");
return "jdbc:fake:db".equals(url);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ public static boolean isZero(String value) {
* @return if the provided string argument is to be considered as a boolean.
*/
public static boolean isBool(String value) {
return value != null && (value.equals("true") || value.equals("false"));
return value != null && ("true".equals(value) || "false".equals(value));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ default HttpResponse perform(HttpMethod method, String url, RequestComponent...
List<Header> headers = new ArrayList<>();
for (RequestComponent c : components) {
if (c instanceof Header header) {
if (header.name().equalsIgnoreCase("ContentType")) {
if ("ContentType".equalsIgnoreCase(header.name())) {
// last provided content type wins
contentMediaType = header.value().toString();
} else {
Expand Down Expand Up @@ -277,7 +277,7 @@ public boolean success() {
* @return raw content body in UTF-8 encoding
*/
public String content(String contentType) {
if (contentType.equals("application/json")) {
if ("application/json".equals(contentType)) {
fail("Use one of the other content() methods for JSON");
}
String actualContentType = header("Content-Type");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public String getNamespaceURI(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("No prefix provided!");
} else {
if (prefix.equals("d")) {
if ("d".equals(prefix)) {
return "http://dhis2.org/schema/dxf/2.0";
} else {
return XMLConstants.NULL_NS_URI;
Expand Down
Loading

0 comments on commit 2b4f747

Please sign in to comment.