Browse Source

Improve code quality

tags/9.2.0.49834
Duarte Meneses 2 years ago
parent
commit
9f7a5068bb
57 changed files with 208 additions and 180 deletions
  1. 2
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilder.java
  2. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationMeasures.java
  3. 3
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/FormulaExecutorComponentVisitor.java
  4. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageVariationFormula.java
  5. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycle.java
  6. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/MaintainabilityMeasuresVisitor.java
  7. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewMaintainabilityMeasuresVisitor.java
  8. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/CommentMeasuresStep.java
  9. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ComplexityMeasuresStep.java
  10. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/CoverageMeasuresStep.java
  11. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LanguageDistributionMeasuresStep.java
  12. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewCoverageMeasuresStep.java
  13. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java
  14. 2
    4
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/SizeMeasuresStep.java
  15. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/UnitTestMeasuresStep.java
  16. 3
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStep.java
  17. 23
    0
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/taskprocessor/package-info.java
  18. 23
    0
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/util/package-info.java
  19. 9
    7
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java
  20. 2
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java
  21. 14
    12
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MatchTest.java
  22. 3
    2
      server/sonar-db-core/src/main/java/org/sonar/db/DatabaseUtils.java
  23. 3
    3
      server/sonar-server-common/src/main/java/org/sonar/server/config/ConfigurationProvider.java
  24. 1
    1
      server/sonar-server-common/src/main/java/org/sonar/server/es/SearchIdResult.java
  25. 1
    1
      server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchFeatureRepertoire.java
  26. 2
    2
      server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionEvaluator.java
  27. 1
    2
      server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginJarLoader.java
  28. 1
    1
      server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQuery.java
  29. 1
    1
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/badge/ws/SvgFormatter.java
  30. 1
    2
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentDtoToWsComponent.java
  31. 1
    2
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java
  32. 1
    2
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AuthorsAction.java
  33. 4
    3
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureMatrix.java
  34. 2
    2
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java
  35. 1
    1
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/EventValidator.java
  36. 4
    4
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java
  37. 5
    6
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/TagsWsSupport.java
  38. 5
    8
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateConditionsUpdater.java
  39. 2
    5
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java
  40. 2
    3
      server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java
  41. 3
    3
      server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java
  42. 2
    3
      server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/ServletRequest.java
  43. 1
    2
      server/sonar-webserver/src/main/java/org/sonar/server/platform/web/SecurityServletFilter.java
  44. 7
    7
      sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionsInstaller.java
  45. 14
    14
      sonar-duplications/src/main/java/org/sonar/duplications/block/Block.java
  46. 1
    2
      sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java
  47. 5
    6
      sonar-duplications/src/main/java/org/sonar/duplications/detector/original/BlocksGroup.java
  48. 6
    15
      sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/TextSet.java
  49. 5
    2
      sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/MultivalueProperty.java
  50. 2
    0
      sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/server/RulesDefinitionContext.java
  51. 3
    3
      sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/AlwaysIncreasingSystem2.java
  52. 2
    2
      sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java
  53. 1
    1
      sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Checks.java
  54. 11
    15
      sonar-plugin-api/src/main/java/org/sonar/api/rules/AnnotationRuleParser.java
  55. 1
    2
      sonar-plugin-api/src/main/java/org/sonar/api/utils/text/CsvWriter.java
  56. 6
    6
      sonar-plugin-api/src/test/java/org/sonar/api/rules/RulePriorityTest.java
  57. 2
    2
      sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/CharsetValidation.java

+ 2
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilder.java View File

