Browse Source

NO JIRA fix code smells after moving to lang3 library

tags/10.5.0.89998
Matteo Mara 1 month ago
parent
commit
7f3f44f830
26 changed files with 111 additions and 45 deletions
  1. 1
    0
      build.gradle
  2. 2
    2
      server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java
  3. 2
    2
      server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java
  4. 3
    3
      server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java
  5. 1
    0
      server/sonar-ce-task-projectanalysis/build.gradle
  6. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java
  7. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java
  8. 1
    1
      server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java
  9. 3
    3
      server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java
  10. 3
    3
      server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java
  11. 2
    2
      server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java
  12. 3
    3
      server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java
  13. 1
    1
      server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java
  14. 3
    3
      server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java
  15. 1
    0
      server/sonar-webserver-webapi/build.gradle
  16. 3
    3
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java
  17. 1
    1
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java
  18. 1
    1
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java
  19. 4
    5
      sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java
  20. 1
    1
      sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java
  21. 4
    4
      sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java
  22. 63
    0
      sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java
  23. 1
    0
      sonar-scanner-engine/build.gradle
  24. 1
    1
      sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java
  25. 1
    1
      sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java
  26. 1
    1
      sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java

+ 1
- 0
build.gradle View File

@@ -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'

+ 2
- 2
server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java View File

@@ -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);

+ 2
- 2
server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java View File

@@ -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 + "}");

+ 3
- 3
server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java View File

@@ -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;
}

+ 1
- 0
server/sonar-ce-task-projectanalysis/build.gradle View File

@@ -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'

+ 2
- 2
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java View File

@@ -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()

+ 2
- 2
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java View File

@@ -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("<b s=\"").append(textBlock.getStart())
.append("\" l=\"").append(length)
.append("\" t=\"").append(disableLink)
.append("\" r=\"").append(StringEscapeUtils.escapeXml(componentDbKey))
.append("\" r=\"").append(StringEscapeUtils.escapeXml10(componentDbKey))
.append("\"/>");
}
}

+ 1
- 1
server/sonar-ce/src/main/java/org/sonar/ce/queue/NextPendingTaskPicker.java View File

@@ -74,7 +74,7 @@ public class NextPendingTaskPicker {
* priority is always given to the task that is waiting longer - to avoid starvation
*/
private Optional<CeQueueDto> 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> 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"));

+ 3
- 3
server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/ComponentNewValue.java View File

@@ -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();
}

+ 3
- 3
server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/DevOpsPlatformSettingNewValue.java View File

@@ -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();
}

+ 2
- 2
server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/PermissionTemplateNewValue.java View File

@@ -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();
}

+ 3
- 3
server/sonar-db-dao/src/main/java/org/sonar/db/audit/model/UserNewValue.java View File

@@ -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);

+ 1
- 1
server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java View File

@@ -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);
}


+ 3
- 3
server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/UserSessionInitializer.java View File

@@ -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) {

+ 1
- 0
server/sonar-webserver-webapi/build.gradle View File

@@ -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')

+ 3
- 3
server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgGenerator.java View File

@@ -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<String, String> 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);
}


+ 1
- 1
server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ScmAction.java View File

@@ -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)) {

+ 1
- 1
server/sonar-webserver-webapi/src/main/java/org/sonar/server/source/ws/ShowAction.java View File

@@ -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);

+ 4
- 5
sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java View File

@@ -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<RAW extends Trackable, BASE extends Trackable> {
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<RAW extends Trackable, BASE extends Trackable> {
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<RAW extends Trackable, BASE extends Trackable> {
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<RAW extends Trackable, BASE extends Trackable> {

LineHashKey(Trackable trackable) {
this.ruleKey = trackable.getRuleKey();
this.lineHash = StringUtils.defaultString(trackable.getLineHash(), "");
this.lineHash = Objects.toString(trackable.getLineHash(), "");
}

@Override

+ 1
- 1
sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.java View File

@@ -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;
}


+ 4
- 4
sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.java View File

@@ -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<String> 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");
}

+ 63
- 0
sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/ValidatingRequestTest.java View File

@@ -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;
}
}

+ 1
- 0
sonar-scanner-engine/build.gradle View File

@@ -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'

+ 1
- 1
sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/settings/AbstractSettingsLoader.java View File

@@ -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;

+ 1
- 1
sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/AbstractExclusionFilters.java View File

@@ -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);
}

+ 1
- 1
sonar-scanner-engine/src/main/java/org/sonar/scm/git/NativeGitBlameCommand.java View File

@@ -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("."));
}


Loading…
Cancel
Save