From 7f3f44f830868197b19cbd8a6e151cb7885d0213 Mon Sep 17 00:00:00 2001 From: Matteo Mara Date: Wed, 20 Mar 2024 15:14:10 +0100 Subject: [PATCH] NO JIRA fix code smells after moving to lang3 library --- build.gradle | 1 + .../sonar/auth/ldap/LdapContextFactory.java | 4 +- .../org/sonar/auth/ldap/LdapGroupMapping.java | 4 +- .../org/sonar/auth/ldap/LdapUserMapping.java | 6 +- .../build.gradle | 1 + .../source/PersistFileSourcesStep.java | 4 +- .../step/PersistDuplicationDataStep.java | 4 +- .../sonar/ce/queue/NextPendingTaskPicker.java | 2 +- .../db/audit/model/ComponentNewValue.java | 6 +- .../model/DevOpsPlatformSettingNewValue.java | 6 +- .../model/PermissionTemplateNewValue.java | 4 +- .../sonar/db/audit/model/UserNewValue.java | 6 +- .../email/EmailNotificationChannel.java | 2 +- .../UserSessionInitializer.java | 6 +- server/sonar-webserver-webapi/build.gradle | 1 + .../sonar/server/badge/ws/SvgGenerator.java | 6 +- .../org/sonar/server/source/ws/ScmAction.java | 2 +- .../sonar/server/source/ws/ShowAction.java | 2 +- .../core/issue/tracking/AbstractTracker.java | 9 ++- .../api/batch/rule/internal/NewRule.java | 2 +- .../sonar/api/impl/ws/ValidatingRequest.java | 8 +-- .../api/impl/ws/ValidatingRequestTest.java | 63 +++++++++++++++++++ sonar-scanner-engine/build.gradle | 1 + .../settings/AbstractSettingsLoader.java | 2 +- .../filesystem/AbstractExclusionFilters.java | 2 +- .../sonar/scm/git/NativeGitBlameCommand.java | 2 +- 26 files changed, 111 insertions(+), 45 deletions(-) create mode 100644 sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java diff --git a/build.gradle b/build.gradle index a4561ea8083..d83ee59d191 100644 --- a/build.gradle +++ b/build.gradle @@ -378,6 +378,7 @@ subprojects { dependency 'org.apache.commons:commons-csv:1.10.0' dependency 'org.apache.commons:commons-lang3:3.14.0' dependency 'org.apache.commons:commons-email:1.6.0' + dependency 'org.apache.commons:commons-text:1.11.0' dependency 'com.zaxxer:HikariCP:5.1.0' dependency('org.apache.httpcomponents:httpclient:4.5.14') { exclude 'commons-logging:commons-logging' diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java index bbcbf8b9f27..caa5da7f799 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java @@ -78,8 +78,8 @@ public class LdapContextFactory { private final String saslMaxbuf; public LdapContextFactory(org.sonar.api.config.Configuration config, String settingsPrefix, String ldapUrl) { - this.authentication = StringUtils.defaultString(config.get(settingsPrefix + ".authentication").orElse(null), DEFAULT_AUTHENTICATION); - this.factory = StringUtils.defaultString(config.get(settingsPrefix + ".contextFactoryClass").orElse(null), DEFAULT_FACTORY); + this.authentication = config.get(settingsPrefix + ".authentication").orElse(DEFAULT_AUTHENTICATION); + this.factory = config.get(settingsPrefix + ".contextFactoryClass").orElse(DEFAULT_FACTORY); this.realm = config.get(settingsPrefix + ".realm").orElse(null); this.providerUrl = ldapUrl; this.startTLS = config.getBoolean(settingsPrefix + ".StartTLS").orElse(false); diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java index 365016a20f6..3627db17362 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java @@ -44,9 +44,9 @@ public class LdapGroupMapping { */ public LdapGroupMapping(Configuration config, String settingsPrefix) { this.baseDn = config.get(settingsPrefix + ".group.baseDn").orElse(null); - this.idAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".group.idAttribute").orElse(null), DEFAULT_ID_ATTRIBUTE); + this.idAttribute = config.get(settingsPrefix + ".group.idAttribute").orElse(DEFAULT_ID_ATTRIBUTE); - String req = StringUtils.defaultString(config.get(settingsPrefix + ".group.request").orElse(null), DEFAULT_REQUEST); + String req = config.get(settingsPrefix + ".group.request").orElse(DEFAULT_REQUEST); this.requiredUserAttributes = StringUtils.substringsBetween(req, "{", "}"); for (int i = 0; i < requiredUserAttributes.length; i++) { req = StringUtils.replace(req, "{" + requiredUserAttributes[i] + "}", "{" + i + "}"); diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java index a32eb37eccd..ad99b820321 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java @@ -44,10 +44,10 @@ public class LdapUserMapping { public LdapUserMapping(Configuration config, String settingsPrefix) { String userBaseDnSettingKey = settingsPrefix + ".user.baseDn"; this.baseDn = config.get(userBaseDnSettingKey).orElseThrow(() -> new LdapException(String.format(MANDATORY_LDAP_PROPERTY_ERROR, userBaseDnSettingKey))); - this.realNameAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.realNameAttribute").orElse(null), DEFAULT_NAME_ATTRIBUTE); - this.emailAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.emailAttribute").orElse(null), DEFAULT_EMAIL_ATTRIBUTE); + this.realNameAttribute = config.get(settingsPrefix + ".user.realNameAttribute").orElse(DEFAULT_NAME_ATTRIBUTE); + this.emailAttribute = config.get(settingsPrefix + ".user.emailAttribute").orElse(DEFAULT_EMAIL_ATTRIBUTE); - String req = StringUtils.defaultString(config.get(settingsPrefix + ".user.request").orElse(null), DEFAULT_REQUEST); + String req = config.get(settingsPrefix + ".user.request").orElse(DEFAULT_REQUEST); req = StringUtils.replace(req, "{login}", "{0}"); this.request = req; } diff --git a/server/sonar-ce-task-projectanalysis/build.gradle b/server/sonar-ce-task-projectanalysis/build.gradle index 2468ec47745..4cca46f43b0 100644 --- a/server/sonar-ce-task-projectanalysis/build.gradle +++ b/server/sonar-ce-task-projectanalysis/build.gradle @@ -23,6 +23,7 @@ dependencies { api 'commons-codec:commons-codec' api 'commons-io:commons-io' api 'org.apache.commons:commons-lang3' + implementation 'org.apache.commons:commons-text' api 'com.google.code.gson:gson' api 'com.google.guava:guava' api 'com.google.code.findbugs:jsr305' diff --git a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java index 82d6d759ba9..b50b4786145 100644 --- a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java +++ b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java @@ -20,10 +20,10 @@ package org.sonar.ce.task.projectanalysis.source; import java.util.List; +import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang3.ObjectUtils; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit; @@ -130,7 +130,7 @@ public class PersistFileSourcesStep implements ComputationStep { boolean binaryDataUpdated = !dataHash.equals(previousDto.getDataHash()); boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash()); String revision = computeRevision(latestChangeWithRevision); - boolean revisionUpdated = !ObjectUtils.equals(revision, previousDto.getRevision()); + boolean revisionUpdated = !Objects.equals(revision, previousDto.getRevision()); boolean lineHashesVersionUpdated = previousDto.getLineHashesVersion() != lineHashesVersion; if (binaryDataUpdated || srcHashUpdated || revisionUpdated || lineHashesVersionUpdated) { FileSourceDto updatedDto = new FileSourceDto() diff --git a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java index 74323644cd8..1e04b79de3d 100644 --- a/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java +++ b/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java @@ -21,7 +21,7 @@ package org.sonar.ce.task.projectanalysis.step; import java.util.ArrayList; import java.util.List; -import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.text.StringEscapeUtils; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit; import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler; @@ -183,7 +183,7 @@ public class PersistDuplicationDataStep implements ComputationStep { xml.append(""); } } diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java b/server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java index fa6ac94fdb4..854d988cd84 100644 --- a/server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java +++ b/server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java @@ -74,7 +74,7 @@ public class NextPendingTaskPicker { * priority is always given to the task that is waiting longer - to avoid starvation */ private Optional submitOldest(DbSession session, String workerUuid, @Nullable CeTaskDtoLight eligibleForPeek, @Nullable CeTaskDtoLight eligibleForPeekInParallel) { - CeTaskDtoLight oldest = (CeTaskDtoLight) ObjectUtils.min(eligibleForPeek, eligibleForPeekInParallel); + CeTaskDtoLight oldest = ObjectUtils.min(eligibleForPeek, eligibleForPeekInParallel); Optional ceQueueDto = ceQueueDao.tryToPeek(session, oldest.getCeTaskUuid(), workerUuid); if (!Objects.equals(oldest, eligibleForPeek)) { ceQueueDto.ifPresent(t -> LOG.info("Task [uuid = " + t.getUuid() + "] will be run concurrently with other tasks for the same project")); diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java index 146ae5d33b3..c3ad625f4b9 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java @@ -19,9 +19,9 @@ */ package org.sonar.db.audit.model; +import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; @@ -116,8 +116,8 @@ public class ComponentNewValue extends NewValue { addField(sb, "\"qualifier\": ", getQualifier(qualifier), true); addField(sb, "\"description\": ", this.description, true); addField(sb, "\"path\": ", this.path, true); - addField(sb, "\"isPrivate\": ", ObjectUtils.toString(this.isPrivate), false); - addField(sb, "\"isEnabled\": ", ObjectUtils.toString(this.isEnabled), false); + addField(sb, "\"isPrivate\": ", Objects.toString(this.isPrivate, ""), false); + addField(sb, "\"isEnabled\": ", Objects.toString(this.isEnabled, ""), false); endString(sb); return sb.toString(); } diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java index 39040b313ca..c5ae6b04615 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java @@ -19,9 +19,9 @@ */ package org.sonar.db.audit.model; +import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; @@ -194,8 +194,8 @@ public class DevOpsPlatformSettingNewValue extends NewValue { addField(sb, "\"projectName\": ", this.projectName, true); addField(sb, "\"almRepo\": ", this.almRepo, true); addField(sb, "\"almSlug\": ", this.almSlug, true); - addField(sb, "\"isSummaryCommentEnabled\": ", ObjectUtils.toString(this.isSummaryCommentEnabled), false); - addField(sb, "\"isMonorepo\": ", ObjectUtils.toString(this.isMonorepo), false); + addField(sb, "\"isSummaryCommentEnabled\": ", Objects.toString(this.isSummaryCommentEnabled, ""), false); + addField(sb, "\"isMonorepo\": ", Objects.toString(this.isMonorepo, ""), false); endString(sb); return sb.toString(); } diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java index d7f135f1dd6..eeb09433cbc 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java @@ -19,9 +19,9 @@ */ package org.sonar.db.audit.model; +import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; import org.sonar.db.permission.template.PermissionTemplateDto; public class PermissionTemplateNewValue extends NewValue { @@ -168,7 +168,7 @@ public class PermissionTemplateNewValue extends NewValue { addField(sb, "\"userLogin\": ", this.userLogin, true); addField(sb, "\"groupUuid\": ", this.groupUuid, true); addField(sb, "\"groupName\": ", this.groupName, true); - addField(sb, "\"withProjectCreator\": ", ObjectUtils.toString(this.withProjectCreator), false); + addField(sb, "\"withProjectCreator\": ", Objects.toString(this.withProjectCreator, ""), false); endString(sb); return sb.toString(); } diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java index 70a4d389a5c..b8a6e404730 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java @@ -21,9 +21,9 @@ package org.sonar.db.audit.model; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; -import org.apache.commons.lang3.ObjectUtils; import org.sonar.api.utils.DateUtils; import org.sonar.db.user.UserDto; @@ -146,12 +146,12 @@ public class UserNewValue extends NewValue { addField(sb, "\"userLogin\": ", this.userLogin, true); addField(sb, "\"name\": ", this.name, true); addField(sb, "\"email\": ", this.email, true); - addField(sb, "\"isActive\": ", ObjectUtils.toString(this.isActive), false); + addField(sb, "\"isActive\": ", Objects.toString(this.isActive, ""), false); addField(sb, "\"scmAccounts\": ", String.join(",", scmAccounts), true); addField(sb, "\"externalId\": ", this.externalId, true); addField(sb, "\"externalLogin\": ", this.externalLogin, true); addField(sb, "\"externalIdentityProvider\": ", this.externalIdentityProvider, true); - addField(sb, "\"local\": ", ObjectUtils.toString(this.local), false); + addField(sb, "\"local\": ", Objects.toString(this.local, ""), false); addField(sb, "\"lastConnectionDate\": ", this.lastConnectionDate == null ? "" : DateUtils.formatDateTime(this.lastConnectionDate), true); endString(sb); diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java index b052d3110a5..f91a2fef12a 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java @@ -246,7 +246,7 @@ public class EmailNotificationChannel extends NotificationChannel { private void setSubject(Email email, EmailMessage emailMessage) { String subject = StringUtils.defaultIfBlank(StringUtils.trimToEmpty(configuration.getPrefix()) + " ", "") - + StringUtils.defaultString(emailMessage.getSubject(), SUBJECT_DEFAULT); + + Objects.toString(emailMessage.getSubject(), SUBJECT_DEFAULT); email.setSubject(subject); } diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java index 1cbb469704a..3e8a530f530 100644 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java +++ b/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java @@ -19,6 +19,7 @@ */ package org.sonar.server.authentication; +import java.util.Objects; import java.util.Optional; import java.util.Set; import org.slf4j.MDC; @@ -37,7 +38,6 @@ import org.sonar.server.user.TokenUserSession; import org.sonar.server.user.UserSession; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static org.apache.commons.lang3.StringUtils.defaultString; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY; import static org.sonar.api.utils.DateUtils.formatDateTime; @@ -140,8 +140,8 @@ public class UserSessionInitializer { } threadLocalSession.set(session); checkTokenUserSession(response, session); - request.setAttribute(ACCESS_LOG_LOGIN, defaultString(session.getLogin(), "-")); - MDC.put(USER_LOGIN_MDC_KEY, defaultString(session.getLogin(), "-")); + request.setAttribute(ACCESS_LOG_LOGIN, Objects.toString(session.getLogin(), "-")); + MDC.put(USER_LOGIN_MDC_KEY, Objects.toString(session.getLogin(), "-")); } private static void checkTokenUserSession(HttpResponse response, UserSession session) { diff --git a/server/sonar-webserver-webapi/build.gradle b/server/sonar-webserver-webapi/build.gradle index 198c26ee104..9e924b126cf 100644 --- a/server/sonar-webserver-webapi/build.gradle +++ b/server/sonar-webserver-webapi/build.gradle @@ -11,6 +11,7 @@ dependencies { implementation 'com.github.erosb:json-sKema' api 'io.prometheus:simpleclient_common' api 'io.prometheus:simpleclient_servlet' + implementation 'org.apache.commons:commons-text' api project(':server:sonar-ce-common') api project(':server:sonar-ce-task') diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java index 5a71ad54a9e..47d241556b1 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java @@ -23,7 +23,7 @@ import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.Map; import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.text.StrSubstitutor; +import org.apache.commons.text.StringSubstitutor; import org.sonar.api.measures.Metric; import org.sonar.api.server.ServerSide; @@ -150,7 +150,7 @@ public class SvgGenerator { .put(PARAMETER_LABEL, label) .put(PARAMETER_VALUE, value) .build(); - StrSubstitutor strSubstitutor = new StrSubstitutor(values); + StringSubstitutor strSubstitutor = new StringSubstitutor(values); return strSubstitutor.replace(badgeTemplate); } @@ -162,7 +162,7 @@ public class SvgGenerator { Map values = ImmutableMap.of( PARAMETER_TOTAL_WIDTH, valueOf(MARGIN + computeWidth(error) + MARGIN), PARAMETER_LABEL, error); - StrSubstitutor strSubstitutor = new StrSubstitutor(values); + StringSubstitutor strSubstitutor = new StringSubstitutor(values); return strSubstitutor.replace(errorTemplate); } diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java index 1f0bf728f0f..a504735a063 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java @@ -98,7 +98,7 @@ public class ScmAction implements SourcesWsAction { public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("key"); int from = Math.max(request.mandatoryParamAsInt("from"), 1); - int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); + int to = ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); boolean commitsByLine = request.mandatoryParamAsBoolean("commits_by_line"); try (DbSession dbSession = dbClient.openSession(false)) { diff --git a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java index 58c4ca0795b..fda6dc302c8 100644 --- a/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java +++ b/server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java @@ -84,7 +84,7 @@ public class ShowAction implements SourcesWsAction { public void handle(Request request, Response response) { String fileKey = request.mandatoryParam("key"); int from = Math.max(request.paramAsInt("from"), 1); - int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); + int to = ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto file = componentFinder.getByKey(dbSession, fileKey); diff --git a/sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java b/sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java index 41b4aa79f87..46978ee5fb1 100644 --- a/sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java +++ b/sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java @@ -25,7 +25,6 @@ import java.util.Collection; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nonnull; -import org.apache.commons.lang3.StringUtils; import org.sonar.api.rule.RuleKey; import static java.util.Comparator.comparing; @@ -66,7 +65,7 @@ public class AbstractTracker { protected LineAndLineHashKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.line = trackable.getLine(); - this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); + this.lineHash = Objects.toString(trackable.getLineHash(), ""); } @Override @@ -98,7 +97,7 @@ public class AbstractTracker { this.ruleKey = trackable.getRuleKey(); this.line = trackable.getLine(); this.message = trackable.getMessage(); - this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); + this.lineHash = Objects.toString(trackable.getLineHash(), ""); } @Override @@ -128,7 +127,7 @@ public class AbstractTracker { LineHashAndMessageKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.message = trackable.getMessage(); - this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); + this.lineHash = Objects.toString(trackable.getLineHash(), ""); } @Override @@ -186,7 +185,7 @@ public class AbstractTracker { LineHashKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); - this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); + this.lineHash = Objects.toString(trackable.getLineHash(), ""); } @Override diff --git a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java b/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java index f30a0b58371..660b31fa69b 100644 --- a/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java +++ b/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java @@ -66,7 +66,7 @@ public class NewRule { } public NewRule setStatus(@Nullable RuleStatus s) { - this.status = (RuleStatus) ObjectUtils.defaultIfNull(s, RuleStatus.defaultStatus()); + this.status = ObjectUtils.defaultIfNull(s, RuleStatus.defaultStatus()); return this; } diff --git a/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java b/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java index cc62c256c08..adb0d1a0171 100644 --- a/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java +++ b/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java @@ -22,6 +22,7 @@ package org.sonar.api.impl.ws; import java.io.InputStream; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; @@ -33,7 +34,6 @@ import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang3.StringUtils.defaultString; import static org.sonar.api.utils.Preconditions.checkArgument; /** @@ -68,7 +68,7 @@ public abstract class ValidatingRequest extends Request { public String param(String key) { WebService.Param definition = action.param(key); String rawValue = readParam(key, definition); - String rawValueOrDefault = defaultString(rawValue, definition.defaultValue()); + String rawValueOrDefault = Objects.toString(rawValue, definition.defaultValue()); String value = rawValueOrDefault == null ? null : trim(rawValueOrDefault); validateRequiredValue(key, definition, rawValue); if (value == null) { @@ -124,7 +124,7 @@ public abstract class ValidatingRequest extends Request { @Override public List paramAsStrings(String key) { WebService.Param definition = action.param(key); - String value = defaultString(readParam(key, definition), definition.defaultValue()); + String value = Objects.toString(readParam(key, definition), definition.defaultValue()); if (value == null) { return null; } @@ -152,7 +152,7 @@ public abstract class ValidatingRequest extends Request { private String readParam(String key, @Nullable WebService.Param definition) { checkArgument(definition != null, "BUG - parameter '%s' is undefined for action '%s'", key, action.key()); String deprecatedKey = definition.deprecatedKey(); - String param = deprecatedKey != null ? defaultString(readParam(deprecatedKey), readParam(key)) : readParam(key); + String param = deprecatedKey != null ? Objects.toString(readParam(deprecatedKey), readParam(key)) : readParam(key); if (param != null && param.contains("\0")) { throw new IllegalArgumentException("Request parameters are not allowed to contain NUL character"); } diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java new file mode 100644 index 00000000000..1c017da4d5d --- /dev/null +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java @@ -0,0 +1,63 @@ +/* + * SonarQube + * Copyright (C) 2009-2024 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.api.impl.ws; + +import org.junit.Test; +import org.mockito.Mockito; +import org.sonar.api.server.ws.WebService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ValidatingRequestTest { + + ValidatingRequest underTest = Mockito.mock(ValidatingRequest.class, Mockito.CALLS_REAL_METHODS); + @Test + public void paramReturnsTheDefaultValue_whenDefaultIsSetAndValueIsNot() { + underTest.setAction(mock(WebService.Action.class)); + WebService.Param param = mockParamWithDefaultValue("default"); + + when(underTest.action().param("param")).thenReturn(param); + + assertThat(underTest.param("param")).isEqualTo("default"); + } + + @Test + public void paramAsStringsReturnsTheDefaultValues_whenDefaultIsSetAndValueIsNot() { + underTest.setAction(mock(WebService.Action.class)); + WebService.Param param = mockParamWithDefaultValue("default,values"); + + when(underTest.action().param("param")).thenReturn(param); + + assertThat(underTest.paramAsStrings("param")).containsExactly("default", "values"); + } + + private static WebService.Param mockParamWithDefaultValue(String defaultValue) { + WebService.Param param = mock(WebService.Param.class); + when(param.defaultValue()).thenReturn(defaultValue); + when(param.possibleValues()).thenReturn(null); + when(param.maximumLength()).thenReturn(10); + when(param.maximumLength()).thenReturn(10); + when(param.maximumValue()).thenReturn(null); + when(param.maxValuesAllowed()).thenReturn(2); + return param; + } +} diff --git a/sonar-scanner-engine/build.gradle b/sonar-scanner-engine/build.gradle index 40ff8e0a2ba..de8669b288d 100644 --- a/sonar-scanner-engine/build.gradle +++ b/sonar-scanner-engine/build.gradle @@ -21,6 +21,7 @@ dependencies { api 'commons-codec:commons-codec' api 'commons-io:commons-io' api 'org.apache.commons:commons-lang3' + implementation 'org.apache.commons:commons-text' api 'com.google.code.gson:gson' api 'org.apache.commons:commons-csv' api 'com.google.protobuf:protobuf-java' diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java index 9c17a76a8c2..6df3e293910 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java @@ -29,7 +29,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.text.StringEscapeUtils; import org.sonar.api.impl.utils.ScannerUtils; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java index 36840fb6ac8..235f297fc69 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java @@ -179,7 +179,7 @@ public abstract class AbstractExclusionFilters { } static PathPattern[] prepareMainExclusions(String[] sourceExclusions, String[] testInclusions) { - String[] patterns = (String[]) ArrayUtils.addAll( + String[] patterns = ArrayUtils.addAll( sourceExclusions, testInclusions); return PathPattern.create(patterns); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java b/sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java index a4dede66e08..c219c831fa1 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java @@ -199,7 +199,7 @@ public class NativeGitBlameCommand { private static String formatGitSemanticVersion(String version) { return semanticVersionDelimiter .splitAsStream(version) - .takeWhile(NumberUtils::isNumber) + .takeWhile(NumberUtils::isCreatable) .collect(Collectors.joining(".")); } -- 2.39.5