@@ -26,6 +26,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
@@ -72,7 +73,7 @@ public class ComponentTreeBuilder {
public ComponentTreeBuilder(
ComponentKeyGenerator keyGenerator,
ComponentKeyGenerator publicKeyGenerator,
Function<String, String> uuidSupplier,
UnaryOperator<String> uuidSupplier,
Function<Integer, ScannerReport.Component> scannerComponentSupplier,
Project project,
Branch branch,

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationMeasures.java View File

@@ -47,7 +47,7 @@ import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;

public class DuplicationMeasures {
protected final List<Formula> formulas;
protected final List<Formula<?>> formulas;
protected final TreeRootHolder treeRootHolder;
protected final MetricRepository metricRepository;
protected final MeasureRepository measureRepository;

+ 3
- 3
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/FormulaExecutorComponentVisitor.java View File

@@ -59,9 +59,9 @@ public class FormulaExecutorComponentVisitor extends PathAwareVisitorAdapter<For

private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final List<Formula> formulas;
private final List<Formula<?>> formulas;

private FormulaExecutorComponentVisitor(Builder builder, Iterable<Formula> formulas) {
private FormulaExecutorComponentVisitor(Builder builder, Iterable<Formula<?>> formulas) {
super(CrawlerDepthLimit.LEAVES, ComponentVisitor.Order.POST_ORDER, COUNTERS_FACTORY);
this.measureRepository = builder.measureRepository;
this.metricRepository = builder.metricRepository;
@@ -85,7 +85,7 @@ public class FormulaExecutorComponentVisitor extends PathAwareVisitorAdapter<For
return new Builder(metricRepository, measureRepository);
}

public FormulaExecutorComponentVisitor buildFor(Iterable<Formula> formulas) {
public FormulaExecutorComponentVisitor buildFor(Iterable<Formula<?>> formulas) {
return new FormulaExecutorComponentVisitor(this, formulas);
}
}

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageVariationFormula.java View File

@@ -37,7 +37,7 @@ public abstract class CoverageVariationFormula<T extends ElementsAndCoveredEleme
@Override
public Optional<Measure> createMeasure(T counter, CreateMeasureContext context) {
LongValue elements = counter.elements;
if (elements.isSet() && elements.getValue() > 0d) {
if (elements.isSet() && elements.getValue() > 0D) {
LongValue coveredElements = counter.coveredElements;
double variation = calculateCoverage(coveredElements.getValue(), elements.getValue());
return Optional.of(newMeasureBuilder().setVariation(variation).createNoValue());

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

@@ -80,14 +80,14 @@ public class IssueLifecycle {
setStatus(issue, rule);
}

private void setType(DefaultIssue issue, Rule rule) {
private static void setType(DefaultIssue issue, Rule rule) {
if (issue.isFromExternalRuleEngine()) {
return;
}
issue.setType(requireNonNull(rule.getType(), "No rule type"));
}

private void setStatus(DefaultIssue issue, Rule rule) {
private static void setStatus(DefaultIssue issue, Rule rule) {
if (rule.getType() == RuleType.SECURITY_HOTSPOT || issue.type() == RuleType.SECURITY_HOTSPOT) {
issue.setStatus(Issue.STATUS_TO_REVIEW);
} else {

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

@@ -112,9 +112,9 @@ public class MaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<Main
Optional<Measure> measure = measureRepository.getRawMeasure(component, maintainabilityRemediationEffortMetric);
double maintainabilityRemediationEffort = measure.isPresent() ? measure.get().getLongValue() : 0L;
if (Double.doubleToRawLongBits(developmentCost.devCosts) != 0L) {
return maintainabilityRemediationEffort / (double) developmentCost.devCosts;
return maintainabilityRemediationEffort / developmentCost.devCosts;
}
return 0d;
return 0D;
}

private void addDevelopmentCostMeasure(Component component, Counter developmentCost) {

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewMaintainabilityMeasuresVisitor.java View File

@@ -125,7 +125,7 @@ public class NewMaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<N
return newDebt.getValue() / (double) developmentCost;
}
}
return 0d;
return 0D;
}

private static long getLongValue(Optional<Measure> measure) {

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

@@ -52,7 +52,7 @@ public class CommentMeasuresStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final List<Formula> formulas;
private final List<Formula<?>> formulas;

public CommentMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;

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

@@ -48,7 +48,7 @@ import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumF
* Computes complexity measures on files and then aggregates them on higher components.
*/
public class ComplexityMeasuresStep implements ComputationStep {
private static final List<Formula> FORMULAS = List.of(
private static final List<Formula<?>> FORMULAS = List.of(
createIntSumFormula(COMPLEXITY_KEY),
createIntSumFormula(COMPLEXITY_IN_CLASSES_KEY),
createIntSumFormula(COMPLEXITY_IN_FUNCTIONS_KEY),

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

@@ -55,7 +55,7 @@ import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumF
* Computes coverage measures on files and then aggregates them on higher components.
*/
public class CoverageMeasuresStep implements ComputationStep {
private static final List<Formula> COVERAGE_FORMULAS = List.of(
private static final List<Formula<?>> COVERAGE_FORMULAS = List.of(
createIntSumFormula(LINES_TO_COVER_KEY),
createIntSumFormula(UNCOVERED_LINES_KEY),
createIntSumFormula(CONDITIONS_TO_COVER_KEY),

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

@@ -52,7 +52,7 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilde
public class LanguageDistributionMeasuresStep implements ComputationStep {
private static final String UNKNOWN_LANGUAGE_KEY = "<null>";

private static final List<Formula> FORMULAS = List.of(new LanguageDistributionFormula());
private static final List<Formula<?>> FORMULAS = List.of(new LanguageDistributionFormula());

private static final String[] LANGUAGE_DISTRIBUTION_FORMULA_METRICS = new String[] {NCLOC_LANGUAGE_DISTRIBUTION_KEY};


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

@@ -59,7 +59,7 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilde
* Computes measures related to the New Coverage. These measures do not have values, only variations.
*/
public class NewCoverageMeasuresStep implements ComputationStep {
private static final List<Formula> FORMULAS = List.of(
private static final List<Formula<?>> FORMULAS = List.of(
// UT coverage
new NewCoverageFormula(),
new NewBranchCoverageFormula(),

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

@@ -106,7 +106,7 @@ public class NewSizeMeasuresStep implements ComputationStep {
return;
}
Optional<Set<Integer>> changedLines = newLinesRepository.getNewLines(leaf);
if (!changedLines.isPresent()) {
if (changedLines.isEmpty()) {
return;
}


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

@@ -19,8 +19,6 @@
*/
package org.sonar.ce.task.projectanalysis.step;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
@@ -53,13 +51,13 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilde
*/
public class SizeMeasuresStep implements ComputationStep {
private static final CounterStackElementFactory COUNTER_STACK_ELEMENT_FACTORY = new CounterStackElementFactory();
private static final List<Formula> AGGREGATED_SIZE_MEASURE_FORMULAS = Collections.unmodifiableList(Arrays.asList(
private static final List<Formula<?>> AGGREGATED_SIZE_MEASURE_FORMULAS = List.of(
createIntSumFormula(GENERATED_LINES_KEY),
createIntSumFormula(NCLOC_KEY),
createIntSumFormula(GENERATED_NCLOC_KEY),
createIntSumFormula(FUNCTIONS_KEY),
createIntSumFormula(STATEMENTS_KEY),
createIntSumFormula(CLASSES_KEY)));
createIntSumFormula(CLASSES_KEY));

private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;

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

@@ -49,7 +49,7 @@ import static org.sonar.api.measures.CoreMetrics.TEST_SUCCESS_DENSITY_KEY;
public class UnitTestMeasuresStep implements ComputationStep {
private static final String[] METRICS = new String[] {TESTS_KEY, TEST_ERRORS_KEY, TEST_FAILURES_KEY, SKIPPED_TESTS_KEY, TEST_SUCCESS_DENSITY_KEY, TEST_EXECUTION_TIME_KEY};

private static final List<Formula> FORMULAS = List.of(new UnitTestsFormula());
private static final List<Formula<?>> FORMULAS = List.of(new UnitTestsFormula());

private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;

+ 3
- 2
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStep.java View File

@@ -32,6 +32,7 @@ import org.sonar.ce.task.projectexport.component.ComponentRepository;
import org.sonar.ce.task.projectexport.rule.Rule;
import org.sonar.ce.task.projectexport.rule.RuleRepository;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.DumpElement.IssueDumpElement;
import org.sonar.ce.task.projectexport.steps.DumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.projectexport.steps.StreamWriter;
@@ -134,8 +135,8 @@ public class ExportIssuesStep implements ComputationStep {
.setResolution(emptyIfNull(rs, 11))
.setSeverity(emptyIfNull(rs, 12))
.setManualSeverity(rs.getBoolean(13))
.setGap(defaultIfNull(rs, 14, DumpElement.ISSUES.NO_GAP))
.setEffort(defaultIfNull(rs, 15, DumpElement.ISSUES.NO_EFFORT))
.setGap(defaultIfNull(rs, 14, IssueDumpElement.NO_GAP))
.setEffort(defaultIfNull(rs, 15, IssueDumpElement.NO_EFFORT))
.setAssignee(emptyIfNull(rs, 16))
.setAuthor(emptyIfNull(rs, 17))
.setTags(emptyIfNull(rs, 18))

+ 23
- 0
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/taskprocessor/package-info.java View File

@@ -0,0 +1,23 @@
/*
* 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.projectexport.taskprocessor;

import javax.annotation.ParametersAreNonnullByDefault;

+ 23
- 0
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/util/package-info.java View File

@@ -0,0 +1,23 @@
/*
* 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.util;

import javax.annotation.ParametersAreNonnullByDefault;

+ 9
- 7
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java View File

@@ -153,13 +153,15 @@ public class MeasureComputerDefinitionImplTest {
.setOutputMetrics("debt")
.build();

assertThat(computer).isEqualTo(computer);
assertThat(computer).isEqualTo(sameComputer);
assertThat(computer).isNotEqualTo(anotherComputer);
assertThat(computer).isNotEqualTo(null);
assertThat(computer).isEqualTo(computer)
.isEqualTo(sameComputer)
.isNotEqualTo(anotherComputer)
.isNotEqualTo(null);

assertThat(computer)
.hasSameHashCodeAs(computer)
.hasSameHashCodeAs(sameComputer);

assertThat(computer.hashCode()).isEqualTo(computer.hashCode());
assertThat(computer.hashCode()).isEqualTo(sameComputer.hashCode());
assertThat(computer.hashCode()).isNotEqualTo(anotherComputer.hashCode());
}

@@ -169,7 +171,7 @@ public class MeasureComputerDefinitionImplTest {
.setInputMetrics("ncloc", "comment")
.setOutputMetrics("comment_density_1", "comment_density_2")
.build().toString())
.isEqualTo("MeasureComputerDefinitionImpl{inputMetricKeys=[ncloc, comment], outputMetrics=[comment_density_1, comment_density_2]}");
.isEqualTo("MeasureComputerDefinitionImpl{inputMetricKeys=[ncloc, comment], outputMetrics=[comment_density_1, comment_density_2]}");
}

}

+ 2
- 1
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java View File

@@ -28,6 +28,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -56,7 +57,7 @@ public class ComponentTreeBuilderTest {
+ ComponentKeys.createEffectiveKey(projectKey, path);
private static final ComponentKeyGenerator PUBLIC_KEY_GENERATOR = (projectKey, path) -> "public_"
+ ComponentKeys.createEffectiveKey(projectKey, path);
private static final Function<String, String> UUID_SUPPLIER = (componentKey) -> componentKey + "_uuid";
private static final UnaryOperator<String> UUID_SUPPLIER = (componentKey) -> componentKey + "_uuid";
private static final EnumSet<ScannerReport.Component.ComponentType> REPORT_TYPES = EnumSet.of(PROJECT, FILE);
private static final String NO_SCM_BASE_PATH = "";
// both no project as "" or null should be supported

+ 14
- 12
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MatchTest.java View File

@@ -52,23 +52,25 @@ public class MatchTest {

@Test
public void equals_is_based_on_both_properties() {
assertThat(underTest).isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY));
assertThat(underTest).isNotEqualTo(new Match("other key", SOME_REPORT_KEY));
assertThat(underTest).isNotEqualTo(new Match(SOME_KEY, "other report key"));
assertThat(underTest).isNotEqualTo(new Match(null, SOME_REPORT_KEY));
assertThat(underTest).isNotEqualTo(new Match(SOME_KEY, null));
assertThat(underTest).isNotEqualTo(new Match(null, null));
assertThat(underTest)
.isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY))
.isNotEqualTo(new Match("other key", SOME_REPORT_KEY))
.isNotEqualTo(new Match(SOME_KEY, "other report key"))
.isNotEqualTo(new Match(null, SOME_REPORT_KEY))
.isNotEqualTo(new Match(SOME_KEY, null))
.isNotEqualTo(new Match(null, null));
}

@Test
public void hashcode_is_base_on_both_properties() {
int hashCode = underTest.hashCode();
assertThat(hashCode).isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY).hashCode());
assertThat(hashCode).isNotEqualTo(new Match("other key", SOME_REPORT_KEY).hashCode());
assertThat(hashCode).isNotEqualTo(new Match(SOME_KEY, "other report key").hashCode());
assertThat(hashCode).isNotEqualTo(new Match(null, SOME_REPORT_KEY).hashCode());
assertThat(hashCode).isNotEqualTo(new Match(SOME_KEY, null).hashCode());
assertThat(hashCode).isNotEqualTo(new Match(null, null).hashCode());
assertThat(hashCode)
.isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY).hashCode())
.isNotEqualTo(new Match("other key", SOME_REPORT_KEY).hashCode())
.isNotEqualTo(new Match(SOME_KEY, "other report key").hashCode())
.isNotEqualTo(new Match(null, SOME_REPORT_KEY).hashCode())
.isNotEqualTo(new Match(SOME_KEY, null).hashCode())
.isNotEqualTo(new Match(null, null).hashCode());
}

@Test

+ 3
- 2
server/sonar-db-core/src/main/java/org/sonar/db/DatabaseUtils.java View File

@@ -43,6 +43,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
@@ -440,10 +441,10 @@ public class DatabaseUtils {
/**
* This method can be used as a method reference, for not to have to handle the checked exception {@link SQLException}
*/
public static Consumer<String> setStrings(PreparedStatement stmt, Supplier<Integer> index) {
public static Consumer<String> setStrings(PreparedStatement stmt, IntSupplier index) {
return value -> {
try {
stmt.setString(index.get(), value);
stmt.setString(index.getAsInt(), value);
} catch (SQLException e) {
Throwables.propagate(e);
}

+ 3
- 3
server/sonar-server-common/src/main/java/org/sonar/server/config/ConfigurationProvider.java View File

@@ -20,14 +20,14 @@
package org.sonar.server.config;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import org.apache.commons.lang.ArrayUtils;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.internal.Settings;

import static java.util.function.Function.identity;
import static java.util.function.UnaryOperator.identity;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;

public class ConfigurationProvider extends ProviderAdapter {
@@ -42,7 +42,7 @@ public class ConfigurationProvider extends ProviderAdapter {
}

private static class ServerConfigurationAdapter implements Configuration {
private static final Function<String, String> REPLACE_ENCODED_COMMAS = value -> value.replace("%2C", ",");
private static final UnaryOperator<String> REPLACE_ENCODED_COMMAS = value -> value.replace("%2C", ",");

private final Settings settings;


+ 1
- 1
server/sonar-server-common/src/main/java/org/sonar/server/es/SearchIdResult.java View File

@@ -19,10 +19,10 @@
*/
package org.sonar.server.es;

import com.google.common.base.Function;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

+ 1
- 1
server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchFeatureRepertoire.java View File

@@ -60,7 +60,7 @@ public enum ComponentTextSearchFeatureRepertoire implements ComponentTextSearchF
return Stream.empty();
}
BoolQueryBuilder queryBuilder = prefixAndPartialQuery(tokens, query.getFieldName(), SEARCH_PREFIX_ANALYZER)
.boost(3f);
.boost(3F);
return Stream.of(queryBuilder);
}
},

+ 2
- 2
server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/ConditionEvaluator.java View File

@@ -49,12 +49,12 @@ class ConditionEvaluator {
*/
static EvaluatedCondition evaluate(Condition condition, QualityGateEvaluator.Measures measures) {
Optional<QualityGateEvaluator.Measure> measure = measures.get(condition.getMetricKey());
if (!measure.isPresent()) {
if (measure.isEmpty()) {
return new EvaluatedCondition(condition, EvaluationStatus.OK, null);
}

Optional<Comparable> value = getMeasureValue(condition, measure.get());
if (!value.isPresent()) {
if (value.isEmpty()) {
return new EvaluatedCondition(condition, EvaluationStatus.OK, null);
}


+ 1
- 2
server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginJarLoader.java View File

@@ -21,7 +21,6 @@ package org.sonar.server.plugins;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@@ -55,7 +54,7 @@ public class PluginJarLoader {
private static final Logger LOG = Loggers.get(PluginJarLoader.class);

// List of plugins that are silently removed if installed
private static final Set<String> DEFAULT_BLACKLISTED_PLUGINS = ImmutableSet.of("scmactivity", "issuesreport", "genericcoverage");
private static final Set<String> DEFAULT_BLACKLISTED_PLUGINS = Set.of("scmactivity", "issuesreport", "genericcoverage");
// List of plugins that should prevent the server to finish its startup
private static final Set<String> FORBIDDEN_INCOMPATIBLE_PLUGINS = Set.of(
"sqale", "report", "views", "authgithub", "authgitlab", "authbitbucket", "authsaml", "ldap", "scmgit", "scmsvn");

+ 1
- 1
server/sonar-webserver-es/src/main/java/org/sonar/server/issue/index/IssueQuery.java View File

@@ -59,7 +59,7 @@ public class IssueQuery {
*/
public static final String SORT_HOTSPOTS = "HOTSPOTS";

public static final Set<String> SORTS = ImmutableSet.of(SORT_BY_CREATION_DATE, SORT_BY_UPDATE_DATE, SORT_BY_CLOSE_DATE, SORT_BY_ASSIGNEE, SORT_BY_SEVERITY,
public static final Set<String> SORTS = Set.of(SORT_BY_CREATION_DATE, SORT_BY_UPDATE_DATE, SORT_BY_CLOSE_DATE, SORT_BY_ASSIGNEE, SORT_BY_SEVERITY,
SORT_BY_STATUS, SORT_BY_FILE_LINE, SORT_HOTSPOTS);

private final Collection<String> issueKeys;

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

@@ -52,7 +52,7 @@ class SvgFormatter {
NumberFormat numericFormatter = DecimalFormat.getInstance(Locale.ENGLISH);
numericFormatter.setMaximumFractionDigits(1);
int power = (int) StrictMath.log10(value);
double valueToFormat = value / (Math.pow(10, Math.floorDiv(power, 3) * 3d));
double valueToFormat = value / (Math.pow(10, Math.floorDiv(power, 3) * 3D));
String formattedNumber = numericFormatter.format(valueToFormat);
formattedNumber = formattedNumber + NUMERIC_SUFFIX_LIST.charAt(power / 3);
return formattedNumber.length() > 4 ? trim(formattedNumber.replaceAll(NUMERIC_REGEXP, "")) : trim(formattedNumber);

+ 1
- 2
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentDtoToWsComponent.java View File

@@ -19,7 +19,6 @@
*/
package org.sonar.server.component.ws;

import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Set;
import javax.annotation.Nullable;
@@ -39,7 +38,7 @@ class ComponentDtoToWsComponent {
/**
* The concept of "visibility" will only be configured for these qualifiers.
*/
private static final Set<String> QUALIFIERS_WITH_VISIBILITY = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP);
private static final Set<String> QUALIFIERS_WITH_VISIBILITY = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP);

private ComponentDtoToWsComponent() {
// prevent instantiation

+ 1
- 2
server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java View File

@@ -93,6 +93,7 @@ public class TreeAction implements ComponentsWsAction {
private static final String PATH_SORT = "path";
private static final String QUALIFIER_SORT = "qualifier";
private static final Set<String> SORTS = ImmutableSortedSet.of(NAME_SORT, PATH_SORT, QUALIFIER_SORT);
private static final Set<String> PROJECT_OR_APP_QUALIFIERS = ImmutableSortedSet.of(Qualifiers.PROJECT, Qualifiers.APP);

private final DbClient dbClient;
private final ComponentFinder componentFinder;
@@ -100,8 +101,6 @@ public class TreeAction implements ComponentsWsAction {
private final UserSession userSession;
private final I18n i18n;

private static final Set<String> PROJECT_OR_APP_QUALIFIERS = ImmutableSortedSet.of(Qualifiers.PROJECT, Qualifiers.APP);

public TreeAction(DbClient dbClient, ComponentFinder componentFinder, ResourceTypes resourceTypes, UserSession userSession, I18n i18n) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;

+ 1
- 2
server/sonar-webserver-webapi/src/main/java/org/sonar/server/issue/ws/AuthorsAction.java View File

@@ -63,8 +63,7 @@ public class AuthorsAction implements IssuesWsAction {
private final ComponentFinder componentFinder;

public AuthorsAction(UserSession userSession, DbClient dbClient, IssueIndex issueIndex,
IssueIndexSyncProgressChecker issueIndexSyncProgressChecker,
ComponentFinder componentFinder) {
IssueIndexSyncProgressChecker issueIndexSyncProgressChecker, ComponentFinder componentFinder) {
this.userSession = userSession;
this.dbClient = dbClient;
this.issueIndex = issueIndex;

+ 4
- 3
server/sonar-webserver-webapi/src/main/java/org/sonar/server/measure/live/MeasureMatrix.java View File

@@ -31,6 +31,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.sonar.db.component.ComponentDto;
@@ -152,7 +153,7 @@ class MeasureMatrix {
.map(MeasureCell::getMeasure);
}

private void changeCell(ComponentDto component, String metricKey, Function<LiveMeasureDto, Boolean> changer) {
private void changeCell(ComponentDto component, String metricKey, Predicate<LiveMeasureDto> changer) {
MeasureCell cell = table.get(component.uuid(), metricKey);
if (cell == null) {
LiveMeasureDto measure = new LiveMeasureDto()
@@ -161,8 +162,8 @@ class MeasureMatrix {
.setMetricUuid(metricsByKeys.get(metricKey).getUuid());
cell = new MeasureCell(measure, true);
table.put(component.uuid(), metricKey, cell);
changer.apply(cell.getMeasure());
} else if (changer.apply(cell.getMeasure())) {
changer.test(cell.getMeasure());
} else if (changer.test(cell.getMeasure())) {
cell.setChanged(true);
}
}

+ 2
- 2
server/sonar-webserver-webapi/src/main/java/org/sonar/server/permission/DefaultTemplatesResolverImpl.java View File

@@ -58,14 +58,14 @@ public class DefaultTemplatesResolverImpl implements DefaultTemplatesResolver {
return resourceTypes.getRoots()
.stream()
.map(ResourceType::getQualifier)
.anyMatch(qualifier -> Qualifiers.VIEW.equals(qualifier));
.anyMatch(Qualifiers.VIEW::equals);
}

private static boolean isApplicationEnabled(ResourceTypes resourceTypes) {
return resourceTypes.getRoots()
.stream()
.map(ResourceType::getQualifier)
.anyMatch(qualifier -> Qualifiers.APP.equals(qualifier));
.anyMatch(Qualifiers.APP::equals);
}

}

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

@@ -33,7 +33,7 @@ import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;

class EventValidator {
private static final Set<String> AUTHORIZED_CATEGORIES = ImmutableSet.of(VERSION.name(), OTHER.name());
private static final Set<String> AUTHORIZED_CATEGORIES = Set.of(VERSION.name(), OTHER.name());
private static final String AUTHORIZED_CATEGORIES_INLINED = Joiner.on(", ").join(AUTHORIZED_CATEGORIES);

private EventValidator() {

+ 4
- 4
server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/CreateAction.java View File

@@ -44,15 +44,15 @@ import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;

public class CreateAction implements ProjectLinksWsAction {
private static final int LINK_NAME_MAX_LENGTH = 128;
private static final int LINK_URL_MAX_LENGTH = 2048;
private static final int LINK_TYPE_MAX_LENGTH = 20;

private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final UuidFactory uuidFactory;

private static final int LINK_NAME_MAX_LENGTH = 128;
private static final int LINK_URL_MAX_LENGTH = 2048;
private static final int LINK_TYPE_MAX_LENGTH = 20;

public CreateAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.userSession = userSession;

+ 5
- 6
server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/TagsWsSupport.java View File

@@ -38,6 +38,11 @@ import static org.sonar.server.es.ProjectIndexer.Cause.PROJECT_TAGS_UPDATE;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;

public class TagsWsSupport {
/**
* The characters allowed in project tags are lower-case
* letters, digits, plus (+), sharp (#), dash (-) and dot (.)
*/
private static final Pattern VALID_TAG_REGEXP = Pattern.compile("[a-z0-9+#\\-.]+$");

private final DbClient dbClient;
private final ComponentFinder componentFinder;
@@ -45,12 +50,6 @@ public class TagsWsSupport {
private final ProjectIndexers projectIndexers;
private final System2 system2;

/**
* The characters allowed in project tags are lower-case
* letters, digits, plus (+), sharp (#), dash (-) and dot (.)
*/
private static final Pattern VALID_TAG_REGEXP = Pattern.compile("[a-z0-9+#\\-.]+$");

public TagsWsSupport(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, ProjectIndexers projectIndexers, System2 system2) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;

+ 5
- 8
server/sonar-webserver-webapi/src/main/java/org/sonar/server/qualitygate/QualityGateConditionsUpdater.java View File

@@ -19,8 +19,6 @@
*/
package org.sonar.server.qualitygate;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
@@ -61,13 +59,12 @@ import static org.sonar.server.qualitygate.Condition.Operator.LESS_THAN;
import static org.sonar.server.qualitygate.ValidRatingMetrics.isCoreRatingMetric;

public class QualityGateConditionsUpdater {
public static final Set<String> INVALID_METRIC_KEYS = ImmutableSet.of(ALERT_STATUS_KEY, SECURITY_HOTSPOTS_KEY, NEW_SECURITY_HOTSPOTS_KEY);
public static final Set<String> INVALID_METRIC_KEYS = Set.of(ALERT_STATUS_KEY, SECURITY_HOTSPOTS_KEY, NEW_SECURITY_HOTSPOTS_KEY);

private static final Map<Integer, ImmutableSet<Condition.Operator>> VALID_OPERATORS_BY_DIRECTION = ImmutableMap.<Integer, ImmutableSet<Condition.Operator>>builder()
.put(DIRECTION_NONE, ImmutableSet.of(GREATER_THAN, LESS_THAN))
.put(DIRECTION_BETTER, ImmutableSet.of(LESS_THAN))
.put(DIRECTION_WORST, ImmutableSet.of(GREATER_THAN))
.build();
private static final Map<Integer, Set<Condition.Operator>> VALID_OPERATORS_BY_DIRECTION = Map.of(
DIRECTION_NONE, Set.of(GREATER_THAN, LESS_THAN),
DIRECTION_BETTER, Set.of(LESS_THAN),
DIRECTION_WORST, Set.of(GREATER_THAN));

private static final EnumSet<ValueType> VALID_METRIC_TYPES = EnumSet.of(
ValueType.INT,

+ 2
- 5
server/sonar-webserver-webapi/src/main/java/org/sonar/server/setting/ws/SettingValidations.java View File

@@ -19,10 +19,8 @@
*/
package org.sonar.server.setting.ws;

import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.JsonElement;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
@@ -34,7 +32,6 @@ import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
@@ -64,6 +61,8 @@ public class SettingValidations {
"sonar.security.config.pythonsecurity",
"sonar.security.config.roslyn.sonaranalyzer.security.cs"
);
private static final Set<String> SUPPORTED_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP, Qualifiers.MODULE, Qualifiers.SUBVIEW);

private final PropertyDefinitions definitions;
private final DbClient dbClient;
private final I18n i18n;
@@ -82,8 +81,6 @@ public class SettingValidations {
};
}

private static final Set<String> SUPPORTED_QUALIFIERS = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP, Qualifiers.MODULE, Qualifiers.SUBVIEW);

public Consumer<SettingData> qualifier() {
return data -> {
String qualifier = data.component == null ? "" : data.component.qualifier();

+ 2
- 3
server/sonar-webserver-webapi/src/main/java/org/sonar/server/ui/ws/ComponentAction.java View File

@@ -19,7 +19,6 @@
*/
package org.sonar.server.ui.ws;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.List;
@@ -78,7 +77,7 @@ import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001;

public class ComponentAction implements NavigationWsAction {

private static final Set<String> MODULE_OR_DIR_QUALIFIERS = ImmutableSet.of(Qualifiers.MODULE, Qualifiers.DIRECTORY);
private static final Set<String> MODULE_OR_DIR_QUALIFIERS = Set.of(Qualifiers.MODULE, Qualifiers.DIRECTORY);
static final String PARAM_COMPONENT = "component";
private static final String PARAM_BRANCH = "branch";
private static final String PARAM_PULL_REQUEST = "pullRequest";
@@ -90,7 +89,7 @@ public class ComponentAction implements NavigationWsAction {
/**
* The concept of "visibility" will only be configured for these qualifiers.
*/
private static final Set<String> QUALIFIERS_WITH_VISIBILITY = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP);
private static final Set<String> QUALIFIERS_WITH_VISIBILITY = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP);

private final DbClient dbClient;
private final PageRepository pageRepository;

+ 3
- 3
server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java View File

@@ -61,9 +61,9 @@ public class UpdateEventActionTest {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);

private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private WsActionTester ws = new WsActionTester(new UpdateEventAction(dbClient, userSession));
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final WsActionTester ws = new WsActionTester(new UpdateEventAction(dbClient, userSession));

@Test
public void json_example() {

+ 2
- 3
server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/ServletRequest.java View File

@@ -43,14 +43,13 @@ import static org.apache.commons.lang.StringUtils.substringAfterLast;
import static org.apache.tomcat.util.http.fileupload.FileUploadBase.MULTIPART;

public class ServletRequest extends ValidatingRequest {

private final HttpServletRequest source;

static final Map<String, String> SUPPORTED_MEDIA_TYPES_BY_URL_SUFFIX = ImmutableMap.of(
"json", MediaTypes.JSON,
"protobuf", MediaTypes.PROTOBUF,
"text", MediaTypes.TXT);

private final HttpServletRequest source;

public ServletRequest(HttpServletRequest source) {
this.source = source;
}

+ 1
- 2
server/sonar-webserver/src/main/java/org/sonar/server/platform/web/SecurityServletFilter.java View File

@@ -19,7 +19,6 @@
*/
package org.sonar.server.platform.web;

import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Set;
import javax.servlet.Filter;
@@ -36,7 +35,7 @@ import javax.servlet.http.HttpServletResponse;
*/
public class SecurityServletFilter implements Filter {

private static final Set<String> ALLOWED_HTTP_METHODS = ImmutableSet.of("DELETE", "GET", "HEAD", "POST", "PUT");
private static final Set<String> ALLOWED_HTTP_METHODS = Set.of("DELETE", "GET", "HEAD", "POST", "PUT");

@Override
public void init(FilterConfig filterConfig) {

+ 7
- 7
sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionsInstaller.java View File

@@ -41,6 +41,13 @@ public abstract class CoreExtensionsInstaller {
private final CoreExtensionRepository coreExtensionRepository;
private final Class<? extends Annotation> supportedAnnotationType;

protected CoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository,
Class<? extends Annotation> supportedAnnotationType) {
this.sonarRuntime = sonarRuntime;
this.coreExtensionRepository = coreExtensionRepository;
this.supportedAnnotationType = supportedAnnotationType;
}

public static Predicate<Object> noExtensionFilter() {
return t -> true;
}
@@ -49,13 +56,6 @@ public abstract class CoreExtensionsInstaller {
return t -> true;
}

protected CoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository,
Class<? extends Annotation> supportedAnnotationType) {
this.sonarRuntime = sonarRuntime;
this.coreExtensionRepository = coreExtensionRepository;
this.supportedAnnotationType = supportedAnnotationType;
}

/**
* @param container the container into which extensions will be installed
* @param extensionFilter filters extensions added to {@link CoreExtension.Context}. When it returns false, the

+ 14
- 14
sonar-duplications/src/main/java/org/sonar/duplications/block/Block.java View File

@@ -32,14 +32,26 @@ public final class Block {
private final int startLine;
private final int endLine;

private int startUnit;
private int endUnit;
private final int startUnit;
private final int endUnit;

/**
* Cache for hash code.
*/
private int hash;

private Block(Builder builder) {
this.resourceId = builder.resourceId;
this.blockHash = builder.blockHash;
this.indexInFile = builder.indexInFile;

this.startLine = builder.startLine;
this.endLine = builder.endLine;

this.startUnit = builder.startUnit;
this.endUnit = builder.endUnit;
}

/**
* @since 2.14
*/
@@ -97,18 +109,6 @@ public final class Block {
}
}

private Block(Builder builder) {
this.resourceId = builder.resourceId;
this.blockHash = builder.blockHash;
this.indexInFile = builder.indexInFile;

this.startLine = builder.startLine;
this.endLine = builder.endLine;

this.startUnit = builder.startUnit;
this.endUnit = builder.endUnit;
}

public String getHashHex() {
return getBlockHash().toString();
}

+ 1
- 2
sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java View File

@@ -30,6 +30,7 @@ import java.util.Arrays;
* also maybe we can incorporate it into Block to reduce memory footprint during detection of duplicates
*/
public final class ByteArray {
private static final String HEXES = "0123456789abcdef";

private final byte[] bytes;

@@ -103,8 +104,6 @@ public final class ByteArray {
return result;
}

private static final String HEXES = "0123456789abcdef";

public String toHexString() {
StringBuilder hex = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {

+ 5
- 6
sonar-duplications/src/main/java/org/sonar/duplications/detector/original/BlocksGroup.java View File

@@ -30,8 +30,13 @@ import org.sonar.duplications.utils.FastStringComparator;
* Set of {@link Block}s, which internally stored as a sorted list.
*/
final class BlocksGroup {
private static final Comparator<String> RESOURCE_ID_COMPARATOR = FastStringComparator.INSTANCE;
final List<Block> blocks;

private BlocksGroup() {
this.blocks = new ArrayList<>();
}

/**
* Factory method.
*
@@ -41,10 +46,6 @@ final class BlocksGroup {
return new BlocksGroup();
}

private BlocksGroup() {
this.blocks = new ArrayList<>();
}

public int size() {
return blocks.size();
}
@@ -193,8 +194,6 @@ final class BlocksGroup {
return result;
}

private static final Comparator<String> RESOURCE_ID_COMPARATOR = FastStringComparator.INSTANCE;

/**
* Compares {@link Block}s first using {@link Block#getResourceId() resource id} and then using {@link Block#getIndexInFile() index in file}.
*/

+ 6
- 15
sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/TextSet.java View File

@@ -21,7 +21,6 @@ package org.sonar.duplications.detector.suffixtree;

import java.util.ArrayList;
import java.util.List;

import org.sonar.duplications.block.Block;


@@ -29,10 +28,15 @@ import org.sonar.duplications.block.Block;
* Simplifies construction of <a href="http://en.wikipedia.org/wiki/Generalised_suffix_tree">generalised suffix-tree</a>.
*/
public final class TextSet extends AbstractText {
private final int lengthOfOrigin;

private TextSet(List<Object> symbols, int lengthOfOrigin) {
super(symbols);
this.lengthOfOrigin = lengthOfOrigin;
}
public static final class Builder {

private List<Object> symbols = new ArrayList<>();
private final List<Object> symbols = new ArrayList<>();
private Integer lengthOfOrigin;
private int count;

@@ -58,13 +62,6 @@ public final class TextSet extends AbstractText {
return new Builder();
}

private final int lengthOfOrigin;

private TextSet(List<Object> symbols, int lengthOfOrigin) {
super(symbols);
this.lengthOfOrigin = lengthOfOrigin;
}

public boolean isInsideOrigin(int pos) {
return pos < lengthOfOrigin;
}
@@ -100,15 +97,9 @@ public final class TextSet extends AbstractText {
return stringNumber;
}

public int getStringNumber() {
return stringNumber;
}

@Override
public String toString() {
return "$" + stringNumber;
}

}

}

+ 5
- 2
sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/MultivalueProperty.java View File

@@ -25,21 +25,24 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.ArrayUtils;

import static java.util.function.UnaryOperator.identity;

public class MultivalueProperty {
private MultivalueProperty() {
// prevents instantiation
}

public static String[] parseAsCsv(String key, String value) {
return parseAsCsv(key, value, Function.identity());
return parseAsCsv(key, value, identity());
}

public static String[] parseAsCsv(String key, String value, Function<String, String> valueProcessor) {
public static String[] parseAsCsv(String key, String value, UnaryOperator<String> valueProcessor) {
String cleanValue = MultivalueProperty.trimFieldsAndRemoveEmptyFields(value);
List<String> result = new ArrayList<>();
try (CSVParser csvParser = CSVFormat.RFC4180

+ 2
- 0
sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/server/RulesDefinitionContext.java View File

@@ -58,6 +58,7 @@ public class RulesDefinitionContext extends RulesDefinition.Context {
return unmodifiableList(new ArrayList<>(repositoriesByKey.values()));
}

@Override
public void registerRepository(DefaultNewRepository newRepository) {
RulesDefinition.Repository existing = repositoriesByKey.get(newRepository.key());
if (existing != null) {
@@ -69,6 +70,7 @@ public class RulesDefinitionContext extends RulesDefinition.Context {
repositoriesByKey.put(newRepository.key(), new DefaultRepository(newRepository, existing));
}

@Override
public String currentPluginKey() {
return currentPluginKey;
}

+ 3
- 3
sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/AlwaysIncreasingSystem2.java View File

@@ -21,7 +21,7 @@ package org.sonar.api.impl.utils;

import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.function.LongSupplier;
import org.sonar.api.utils.System2;

import static org.sonar.api.utils.Preconditions.checkArgument;
@@ -38,9 +38,9 @@ public class AlwaysIncreasingSystem2 extends System2 {
private final AtomicLong now;
private final long increment;

private AlwaysIncreasingSystem2(Supplier<Long> initialValueSupplier, long increment) {
private AlwaysIncreasingSystem2(LongSupplier initialValueSupplier, long increment) {
checkArgument(increment > 0, "increment must be > 0");
long initialValue = initialValueSupplier.get();
long initialValue = initialValueSupplier.getAsLong();
checkArgument(initialValue >= 0, "Initial value must be >= 0");
this.now = new AtomicLong(initialValue);
this.increment = increment;

+ 2
- 2
sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java View File

@@ -23,12 +23,12 @@ import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import java.util.function.Function;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;

import static java.util.function.UnaryOperator.identity;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;
@@ -46,7 +46,7 @@ public class MultivaluePropertyTest {
public void parseAsCsv_for_coverage(String value, String[] expected) {
// parseAsCsv is extensively tested in org.sonar.server.config.ConfigurationProviderTest
assertThat(parseAsCsv("key", value))
.isEqualTo(parseAsCsv("key", value, Function.identity()))
.isEqualTo(parseAsCsv("key", value, identity()))
.isEqualTo(expected);
}


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

@@ -109,7 +109,7 @@ public class Checks<C> {
}

public Checks<C> addAnnotatedChecks(Object... checkClassesOrObjects) {
return addAnnotatedChecks((Iterable) Arrays.asList(checkClassesOrObjects));
return addAnnotatedChecks(Arrays.asList(checkClassesOrObjects));
}

public Checks<C> addAnnotatedChecks(Iterable checkClassesOrObjects) {

+ 11
- 15
sonar-plugin-api/src/main/java/org/sonar/api/rules/AnnotationRuleParser.java View File

@@ -44,8 +44,18 @@ import org.sonar.api.utils.log.Loggers;
@ServerSide
@ComputeEngineSide
public final class AnnotationRuleParser {

private static final Logger LOG = Loggers.get(AnnotationRuleParser.class);
private static final Map<Class<?>, PropertyType> TYPE_FOR_CLASS_MAP = new HashMap<>();
private static final Function<Class<?>, PropertyType> TYPE_FOR_CLASS = type -> TYPE_FOR_CLASS_MAP.getOrDefault(type, PropertyType.STRING);

static {
TYPE_FOR_CLASS_MAP.put(Integer.class, PropertyType.INTEGER);
TYPE_FOR_CLASS_MAP.put(int.class, PropertyType.INTEGER);
TYPE_FOR_CLASS_MAP.put(Float.class, PropertyType.FLOAT);
TYPE_FOR_CLASS_MAP.put(float.class, PropertyType.FLOAT);
TYPE_FOR_CLASS_MAP.put(Boolean.class, PropertyType.BOOLEAN);
TYPE_FOR_CLASS_MAP.put(boolean.class, PropertyType.BOOLEAN);
}

public List<Rule> parse(String repositoryKey, Collection<Class> annotatedClasses) {
List<Rule> rules = new ArrayList<>();
@@ -101,20 +111,6 @@ public final class AnnotationRuleParser {
}
}

private static final Map<Class<?>, PropertyType> TYPE_FOR_CLASS_MAP = new HashMap<>();

static {
TYPE_FOR_CLASS_MAP.put(Integer.class, PropertyType.INTEGER);
TYPE_FOR_CLASS_MAP.put(int.class, PropertyType.INTEGER);
TYPE_FOR_CLASS_MAP.put(Float.class, PropertyType.FLOAT);
TYPE_FOR_CLASS_MAP.put(float.class, PropertyType.FLOAT);
TYPE_FOR_CLASS_MAP.put(Boolean.class, PropertyType.BOOLEAN);
TYPE_FOR_CLASS_MAP.put(boolean.class, PropertyType.BOOLEAN);

}

private static final Function<Class<?>, PropertyType> TYPE_FOR_CLASS = type -> TYPE_FOR_CLASS_MAP.getOrDefault(type, PropertyType.STRING);

static PropertyType guessType(Class<?> type) {
return TYPE_FOR_CLASS.apply(type);
}

+ 1
- 2
sonar-plugin-api/src/main/java/org/sonar/api/utils/text/CsvWriter.java View File

@@ -28,10 +28,9 @@ import java.io.Writer;
* @since 4.2
*/
public class CsvWriter {

private final Writer writer;
private static final String VALUE_SEPARATOR = ",";
private static final String LINE_SEPARATOR = "\r\n";
private final Writer writer;

private CsvWriter(Writer writer) {
this.writer = writer;

+ 6
- 6
sonar-plugin-api/src/test/java/org/sonar/api/rules/RulePriorityTest.java View File

@@ -28,12 +28,12 @@ public class RulePriorityTest {

@Test
public void testValueOfString() {
assertThat(RulePriority.INFO).isEqualTo(RulePriority.valueOfString("info"));
assertThat(RulePriority.MAJOR).isEqualTo(RulePriority.valueOfString("MAJOR"));
assertThat(RulePriority.MAJOR).isEqualTo(RulePriority.valueOfString("ERROR"));
assertThat(RulePriority.INFO).isEqualTo(RulePriority.valueOfString("WARNING"));
assertThat(RulePriority.MAJOR).isEqualTo(RulePriority.valueOfString("ErRor"));
assertThat(RulePriority.INFO).isEqualTo(RulePriority.valueOfString("WaRnInG"));
assertThat(RulePriority.valueOfString("info")).isEqualTo(RulePriority.INFO);
assertThat(RulePriority.valueOfString("MAJOR")).isEqualTo(RulePriority.MAJOR);
assertThat(RulePriority.valueOfString("ERROR")).isEqualTo(RulePriority.MAJOR);
assertThat(RulePriority.valueOfString("WARNING")).isEqualTo(RulePriority.INFO);
assertThat(RulePriority.valueOfString("ErRor")).isEqualTo(RulePriority.MAJOR);
assertThat(RulePriority.valueOfString("WaRnInG")).isEqualTo(RulePriority.INFO);
}

@Test(expected = IllegalArgumentException.class)

+ 2
- 2
sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/CharsetValidation.java View File

@@ -93,8 +93,8 @@ public class CharsetValidation {
}
}

double beAsciiPerc = beAscii * 2.0 / (double) buffer.length;
double leAsciiPerc = leAscii * 2.0 / (double) buffer.length;
double beAsciiPerc = beAscii * 2.0D / buffer.length;
double leAsciiPerc = leAscii * 2.0D / buffer.length;

if (leLines == 0) {
// could be BE

Loading…
Cancel
Save