*/
package org.sonar.ce.task.projectanalysis.issue;
-import com.google.common.collect.ImmutableList;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
resolveStatus(dbIssue, issue);
}
- private void resolveStatus(IssueDto dbIssue, DefaultIssue issue) {
+ private static void resolveStatus(IssueDto dbIssue, DefaultIssue issue) {
issue.setStatus(dbIssue.getStatus());
}
- private void resolveResolution(IssueDto dbIssue, DefaultIssue issue) {
+ private static void resolveResolution(IssueDto dbIssue, DefaultIssue issue) {
issue.setResolution(dbIssue.getResolution());
}
- private void resolveEffortToFix(IssueDto dbIssue, DefaultIssue issue) {
+ private static void resolveEffortToFix(IssueDto dbIssue, DefaultIssue issue) {
issue.setGap(dbIssue.getGap());
}
- private void resolveSeverity(IssueDto dbIssue, DefaultIssue issue) {
+ private static void resolveSeverity(IssueDto dbIssue, DefaultIssue issue) {
if (dbIssue.isManualSeverity()) {
issue.setManualSeverity(true);
issue.setSeverity(dbIssue.getSeverity());
// else keep severity as declared in quality profile
}
- private void resolveAssignee(IssueDto dbIssue, DefaultIssue issue) {
+ private static void resolveAssignee(IssueDto dbIssue, DefaultIssue issue) {
issue.setAssigneeUuid(dbIssue.getAssigneeUuid());
}
}
double nclocs = nclocsOpt.get().getIntValue();
double comments = commentsOpt.get();
double divisor = nclocs + comments;
- if (divisor > 0d) {
- double value = 100d * (comments / divisor);
+ if (divisor > 0D) {
+ double value = 100D * (comments / divisor);
return Optional.of(Measure.newMeasureBuilder().create(value, context.getMetric().getDecimalScale()));
}
}
&& counter.getPublicUndocumentedApiValue().isPresent()) {
double publicApis = counter.getPublicApiValue().get();
double publicUndocumentedApis = counter.getPublicUndocumentedApiValue().get();
- if (publicApis > 0d) {
+ if (publicApis > 0D) {
double documentedAPI = publicApis - publicUndocumentedApis;
- double value = 100d * (documentedAPI / publicApis);
+ double value = 100D * (documentedAPI / publicApis);
return Optional.of(Measure.newMeasureBuilder().create(value, context.getMetric().getDecimalScale()));
}
}
if (newLines.isSet() && newDuplicatedLines.isSet()) {
int newLinesVariations = newLines.getValue();
int newDuplicatedLinesVariations = newDuplicatedLines.getValue();
- if (newLinesVariations > 0d) {
- double density = Math.min(100d, 100d * newDuplicatedLinesVariations / newLinesVariations);
+ if (newLinesVariations > 0D) {
+ double density = Math.min(100D, 100D * newDuplicatedLinesVariations / newLinesVariations);
return Optional.of(Measure.newMeasureBuilder().setVariation(density).createNoValue());
}
}
int tests = counter.testsCounter.getValue().get();
int errors = counter.testsErrorsCounter.getValue().get();
int failures = counter.testsFailuresCounter.getValue().get();
- double density = (errors + failures) * 100d / tests;
- return Optional.of(Measure.newMeasureBuilder().create(100d - density, decimalScale));
+ double density = (errors + failures) * 100D / tests;
+ return Optional.of(Measure.newMeasureBuilder().create(100D - density, decimalScale));
}
return Optional.empty();
}
underTest.execute(new TestComputationStepContext());
- verify(qProfileStatusRepository).register(eq(qp.getQpKey()), eq(REMOVED));
+ verify(qProfileStatusRepository).register(qp.getQpKey(), REMOVED);
verifyNoMoreInteractions(qProfileStatusRepository);
}
mockRawQProfiles(ImmutableList.of(qp1, qp2));
underTest.execute(new TestComputationStepContext());
- verify(qProfileStatusRepository).register(eq(qp1.getQpKey()), eq(UNCHANGED));
- verify(qProfileStatusRepository).register(eq(qp2.getQpKey()), eq(ADDED));
+ verify(qProfileStatusRepository).register(qp1.getQpKey(), UNCHANGED);
+ verify(qProfileStatusRepository).register(qp2.getQpKey(), ADDED);
verifyNoMoreInteractions(qProfileStatusRepository);
}
mockRawQProfiles(ImmutableList.of(qp2));
underTest.execute(new TestComputationStepContext());
- verify(qProfileStatusRepository).register(eq(qp2.getQpKey()), eq(UPDATED));
+ verify(qProfileStatusRepository).register(qp2.getQpKey(), UPDATED);
verifyNoMoreInteractions(qProfileStatusRepository);
}
mockRawQProfiles(ImmutableList.of(qp1));
underTest.execute(new TestComputationStepContext());
- verify(qProfileStatusRepository).register(eq(qp1.getQpKey()), eq(UNCHANGED));
+ verify(qProfileStatusRepository).register(qp1.getQpKey(), UNCHANGED);
verifyNoMoreInteractions(qProfileStatusRepository);
}
}
}
- private Optional<CeQueueDto> findPendingTask(String workerUuid, DbSession dbSession, CeQueueDao ceQueueDao, boolean excludeIndexationJob) {
+ private static Optional<CeQueueDto> findPendingTask(String workerUuid, DbSession dbSession, CeQueueDao ceQueueDao, boolean excludeIndexationJob) {
// try to find tasks including indexation job & excluding app/portfolio
// and if no match, try the opposite
// when excludeIndexationJob is false, search first excluding indexation jobs and including app/portfolio, then the opposite
private String remediationBaseEffort;
private String tags;
- public RuleMetadataDto() {
- // nothing to do here
- }
-
/**
* Name of on ad hoc rule.
* When {@link RuleDefinitionDto#isAdHoc} is true, this field should always be set
private long createdAt;
private long updatedAt;
+ public RuleMetadataDto() {
+ // nothing to do here
+ }
+
public String getRuleUuid() {
return ruleUuid;
}
return sqls;
}
- private void addColumns(StringBuilder sql, String updateKeyword, String typePrefix, boolean addNotNullableProperty) {
- for (Iterator<ColumnDef> columnDefIterator = columnDefs.iterator(); columnDefIterator.hasNext();) {
- sql.append(updateKeyword);
- addColumn(sql, columnDefIterator.next(), typePrefix, addNotNullableProperty);
- if (columnDefIterator.hasNext()) {
- sql.append(", ");
- }
- }
- }
-
private void addColumn(StringBuilder sql, ColumnDef columnDef, String typePrefix, boolean addNotNullableProperty) {
sql.append(columnDef.getName())
.append(" ")
}
}
}
-
- private static void checkRequiredParameter(String url, String val) {
- if (!url.contains(val)) {
- throw new MessageException(format("JDBC URL must have the property '%s'", val));
- }
- }
-
- private void checkRecommendedParameter(String url, String val) {
- if (!url.contains(val)) {
- LoggerFactory.getLogger(getClass()).warn("JDBC URL is recommended to have the property '{}'", val);
- }
- }
}
* This class holds all object keys accessible via Hazelcast
*/
public final class HazelcastObjects {
-
- private HazelcastObjects() {
- // Holder for clustered objects
- }
-
/**
* The key of replicated map that hold all operational processes
*/
* THe key of the replicated map holding the health state information of all SQ nodes.
*/
public static final String SQ_HEALTH_STATE = "sq_health_state";
+
+ private HazelcastObjects() {
+ // Holder for clustered objects
+ }
}
@Override
public QueryBuilder getQuery(ComponentTextSearchQuery query) {
return matchQuery(SORTABLE_ANALYZER.subField(query.getFieldName()), query.getQueryText())
- .boost(2.5f);
+ .boost(2.5F);
}
},
PREFIX(CHANGE_ORDER_OF_RESULTS) {
}
List<String> lowerCaseTokens = tokens.stream().map(t -> t.toLowerCase(Locale.ENGLISH)).collect(MoreCollectors.toList());
BoolQueryBuilder queryBuilder = prefixAndPartialQuery(lowerCaseTokens, query.getFieldName(), SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER)
- .boost(2f);
+ .boost(2F);
return Stream.of(queryBuilder);
}
},
if (tokens.isEmpty()) {
return Stream.empty();
}
- BoolQueryBuilder queryBuilder = boolQuery().boost(0.5f);
+ BoolQueryBuilder queryBuilder = boolQuery().boost(0.5F);
tokens.stream()
.map(text -> tokenQuery(text, query.getFieldName(), SEARCH_GRAMS_ANALYZER))
.forEach(queryBuilder::must);
@Override
public QueryBuilder getQuery(ComponentTextSearchQuery query) {
return matchQuery(SORTABLE_ANALYZER.subField(query.getFieldKey()), query.getQueryText())
- .boost(50f);
+ .boost(50F);
}
},
RECENTLY_BROWSED(CHANGE_ORDER_OF_RESULTS) {
if (recentlyBrowsedKeys.isEmpty()) {
return Stream.empty();
}
- return Stream.of(termsQuery(query.getFieldKey(), recentlyBrowsedKeys).boost(100f));
+ return Stream.of(termsQuery(query.getFieldKey(), recentlyBrowsedKeys).boost(100F));
}
},
FAVORITE(CHANGE_ORDER_OF_RESULTS) {
if (favoriteKeys.isEmpty()) {
return Stream.empty();
}
- return Stream.of(termsQuery(query.getFieldKey(), favoriteKeys).boost(1000f));
+ return Stream.of(termsQuery(query.getFieldKey(), favoriteKeys).boost(1000F));
}
};
// Build RuleBased contextual query
BoolQueryBuilder qb = boolQuery();
- String queryString = query.getQueryText();
-
- if (queryString != null && !queryString.isEmpty()) {
- BoolQueryBuilder textQuery = boolQuery();
- JavaTokenizer.split(queryString)
- .stream().map(token -> boolQuery().should(
- matchQuery(
- SEARCH_GRAMS_ANALYZER.subField(FIELD_RULE_NAME),
- StringUtils.left(token, DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH)).boost(20f))
- .should(
- matchPhraseQuery(
- ENGLISH_HTML_ANALYZER.subField(FIELD_RULE_HTML_DESCRIPTION),
- token).boost(3f)))
- .forEach(textQuery::must);
- qb.should(textQuery.boost(20f));
- }
+
+ BoolQueryBuilder textQuery = boolQuery();
+ JavaTokenizer.split(queryText)
+ .stream().map(token -> boolQuery().should(
+ matchQuery(
+ SEARCH_GRAMS_ANALYZER.subField(FIELD_RULE_NAME),
+ StringUtils.left(token, DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH)).boost(20f))
+ .should(
+ matchPhraseQuery(
+ ENGLISH_HTML_ANALYZER.subField(FIELD_RULE_HTML_DESCRIPTION),
+ token).boost(3F)))
+ .forEach(textQuery::must);
+ qb.should(textQuery.boost(20F));
// Match and partial Match queries
// Search by key uses the "sortable" sub-field as it requires to be case-insensitive (lower-case filtering)
- qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_KEY), queryString).operator(Operator.AND).boost(30f));
- qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_RULE_KEY), queryString).operator(Operator.AND).boost(15f));
- qb.should(termQuery(FIELD_RULE_LANGUAGE, queryString, 3f));
+ qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_KEY), queryText).operator(Operator.AND).boost(30F));
+ qb.should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_RULE_RULE_KEY), queryText).operator(Operator.AND).boost(15F));
+ qb.should(termQuery(FIELD_RULE_LANGUAGE, queryText, 3F));
return qb;
}
return list;
}
- private void failIfContainsIncompatiblePlugins(List<? extends PluginInfo> plugins) {
+ private static void failIfContainsIncompatiblePlugins(List<? extends PluginInfo> plugins) {
List<String> incompatiblePlugins = plugins.stream()
.filter(p -> FORBIDDEN_INCOMPATIBLE_PLUGINS.contains(p.getKey()))
.map(p -> "'" + p.getKey() + "'")
*/
private static final String RETURN_TO_PARAMETER = "return_to";
- /**
- * This parameter is used to allow the update of login
- */
- private static final String ALLOW_LOGIN_UPDATE_PARAMETER = "allowUpdateLogin";
-
private static final Type JSON_MAP_TYPE = new TypeToken<HashMap<String, String>>() {
}.getType();
assertThat(authenticationException.getSource()).isEqualTo(Source.oauth2(identityProvider));
assertThat(authenticationException.getLogin()).isNull();
assertThat(authenticationException.getPublicMessage()).isEqualTo("Email john@email.com is already used");
- verify(oAuthRedirection).delete(eq(request), eq(response));
+ verify(oAuthRedirection).delete(request, response);
verify(response).addCookie(cookieArgumentCaptor.capture());
Cookie cookie = cookieArgumentCaptor.getValue();
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sonarqube/sessions/unauthorized");
- verify(oAuthRedirection).delete(eq(request), eq(response));
+ verify(oAuthRedirection).delete(request, response);
}
@Test
verify(response).sendRedirect("/sessions/unauthorized");
assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
- verify(oAuthRedirection).delete(eq(request), eq(response));
+ verify(oAuthRedirection).delete(request, response);
}
@Test
public void redirect_if_reset_password_set() throws Exception {
underTest.doFilter(request, response, chain);
- verify(response).sendRedirect(eq("/account/reset_password"));
+ verify(response).sendRedirect("/account/reset_password");
}
@Test
underTest.doFilter(request, response, chain);
- verify(response).sendRedirect(eq("/sonarqube/account/reset_password"));
+ verify(response).sendRedirect("/sonarqube/account/reset_password");
}
@Test
underTest.doFilter(request, response, chain);
- verify(response).sendRedirect(eq("/sonarqube/account/reset_password"));
+ verify(response).sendRedirect("/sonarqube/account/reset_password");
}
@Test
json.endObject();
}
- private void writeAttribute(ProtobufSystemInfo.Attribute attribute, JsonWriter json) {
+ private static void writeAttribute(ProtobufSystemInfo.Attribute attribute, JsonWriter json) {
switch (attribute.getValueCase()) {
case BOOLEAN_VALUE:
json.prop(attribute.getKey(), attribute.getBooleanValue());
rule
.setName("Failed unit tests should be fixed")
.addTags("bug")
- .setHtmlDescription(
- "Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.")
+ .setHtmlDescription("Test failures or errors generally indicate that regressions have been introduced. "
+ + "Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.")
.setDebtRemediationFunction(rule.debtRemediationFunctions().linear("10min"))
.setGapDescription("number of failed tests")
.setSeverity(Severity.MAJOR);
return metricsToRegister;
}
- private void checkMetrics(Map<String, Metrics> metricsByRepository, Metrics metrics) {
+ private static void checkMetrics(Map<String, Metrics> metricsByRepository, Metrics metrics) {
for (Metric metric : metrics.getMetrics()) {
String metricKey = metric.getKey();
if (CoreMetrics.getMetrics().contains(metric)) {
AggregationBuilder aggregation = aggregationHelper.buildTermTopAggregation(
RESOLUTIONS.getName(), RESOLUTIONS.getTopAggregationDef(), RESOLUTIONS.getNumberOfTerms(),
NO_EXTRA_FILTER,
- t -> {
+ t ->
// add aggregation of type "missing" to return count of unresolved issues in the facet
t.subAggregation(
addEffortAggregationIfNeeded(query, AggregationBuilders
.missing(RESOLUTIONS.getName() + FACET_SUFFIX_MISSING)
- .field(RESOLUTIONS.getFieldName())));
- });
+ .field(RESOLUTIONS.getFieldName()))));
esRequest.aggregation(aggregation);
}
ASSIGNED_TO_ME.getTopAggregationDef(),
ASSIGNED_TO_ME.getNumberOfTerms(),
NO_EXTRA_FILTER,
- t -> {
+ t ->
// add sub-aggregation to return issue count for current user
aggregationHelper.getSubAggregationHelper()
.buildSelectedItemsAggregation(ASSIGNED_TO_ME.getName(), ASSIGNED_TO_ME.getTopAggregationDef(), new String[] {uuid})
- .ifPresent(t::subAggregation);
- });
+ .ifPresent(t::subAggregation));
esRequest.aggregation(aggregation);
}
}
@Override
QueryBuilder getQuery(String queryText) {
return matchQuery(SORTABLE_ANALYZER.subField(FIELD_NAME), queryText)
- .boost(2.5f);
+ .boost(2.5F);
}
},
PREFIX {
@Override
QueryBuilder getQuery(String queryText) {
return prefixAndPartialQuery(queryText, FIELD_NAME, FIELD_NAME)
- .boost(2f);
+ .boost(2F);
}
},
PREFIX_IGNORE_CASE {
QueryBuilder getQuery(String queryText) {
String lowerCaseQueryText = queryText.toLowerCase(Locale.ENGLISH);
return prefixAndPartialQuery(lowerCaseQueryText, SORTABLE_ANALYZER.subField(FIELD_NAME), FIELD_NAME)
- .boost(3f);
+ .boost(3F);
}
},
PARTIAL {
.map(text -> partialTermQuery(text, FIELD_NAME))
.forEach(queryBuilder::must);
return queryBuilder
- .boost(0.5f);
+ .boost(0.5F);
}
},
KEY {
QueryBuilder getQuery(String queryText) {
return wildcardQuery(SORTABLE_ANALYZER.subField(FIELD_KEY), "*" + queryText + "*")
.caseInsensitive(true)
- .boost(50f);
+ .boost(50F);
}
};
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchBitbucketServerReposAction implements AlmIntegrationsWsAction {
-
- private static final Logger LOG = Loggers.get(SearchBitbucketServerReposAction.class);
-
private static final String PARAM_ALM_SETTING = "almSetting";
private static final String PARAM_REPO_NAME = "repositoryName";
private static final String PARAM_PROJECT_NAME = "projectName";
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
-import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.project.ProjectDto;
private static final String PARAM_BRANCH = "branch";
private final UserSession userSession;
- private final DbClient dbClient;
private final ComponentFinder componentFinder;
- public ProjectBadgesSupport(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder) {
+ public ProjectBadgesSupport(UserSession userSession, ComponentFinder componentFinder) {
this.userSession = userSession;
- this.dbClient = dbClient;
this.componentFinder = componentFinder;
}
}
}
- private void checkPermission(boolean hasScanPerm) {
+ private static void checkPermission(boolean hasScanPerm) {
if (!hasScanPerm) {
throw new ForbiddenException("You're not authorized to push analysis results to the SonarQube server. " +
"Please contact your SonarQube administrator.");
WsUtils.writeProtobuf(builder.build(), request, response);
}
- private Ce.WorkersPauseStatus convert(CeQueue.WorkersPauseStatus status) {
+ private static Ce.WorkersPauseStatus convert(CeQueue.WorkersPauseStatus status) {
switch (status) {
case PAUSING:
return Ce.WorkersPauseStatus.PAUSING;
import org.sonar.server.issue.ws.UserResponseFormatter;
import org.sonar.server.rule.HotspotRuleDescription;
import org.sonar.server.security.SecurityStandards;
-import org.sonar.server.text.MacroInterpreter;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Hotspots;
import org.sonarqube.ws.Hotspots.ShowWsResponse;
private final TextRangeResponseFormatter textRangeFormatter;
private final UserResponseFormatter userFormatter;
private final IssueChangeWSSupport issueChangeSupport;
- private final MacroInterpreter macroInterpreter;
- public ShowAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport,
- HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter,
- UserResponseFormatter userFormatter, IssueChangeWSSupport issueChangeSupport, MacroInterpreter macroInterpreter) {
+ public ShowAction(DbClient dbClient, HotspotWsSupport hotspotWsSupport, HotspotWsResponseFormatter responseFormatter, TextRangeResponseFormatter textRangeFormatter,
+ UserResponseFormatter userFormatter, IssueChangeWSSupport issueChangeSupport) {
this.dbClient = dbClient;
this.hotspotWsSupport = hotspotWsSupport;
this.responseFormatter = responseFormatter;
this.textRangeFormatter = textRangeFormatter;
this.userFormatter = userFormatter;
this.issueChangeSupport = issueChangeSupport;
- this.macroInterpreter = macroInterpreter;
}
@Override
responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProject()));
}
- private void formatRule(ShowWsResponse.Builder responseBuilder, RuleDefinitionDto ruleDefinitionDto) {
+ private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDefinitionDto ruleDefinitionDto) {
SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(ruleDefinitionDto.getSecurityStandards());
SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
return false;
}
- private Set<String> parseTags(Map<String, Object> properties) {
+ private static Set<String> parseTags(Map<String, Object> properties) {
Set<String> result = new HashSet<>();
String tagsString = (String) properties.get(TAGS_PARAMETER);
if (!Strings.isNullOrEmpty(tagsString)) {
}
}
- private boolean isPR(@Nullable String pullRequest) {
+ private static boolean isPR(@Nullable String pullRequest) {
return pullRequest != null;
}
private final ResourceTypes resourceTypes;
public ComponentTreeAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, I18n i18n,
- ResourceTypes resourceTypes) {
+ ResourceTypes resourceTypes) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
private static Measures.Component.Builder toWsComponent(ComponentDto component, Map<MetricDto, ComponentTreeData.Measure> measures,
- Map<String, ComponentDto> referenceComponentsByUuid) {
+ Map<String, ComponentDto> referenceComponentsByUuid) {
Measures.Component.Builder wsComponent = componentDtoToWsComponent(component);
ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyResourceUuid());
if (referenceComponent != null) {
}
}
- private boolean isPR(@Nullable String pullRequest) {
+ private static boolean isPR(@Nullable String pullRequest) {
return pullRequest != null;
}
}
private Table<String, MetricDto, ComponentTreeData.Measure> searchMeasuresByComponentUuidAndMetric(DbSession dbSession, ComponentDto baseComponent,
- ComponentTreeQuery componentTreeQuery, List<ComponentDto> components, List<MetricDto> metrics) {
+ ComponentTreeQuery componentTreeQuery, List<ComponentDto> components, List<MetricDto> metrics) {
Map<String, MetricDto> metricsByUuid = Maps.uniqueIndex(metrics, MetricDto::getUuid);
MeasureTreeQuery measureQuery = MeasureTreeQuery.builder()
* </ul>
*/
private static void addBestValuesToMeasures(Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric, List<ComponentDto> components,
- List<MetricDto> metrics) {
+ List<MetricDto> metrics) {
List<MetricDtoWithBestValue> metricDtosWithBestValueMeasure = metrics.stream()
.filter(MetricDtoFunctions.isOptimizedForBestValue())
.map(new MetricDtoToMetricDtoWithBestValue())
}
private static List<ComponentDto> filterComponents(List<ComponentDto> components,
- Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric, List<MetricDto> metrics, ComponentTreeRequest wsRequest) {
+ Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric, List<MetricDto> metrics, ComponentTreeRequest wsRequest) {
if (!componentWithMeasuresOnly(wsRequest)) {
return components;
}
}
private static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
- Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
+ Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
return ComponentTreeSort.sortComponents(components, wsRequest, metrics, measuresByComponentUuidAndMetric);
}
import org.sonar.db.metric.MetricDto;
public class MeasureValueFormatter {
- private static final double DELTA = 0.000001d;
+ private static final double DELTA = 0.000001D;
private MeasureValueFormatter() {
// static methods
}
private static String formatBoolean(double value) {
- return Math.abs(value - 1.0d) < DELTA ? "true" : "false";
+ return Math.abs(value - 1.0D) < DELTA ? "true" : "false";
}
private static String formatInteger(double value) {
}
}
- private void insertAndPreserveOrder(OpeningHtmlTag newEntry, List<OpeningHtmlTag> openingHtmlTags) {
+ private static void insertAndPreserveOrder(OpeningHtmlTag newEntry, List<OpeningHtmlTag> openingHtmlTags) {
int insertionIndex = 0;
Iterator<OpeningHtmlTag> tagIterator = openingHtmlTags.iterator();
while (tagIterator.hasNext() && tagIterator.next().getStartOffset() <= newEntry.getStartOffset()) {
openingHtmlTags.add(insertionIndex, newEntry);
}
- private void insertAndPreserveOrder(int newOffset, List<Integer> orderedOffsets) {
+ private static void insertAndPreserveOrder(int newOffset, List<Integer> orderedOffsets) {
int insertionIndex = 0;
Iterator<Integer> entriesIterator = orderedOffsets.iterator();
while (entriesIterator.hasNext() && entriesIterator.next() <= newOffset) {
return to != null && to < currentLine;
}
- private char[] normalize(char currentChar) {
+ private static char[] normalize(char currentChar) {
char[] normalizedChars;
if (currentChar == HTML_OPENING) {
normalizedChars = ENCODED_HTML_OPENING.toCharArray();
return normalizedChars;
}
- private boolean shouldAppendCharToHtmlOutput(CharactersReader charsReader) {
+ private static boolean shouldAppendCharToHtmlOutput(CharactersReader charsReader) {
return charsReader.getCurrentValue() != CR_END_OF_LINE && charsReader.getCurrentValue() != LF_END_OF_LINE;
}
- private int getNumberOfTagsToClose(int currentIndex, DecorationDataHolder dataHolder) {
+ private static int getNumberOfTagsToClose(int currentIndex, DecorationDataHolder dataHolder) {
int numberOfTagsToClose = 0;
while (currentIndex == dataHolder.getCurrentClosingTagOffset()) {
return numberOfTagsToClose;
}
- private Collection<String> getTagsToOpen(int currentIndex, DecorationDataHolder dataHolder) {
+ private static Collection<String> getTagsToOpen(int currentIndex, DecorationDataHolder dataHolder) {
Collection<String> tagsToOpen = newArrayList();
while (dataHolder.getCurrentOpeningTagEntry() != null && currentIndex == dataHolder.getCurrentOpeningTagEntry().getStartOffset()) {
tagsToOpen.add(dataHolder.getCurrentOpeningTagEntry().getCssClass());
return tagsToOpen;
}
- private boolean shouldClosePendingTags(CharactersReader charactersReader) {
+ private static boolean shouldClosePendingTags(CharactersReader charactersReader) {
return charactersReader.getCurrentValue() == CR_END_OF_LINE
|| (charactersReader.getCurrentValue() == LF_END_OF_LINE && charactersReader.getPreviousValue() != CR_END_OF_LINE)
|| (charactersReader.getCurrentValue() == CharactersReader.END_OF_STREAM && charactersReader.getPreviousValue() != LF_END_OF_LINE);
}
- private boolean shouldReopenPendingTags(CharactersReader charactersReader) {
+ private static boolean shouldReopenPendingTags(CharactersReader charactersReader) {
return (charactersReader.getPreviousValue() == LF_END_OF_LINE && charactersReader.getCurrentValue() != LF_END_OF_LINE)
|| (charactersReader.getPreviousValue() == CR_END_OF_LINE && charactersReader.getCurrentValue() != CR_END_OF_LINE
&& charactersReader.getCurrentValue() != LF_END_OF_LINE);
}
- private boolean shouldStartNewLine(CharactersReader charactersReader) {
+ private static boolean shouldStartNewLine(CharactersReader charactersReader) {
return charactersReader.getPreviousValue() == LF_END_OF_LINE
|| (charactersReader.getPreviousValue() == CR_END_OF_LINE && charactersReader.getCurrentValue() != LF_END_OF_LINE);
}
- private void closeCompletedTags(CharactersReader charactersReader, int numberOfTagsToClose,
+ private static void closeCompletedTags(CharactersReader charactersReader, int numberOfTagsToClose,
StringBuilder decoratedText) {
for (int i = 0; i < numberOfTagsToClose; i++) {
injectClosingHtml(decoratedText);
}
}
- private void openNewTags(CharactersReader charactersReader, Collection<String> tagsToOpen,
+ private static void openNewTags(CharactersReader charactersReader, Collection<String> tagsToOpen,
StringBuilder decoratedText) {
for (String tagToOpen : tagsToOpen) {
injectOpeningHtmlForRule(tagToOpen, decoratedText);
}
}
- private void closeCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) {
+ private static void closeCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) {
for (int i = 0; i < charactersReader.getOpenTags().size(); i++) {
injectClosingHtml(decoratedText);
}
}
- private void reopenCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) {
+ private static void reopenCurrentSyntaxTags(CharactersReader charactersReader, StringBuilder decoratedText) {
for (String tags : charactersReader.getOpenTags()) {
injectOpeningHtmlForRule(tags, decoratedText);
}
}
- private void injectOpeningHtmlForRule(String textType, StringBuilder decoratedText) {
+ private static void injectOpeningHtmlForRule(String textType, StringBuilder decoratedText) {
decoratedText.append("<span class=\"").append(textType).append("\">");
}
- private void injectClosingHtml(StringBuilder decoratedText) {
+ private static void injectClosingHtml(StringBuilder decoratedText) {
decoratedText.append("</span>");
}
}
private WsActionTester ws = new WsActionTester(
new MeasureAction(
db.getDbClient(),
- new ProjectBadgesSupport(userSession, db.getDbClient(), new ComponentFinder(db.getDbClient(), null)),
+ new ProjectBadgesSupport(userSession, new ComponentFinder(db.getDbClient(), null)),
new SvgGenerator(mapSettings.asConfig())));
@Test
private WsActionTester ws = new WsActionTester(
new QualityGateAction(db.getDbClient(),
- new ProjectBadgesSupport(userSession, db.getDbClient(), new ComponentFinder(db.getDbClient(), null)),
+ new ProjectBadgesSupport(userSession, new ComponentFinder(db.getDbClient(), null)),
new SvgGenerator(mapSettings.asConfig())));
@Test
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.assertj.core.groups.Tuple;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.security.SecurityStandards;
import org.sonar.server.security.SecurityStandards.SQCategory;
import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Common;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anySet;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.db.component.ComponentTesting.newFileDto;
@RunWith(DataProviderRunner.class)
public class ShowActionTest {
private static final Random RANDOM = new Random();
- private static final String INTERPRETED = "interpreted";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private final DbClient dbClient = dbTester.getDbClient();
- private final MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
private final AvatarResolver avatarResolver = new AvatarResolverImpl();
private final HotspotWsResponseFormatter responseFormatter = new HotspotWsResponseFormatter();
private final IssueChangeWSSupport issueChangeSupport = Mockito.mock(IssueChangeWSSupport.class);
private final HotspotWsSupport hotspotWsSupport = new HotspotWsSupport(dbClient, userSessionRule, System2.INSTANCE);
private final UserResponseFormatter userFormatter = new UserResponseFormatter(new AvatarResolverImpl());
private final TextRangeResponseFormatter textRangeFormatter = new TextRangeResponseFormatter();
- private final ShowAction underTest = new ShowAction(dbClient, hotspotWsSupport, responseFormatter, textRangeFormatter, userFormatter, issueChangeSupport, macroInterpreter);
+ private final ShowAction underTest = new ShowAction(dbClient, hotspotWsSupport, responseFormatter, textRangeFormatter, userFormatter, issueChangeSupport);
private final WsActionTester actionTester = new WsActionTester(underTest);
- @Before
- public void before() {
- doReturn(INTERPRETED).when(macroInterpreter).interpret(anyString());
- }
-
@Test
public void ws_is_public() {
assertThat(actionTester.getDef().isInternal()).isFalse();
.executeProtobuf(Hotspots.ShowWsResponse.class);
assertThat(response.getRule().getRiskDescription()).isNullOrEmpty();
-
- verifyNoInteractions(macroInterpreter);
}
@Test
}
}
- private void stopQuietly() {
+ private static void stopQuietly() {
try {
PlatformImpl.getInstance().doStop();
} catch (Exception e) {
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 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.core.extension;
-
-public final class ExtensionProviderSupport {
- private ExtensionProviderSupport() {
- // prevents implementation
- }
-
- private static boolean isType(Object extension, Class extensionClass) {
- Class clazz = extension instanceof Class ? (Class) extension : extension.getClass();
- return extensionClass.isAssignableFrom(clazz);
- }
-}
*/
public class FieldDiffs implements Serializable {
private static final String CHAR_TO_ESCAPE = "|,{}=:";
-
- private String issueKey;
- private String userUuid;
- private Date creationDate;
public static final String ASSIGNEE = "assignee";
public static final String ENCODING_PREFIX = "{base64:";
public static final String ENCODING_SUFFIX = "}";
private final Map<String, Diff> diffs = new LinkedHashMap<>();
+ private String issueKey;
+ private String userUuid;
+ private Date creationDate;
+
public Map<String, Diff> diffs() {
if (diffs.containsKey(ASSIGNEE)) {
Map<String, Diff> result = new LinkedHashMap<>(diffs);
/**
* A plugin can export some resources to other plugins
*/
- private void exportResources(PluginClassLoaderDef def, ClassloaderBuilder builder, Collection<PluginClassLoaderDef> allPlugins) {
+ private static void exportResources(PluginClassLoaderDef def, ClassloaderBuilder builder, Collection<PluginClassLoaderDef> allPlugins) {
// export the resources to all other plugins
builder.setExportMask(def.getBasePluginKey(), def.getExportMask());
for (PluginClassLoaderDef other : allPlugins) {
/**
* Builds classloaders and verifies that all of them are correctly defined
*/
- private Map<PluginClassLoaderDef, ClassLoader> build(Collection<PluginClassLoaderDef> defs, ClassloaderBuilder builder) {
+ private static Map<PluginClassLoaderDef, ClassLoader> build(Collection<PluginClassLoaderDef> defs, ClassloaderBuilder builder) {
Map<PluginClassLoaderDef, ClassLoader> result = new HashMap<>();
Map<String, ClassLoader> classloadersByBasePluginKey = builder.build();
for (PluginClassLoaderDef def : defs) {
initUserAgent(userAgent, config);
}
- private void initProxy(AuthenticatorFacade system, Configuration config) {
+ private static void initProxy(AuthenticatorFacade system, Configuration config) {
// register credentials
Optional<String> login = config.get(HTTP_PROXY_USER);
if (login.isPresent()) {
* Set of {@link Block}s, which internally stored as a sorted list.
*/
final class BlocksGroup {
+ final List<Block> blocks;
/**
* Factory method.
- *
+ *
* @return new empty group
*/
public static BlocksGroup empty() {
return new BlocksGroup();
}
- protected final List<Block> blocks;
-
private BlocksGroup() {
this.blocks = new ArrayList<>();
}
* </p>
*/
public final class JavaTokenProducer {
-
- private JavaTokenProducer() {
- }
-
private static final String NORMALIZED_CHARACTER_LITERAL = "$CHARS";
private static final String NORMALIZED_NUMERIC_LITERAL = "$NUMBER";
private static final String FLOAT_SUFFIX = "[fFdD]";
private static final String INT_SUFFIX = "[lL]";
+ private JavaTokenProducer() {
+ }
+
public static TokenChunker build() {
return TokenChunker.builder()
// White Space
* For instance, 3 days and 4 hours will return 3.5 days (if hoursIndDay is 8).
*/
public double toWorkingDays() {
- return durationInMinutes / 60d / hoursInDay;
+ return durationInMinutes / 60D / hoursInDay;
}
/**
*/
package org.sonar.api.ce.posttask;
-import java.util.Date;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.ExtensionPoint;
@ServerSide
@ComputeEngineSide
@SonarLintSide
+@Deprecated
public class RulesDefinitionXmlLoader {
private static final String ELEMENT_RULES = "rules";
public interface ZipEntryFilter {
boolean accept(ZipEntry entry);
}
-
- private static class ZipEntryFilterDelegate implements Predicate<ZipEntry> {
- private final ZipEntryFilter delegate;
-
- private ZipEntryFilterDelegate(ZipEntryFilter delegate) {
- this.delegate = delegate;
- }
-
- @Override
- public boolean test(ZipEntry zipEntry) {
- return delegate.accept(zipEntry);
- }
- }
}
appendMeasure(inputFile, writer, new DefaultMeasure<Integer>().forMetric(TEST_FAILURES).withValue((int) failedTests));
}
- private void appendMeasure(InputFile inputFile, ScannerReportWriter writer, DefaultMeasure measure) {
+ private static void appendMeasure(InputFile inputFile, ScannerReportWriter writer, DefaultMeasure measure) {
writer.appendComponentMeasure(((DefaultInputComponent) inputFile).scannerId(), toReportMeasure(measure));
}
return ruleList;
}
- private String getUrl(String qualityProfileKey, int page, int pageSize) {
+ private static String getUrl(String qualityProfileKey, int page, int pageSize) {
StringBuilder builder = new StringBuilder(1024);
builder.append(RULES_SEARCH_URL);
builder.append("&qprofile=").append(ScannerUtils.encodeForUrl(qualityProfileKey));
void apply(Integer value, ScannerReport.LineCoverage.Builder builder);
}
- private void mergeLineCoverageValues(int lineCount, SortedMap<Integer, Integer> valueByLine, SortedMap<Integer, ScannerReport.LineCoverage.Builder> coveragePerLine,
+ private static void mergeLineCoverageValues(int lineCount, SortedMap<Integer, Integer> valueByLine, SortedMap<Integer, ScannerReport.LineCoverage.Builder> coveragePerLine,
LineCoverageOperation op) {
for (Map.Entry<Integer, Integer> lineMeasure : valueByLine.entrySet()) {
int lineIdx = lineMeasure.getKey();
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
+import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.scanner.sensor.ProjectSensor;
-import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.report.ReportPublisher;
@Phase(name = Phase.Name.POST)
continue;
}
if (!isCoverageAlreadyDefined(f)) {
- ((DefaultInputFile) f).getExecutableLines().ifPresent(execLines -> {
- storeZeroCoverageForEachExecutableLine(context, f, execLines);
- });
+ ((DefaultInputFile) f).getExecutableLines().ifPresent(execLines -> storeZeroCoverageForEachExecutableLine(context, f, execLines));
}
}
}
List<LoadedActiveRule> qp2Rules = ImmutableList.of(r2, r3);
List<LoadedActiveRule> qp3Rules = ImmutableList.of(r1, r3);
- when(loader.load(eq("qp1"))).thenReturn(qp1Rules);
- when(loader.load(eq("qp2"))).thenReturn(qp2Rules);
- when(loader.load(eq("qp3"))).thenReturn(qp3Rules);
+ when(loader.load("qp1")).thenReturn(qp1Rules);
+ when(loader.load("qp2")).thenReturn(qp2Rules);
+ when(loader.load("qp3")).thenReturn(qp3Rules);
QualityProfiles profiles = mockProfiles("qp1", "qp2", "qp3");
DefaultActiveRules activeRules = provider.provide(loader, profiles);
assertThat(activeRules.findAll()).extracting("ruleKey").containsOnly(
RuleKey.of("rule1", "rule1"), RuleKey.of("rule2", "rule2"), RuleKey.of("rule3", "rule3"));
- verify(loader).load(eq("qp1"));
- verify(loader).load(eq("qp2"));
- verify(loader).load(eq("qp3"));
+ verify(loader).load("qp1");
+ verify(loader).load("qp2");
+ verify(loader).load("qp3");
assertThat(activeRules.getDeprecatedRuleKeys(RuleKey.of("rule1", "rule1"))).containsOnly("rule1old:rule1old");
verifyNoMoreInteractions(loader);
r2.setParams(ImmutableMap.of("foo1", "bar1", "foo2", "bar2"));
List<LoadedActiveRule> qpRules = ImmutableList.of(r1, r2);
- when(loader.load(eq("qp"))).thenReturn(qpRules);
+ when(loader.load("qp")).thenReturn(qpRules);
QualityProfiles profiles = mockProfiles("qp");
ActiveRules activeRules = provider.provide(loader, profiles);
Tuple.tuple(RuleKey.of("rule1", "rule1"), ImmutableMap.of()),
Tuple.tuple(RuleKey.of("rule2", "rule2"), ImmutableMap.of("foo1", "bar1", "foo2", "bar2")));
- verify(loader).load(eq("qp"));
+ verify(loader).load("qp");
verifyNoMoreInteractions(loader);
}
return compare(expectedJson, actualJson);
}
- private Object parse(String s) {
+ private static Object parse(String s) {
try {
JSONParser parser = new JSONParser();
return parser.parse(s);
return compareBooleans((Boolean) expectedObject, (Boolean) actualObject);
}
- private boolean compareBooleans(Boolean expected, Boolean actual) {
+ private static boolean compareBooleans(Boolean expected, Boolean actual) {
return expected.equals(actual);
}
- private boolean compareNumbers(Number expected, Number actual) {
+ private static boolean compareNumbers(Number expected, Number actual) {
double d1 = expected.doubleValue();
double d2 = actual.doubleValue();
if (Double.compare(d1, d2) == 0) {
return details;
}
- private void print(String title, SortedMap<String, String> translations, StringBuilder to) {
+ private static void print(String title, SortedMap<String, String> translations, StringBuilder to) {
if (!translations.isEmpty()) {
to.append(title);
for (Map.Entry<String, String> entry : translations.entrySet()) {