Browse Source

Fix quality flaws

tags/5.2-RC1
Julien Lancelot 9 years ago
parent
commit
81c526901f
87 changed files with 801 additions and 809 deletions
  1. 1
    1
      plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplate.java
  2. 10
    12
      server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java
  3. 4
    5
      server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java
  4. 6
    8
      server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java
  5. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/component/ws/EventsWs.java
  6. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/component/ws/SearchAction.java
  7. 2
    0
      server/sonar-server/src/main/java/org/sonar/server/computation/component/ComponentImpl.java
  8. 4
    5
      server/sonar-server/src/main/java/org/sonar/server/computation/source/SymbolsLineReader.java
  9. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/computation/step/ComputationSteps.java
  10. 346
    0
      server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistComponentsAndSnapshotsStep.java
  11. 0
    260
      server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistComponentsStep.java
  12. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java
  13. 3
    3
      server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java
  14. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/computation/step/PopulateComponentsUuidAndKeyStep.java
  15. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/config/ws/PropertiesWs.java
  16. 5
    5
      server/sonar-server/src/main/java/org/sonar/server/dashboard/template/ProjectTimeMachineDashboard.java
  17. 1
    3
      server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/ReplaceIssueFiltersProjectKeyByUuid.java
  18. 3
    6
      server/sonar-server/src/main/java/org/sonar/server/db/migrations/v51/AddNewCharacteristics.java
  19. 7
    9
      server/sonar-server/src/main/java/org/sonar/server/debt/DebtCharacteristicsXMLImporter.java
  20. 5
    7
      server/sonar-server/src/main/java/org/sonar/server/debt/DebtModelOperations.java
  21. 18
    20
      server/sonar-server/src/main/java/org/sonar/server/debt/DebtModelXMLExporter.java
  22. 11
    13
      server/sonar-server/src/main/java/org/sonar/server/debt/DebtRulesXMLImporter.java
  23. 6
    8
      server/sonar-server/src/main/java/org/sonar/server/duplication/ws/DuplicationsJsonWriter.java
  24. 3
    4
      server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java
  25. 4
    5
      server/sonar-server/src/main/java/org/sonar/server/issue/CommentAction.java
  26. 14
    16
      server/sonar-server/src/main/java/org/sonar/server/issue/InternalRubyIssueService.java
  27. 11
    13
      server/sonar-server/src/main/java/org/sonar/server/issue/IssueBulkChangeService.java
  28. 3
    5
      server/sonar-server/src/main/java/org/sonar/server/issue/SetSeverityAction.java
  29. 5
    7
      server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java
  30. 8
    10
      server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java
  31. 7
    7
      server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanWs.java
  32. 14
    14
      server/sonar-server/src/main/java/org/sonar/server/issue/ws/IssuesWs.java
  33. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java
  34. 9
    11
      server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterSql.java
  35. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/measure/ws/ManualMeasuresWs.java
  36. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/metric/ws/CreateAction.java
  37. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/metric/ws/MetricsWs.java
  38. 6
    8
      server/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionService.java
  39. 9
    11
      server/sonar-server/src/main/java/org/sonar/server/permission/PermissionFinder.java
  40. 2
    2
      server/sonar-server/src/main/java/org/sonar/server/permission/ws/PermissionsWs.java
  41. 4
    5
      server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java
  42. 3
    5
      server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/ShowAction.java
  43. 13
    15
      server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java
  44. 14
    15
      server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporters.java
  45. 2
    2
      server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java
  46. 3
    6
      server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java
  47. 8
    8
      server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProfilesWs.java
  48. 7
    9
      server/sonar-server/src/main/java/org/sonar/server/rule/DeprecatedRulesDefinitionLoader.java
  49. 9
    6
      server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java
  50. 4
    5
      server/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java
  51. 12
    13
      server/sonar-server/src/main/java/org/sonar/server/rule/RuleUpdater.java
  52. 26
    9
      server/sonar-server/src/main/java/org/sonar/server/search/BaseIndex.java
  53. 4
    6
      server/sonar-server/src/main/java/org/sonar/server/source/HtmlTextDecorator.java
  54. 2
    1
      server/sonar-server/src/main/java/org/sonar/server/source/db/FileSourceDao.java
  55. 4
    6
      server/sonar-server/src/main/java/org/sonar/server/startup/JdbcDriverDeployer.java
  56. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java
  57. 2
    3
      server/sonar-server/src/main/java/org/sonar/server/user/GroupMembershipFinder.java
  58. 2
    3
      server/sonar-server/src/main/java/org/sonar/server/user/GroupMembershipService.java
  59. 3
    4
      server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java
  60. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/user/ws/FavoritesWs.java
  61. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java
  62. 1
    1
      server/sonar-server/src/main/java/org/sonar/server/user/ws/UserPropertiesWs.java
  63. 3
    4
      server/sonar-server/src/main/java/org/sonar/server/view/index/ViewIndexer.java
  64. 22
    49
      server/sonar-server/src/test/java/org/sonar/server/computation/step/PersistComponentsAndSnapshotsStepTest.java
  65. 4
    6
      sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/output/BatchReportReader.java
  66. 2
    3
      sonar-batch/src/main/java/org/sonar/batch/DefaultFileLinesContext.java
  67. 1
    1
      sonar-batch/src/main/java/org/sonar/batch/compute/AbstractNewCoverageFileAnalyzer.java
  68. 7
    7
      sonar-batch/src/main/java/org/sonar/batch/compute/CountUnresolvedIssuesDecorator.java
  69. 1
    1
      sonar-batch/src/main/java/org/sonar/batch/compute/TimeMachineConfigurationPersister.java
  70. 7
    9
      sonar-batch/src/main/java/org/sonar/batch/debt/DebtDecorator.java
  71. 3
    4
      sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java
  72. 14
    16
      sonar-batch/src/main/java/org/sonar/batch/debt/IssueChangelogDebtCalculator.java
  73. 5
    7
      sonar-batch/src/main/java/org/sonar/batch/debt/NewDebtDecorator.java
  74. 6
    8
      sonar-batch/src/main/java/org/sonar/batch/debt/SqaleRatingDecorator.java
  75. 3
    4
      sonar-batch/src/main/java/org/sonar/batch/debt/SqaleRatingSettings.java
  76. 2
    3
      sonar-batch/src/main/java/org/sonar/batch/issue/ModuleIssues.java
  77. 4
    5
      sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java
  78. 6
    8
      sonar-core/src/main/java/org/sonar/core/notification/DefaultNotificationManager.java
  79. 3
    5
      sonar-core/src/main/java/org/sonar/core/permission/PermissionQuery.java
  80. 6
    7
      sonar-core/src/main/java/org/sonar/core/resource/ResourceKeyUpdaterDao.java
  81. 12
    14
      sonar-core/src/main/java/org/sonar/core/timemachine/Periods.java
  82. 1
    1
      sonar-core/src/main/java/org/sonar/core/user/GroupMembershipQuery.java
  83. 3
    5
      sonar-plugin-api/src/main/java/org/sonar/api/issue/internal/FieldDiffs.java
  84. 2
    3
      sonar-plugin-api/src/main/java/org/sonar/api/measures/AverageFormula.java
  85. 14
    16
      sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java
  86. 2
    3
      sonar-plugin-api/src/main/java/org/sonar/api/server/rule/RuleParamType.java
  87. 5
    7
      sonar-plugin-api/src/main/java/org/sonar/api/utils/Durations.java

+ 1
- 1
plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplate.java View File

@@ -65,7 +65,7 @@ public class AlertsEmailTemplate extends EmailTemplate {
.setMessage(messageBody);
}

private String generateSubject(String projectName, String alertLevel, boolean isNewAlert) {
private static String generateSubject(String projectName, String alertLevel, boolean isNewAlert) {
StringBuilder subjectBuilder = new StringBuilder();
if (Metric.Level.OK.toString().equals(alertLevel)) {
subjectBuilder.append("\"").append(projectName).append("\" is back to green");

+ 10
- 12
server/sonar-server/src/main/java/org/sonar/server/batch/ProjectRepositoryLoader.java View File

@@ -24,6 +24,12 @@ import com.google.common.base.Function;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
@@ -54,14 +60,6 @@ import org.sonar.server.search.QueryContext;
import org.sonar.server.search.Result;
import org.sonar.server.user.UserSession;

import javax.annotation.Nullable;

import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;

@@ -188,7 +186,7 @@ public class ProjectRepositoryLoader {
}
}

private Map<String, String> getPropertiesMap(List<PropertyDto> propertyDtos, boolean hasScanPerm) {
private static Map<String, String> getPropertiesMap(List<PropertyDto> propertyDtos, boolean hasScanPerm) {
Map<String, String> properties = newHashMap();
for (PropertyDto propertyDto : propertyDtos) {
String key = propertyDto.getKey();
@@ -292,7 +290,7 @@ public class ProjectRepositoryLoader {
}
}

private void addFileData(DbSession session, ProjectRepositories ref, List<ComponentDto> moduleChildren, List<FilePathWithHashDto> files) {
private static void addFileData(DbSession session, ProjectRepositories ref, List<ComponentDto> moduleChildren, List<FilePathWithHashDto> files) {
Map<String, String> moduleKeysByUuid = newHashMap();
for (ComponentDto module : moduleChildren) {
moduleKeysByUuid.put(module.uuid(), module.key());
@@ -320,7 +318,7 @@ public class ProjectRepositoryLoader {
}
}

private Map<String, String> moduleUuidsByKey(ComponentDto module, List<ComponentDto> moduleChildren) {
private static Map<String, String> moduleUuidsByKey(ComponentDto module, List<ComponentDto> moduleChildren) {
Map<String, String> moduleUuidsByKey = newHashMap();
for (ComponentDto componentDto : moduleChildren) {
moduleUuidsByKey.put(componentDto.key(), componentDto.uuid());
@@ -328,7 +326,7 @@ public class ProjectRepositoryLoader {
return moduleUuidsByKey;
}

private Map<String, Long> moduleIdsByKey(ComponentDto module, List<ComponentDto> moduleChildren) {
private static Map<String, Long> moduleIdsByKey(ComponentDto module, List<ComponentDto> moduleChildren) {
Map<String, Long> moduleIdsByKey = newHashMap();
for (ComponentDto componentDto : moduleChildren) {
moduleIdsByKey.put(componentDto.key(), componentDto.getId());

+ 4
- 5
server/sonar-server/src/main/java/org/sonar/server/component/DefaultComponentFinder.java View File

@@ -22,15 +22,14 @@ package org.sonar.server.component;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.sonar.api.component.Component;
import org.sonar.api.utils.Paging;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -98,7 +97,7 @@ public class DefaultComponentFinder {
}
}

private Collection<? extends Component> pagedComponents(Collection<? extends Component> components, Paging paging) {
private static Collection<? extends Component> pagedComponents(Collection<? extends Component> components, Paging paging) {
Set<Component> pagedComponents = Sets.newLinkedHashSet();
int index = 0;
for (Component component : components) {

+ 6
- 8
server/sonar-server/src/main/java/org/sonar/server/component/ws/AppAction.java View File

@@ -20,6 +20,10 @@

package org.sonar.server.component.ws;

import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.BooleanUtils;
import org.sonar.api.i18n.I18n;
import org.sonar.api.measures.CoreMetrics;
@@ -41,12 +45,6 @@ import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.List;
import java.util.Map;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;

@@ -149,7 +147,7 @@ public class AppAction implements RequestHandler {
json.prop("fav", isFavourite);
}

private void appendPermissions(JsonWriter json, ComponentDto component, UserSession userSession) {
private static void appendPermissions(JsonWriter json, ComponentDto component, UserSession userSession) {
boolean hasBrowsePermission = userSession.hasComponentPermission(UserRole.USER, component.key());
json.prop("canMarkAsFavourite", userSession.isLoggedIn() && hasBrowsePermission);
json.prop("canCreateManualIssue", userSession.isLoggedIn() && hasBrowsePermission);
@@ -168,7 +166,7 @@ public class AppAction implements RequestHandler {
json.endObject();
}

private MeasureDto coverageMeasure(Map<String, MeasureDto> measuresByMetricKey) {
private static MeasureDto coverageMeasure(Map<String, MeasureDto> measuresByMetricKey) {
MeasureDto overallCoverage = measuresByMetricKey.get(CoreMetrics.OVERALL_COVERAGE_KEY);
MeasureDto itCoverage = measuresByMetricKey.get(CoreMetrics.IT_COVERAGE_KEY);
MeasureDto utCoverage = measuresByMetricKey.get(CoreMetrics.COVERAGE_KEY);

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/component/ws/EventsWs.java View File

@@ -36,7 +36,7 @@ public class EventsWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.6")

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/component/ws/SearchAction.java View File

@@ -120,7 +120,7 @@ public class SearchAction implements RequestHandler {
json.close();
}

private Set<Long> pagedProjectIds(Collection<Long> projectIds, SearchOptions options) {
private static Set<Long> pagedProjectIds(Collection<Long> projectIds, SearchOptions options) {
Set<Long> results = Sets.newLinkedHashSet();
int index = 0;
for (Long projectId : projectIds) {

+ 2
- 0
server/sonar-server/src/main/java/org/sonar/server/computation/component/ComponentImpl.java View File

@@ -69,6 +69,7 @@ public class ComponentImpl implements Component {
return ref;
}

@Override
public String getUuid() {
if (uuid == null) {
throw new UnsupportedOperationException(String.format("Component uuid of ref '%s' has not be fed yet", getRef()));
@@ -81,6 +82,7 @@ public class ComponentImpl implements Component {
return this;
}

@Override
public String getKey() {
if (key == null) {
throw new UnsupportedOperationException(String.format("Component key of ref '%s' has not be fed yet", getRef()));

+ 4
- 5
server/sonar-server/src/main/java/org/sonar/server/computation/source/SymbolsLineReader.java View File

@@ -20,9 +20,6 @@

package org.sonar.server.computation.source;

import org.sonar.batch.protocol.output.BatchReport;
import org.sonar.server.source.db.FileSourceDb;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
@@ -32,6 +29,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.batch.protocol.output.BatchReport;
import org.sonar.server.source.db.FileSourceDb;

import static com.google.common.collect.Lists.newArrayList;

@@ -68,7 +67,7 @@ public class SymbolsLineReader implements LineReader {
}
}

private void appendSymbol(StringBuilder lineSymbol, BatchReport.Range range, int line, int symbolId, String sourceLine) {
private static void appendSymbol(StringBuilder lineSymbol, BatchReport.Range range, int line, int symbolId, String sourceLine) {
if (matchLine(range, line)) {
String offsets = RangeOffsetHelper.offsetToString(range, line, sourceLine.length());
if (!offsets.isEmpty()) {
@@ -105,7 +104,7 @@ public class SymbolsLineReader implements LineReader {
return range.getStartLine() <= line && range.getEndLine() >= line;
}

private Map<BatchReport.Symbols.Symbol, Integer> createIdsBySymbolMap(List<BatchReport.Symbols.Symbol> symbols) {
private static Map<BatchReport.Symbols.Symbol, Integer> createIdsBySymbolMap(List<BatchReport.Symbols.Symbol> symbols) {
Map<BatchReport.Symbols.Symbol, Integer> map = new HashMap<>();
int symbolId = 1;
for (BatchReport.Symbols.Symbol symbol : symbols) {

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/computation/step/ComputationSteps.java View File

@@ -52,7 +52,7 @@ public class ComputationSteps {
QualityProfileEventsStep.class,

// Persist data
PersistComponentsStep.class,
PersistComponentsAndSnapshotsStep.class,
PersistNumberOfDaysSinceLastCommitStep.class,
PersistMeasuresStep.class,
PersistIssuesStep.class,

+ 346
- 0
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistComponentsAndSnapshotsStep.java View File

@@ -0,0 +1,346 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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.server.computation.step;

import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
import org.sonar.batch.protocol.output.BatchReport;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.component.SnapshotDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.util.NonNullInputFunction;
import org.sonar.server.computation.batch.BatchReportReader;
import org.sonar.server.computation.component.Component;
import org.sonar.server.computation.component.DbIdsRepository;
import org.sonar.server.computation.component.TreeRootHolder;
import org.sonar.server.db.DbClient;

/**
* Persist components and snapshots
* Also feed the components cache {@link DbIdsRepository}
*/
public class PersistComponentsAndSnapshotsStep implements ComputationStep {

private final System2 system2;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final BatchReportReader reportReader;

private final DbIdsRepository dbIdsRepositor;

public PersistComponentsAndSnapshotsStep(System2 system2, DbClient dbClient, TreeRootHolder treeRootHolder, BatchReportReader reportReader, DbIdsRepository dbIdsRepositor) {
this.system2 = system2;
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.reportReader = reportReader;
this.dbIdsRepositor = dbIdsRepositor;
}

@Override
public void execute() {
DbSession session = dbClient.openSession(false);
try {
org.sonar.server.computation.component.Component root = treeRootHolder.getRoot();
List<ComponentDto> components = dbClient.componentDao().selectComponentsFromProjectKey(session, root.getKey());
Map<String, ComponentDto> componentDtosByKey = componentDtosByKey(components);
PersisComponentExecutor componentContext = new PersisComponentExecutor(session, componentDtosByKey, reportReader, reportReader.readMetadata().getAnalysisDate());

componentContext.recursivelyProcessComponent(root, null, null);
session.commit();
} finally {
session.close();
}
}

private class PersisComponentExecutor {

private final BatchReportReader reportReader;
private final Map<String, ComponentDto> componentDtosByKey;
private final DbSession dbSession;
private final long analysisDate;

private ComponentDto project;
private SnapshotDto projectSnapshot;

public PersisComponentExecutor(DbSession dbSession, Map<String, ComponentDto> componentDtosByKey, BatchReportReader reportReader, long analysisDate) {
this.reportReader = reportReader;
this.componentDtosByKey = componentDtosByKey;
this.dbSession = dbSession;
this.analysisDate = analysisDate;
}

private void recursivelyProcessComponent(Component component, @Nullable ComponentDto lastModule, @Nullable SnapshotDto parentSnapshot) {
BatchReport.Component reportComponent = reportReader.readComponent(component.getRef());

switch (component.getType()) {
case PROJECT:
PersistedComponent persistedProject = processProject(component, reportComponent);
this.project = persistedProject.componentDto;
this.projectSnapshot = persistedProject.parentSnapshot;
processChildren(component, project, persistedProject.parentSnapshot);
break;
case MODULE:
PersistedComponent persistedModule = processModule(component, reportComponent, nonNullLastModule(lastModule), nonNullParentSnapshot(parentSnapshot));
processChildren(component, persistedModule.componentDto, persistedModule.parentSnapshot);
break;
case DIRECTORY:
PersistedComponent persistedDirectory = processDirectory(component, reportComponent, nonNullLastModule(lastModule), nonNullParentSnapshot(parentSnapshot));
processChildren(component, nonNullLastModule(lastModule), persistedDirectory.parentSnapshot);
break;
case FILE:
processFile(component, reportComponent, nonNullLastModule(lastModule), nonNullParentSnapshot(parentSnapshot));
break;
default:
throw new IllegalStateException(String.format("Unsupported component type '%s'", component.getType()));
}
}

private void processChildren(Component component, ComponentDto lastModule, SnapshotDto parentSnapshot) {
for (Component child : component.getChildren()) {
recursivelyProcessComponent(child, lastModule, parentSnapshot);
}
}

private ComponentDto nonNullLastModule(@Nullable ComponentDto lastModule) {
return lastModule == null ? project : lastModule;
}

private SnapshotDto nonNullParentSnapshot(@Nullable SnapshotDto parentSnapshot) {
return parentSnapshot == null ? projectSnapshot : parentSnapshot;
}

public PersistedComponent processProject(Component project, BatchReport.Component reportComponent) {
ComponentDto componentDto = createComponentDto(reportComponent, project);

componentDto.setScope(Scopes.PROJECT);
componentDto.setQualifier(Qualifiers.PROJECT);
componentDto.setName(reportComponent.getName());
componentDto.setLongName(componentDto.name());
if (reportComponent.hasDescription()) {
componentDto.setDescription(reportComponent.getDescription());
}
componentDto.setProjectUuid(componentDto.uuid());
componentDto.setModuleUuidPath(ComponentDto.MODULE_UUID_PATH_SEP + componentDto.uuid() + ComponentDto.MODULE_UUID_PATH_SEP);

ComponentDto projectDto = persistComponent(project.getRef(), componentDto);
SnapshotDto snapshotDto = persistSnapshot(projectDto, reportComponent.getVersion(), null);

addToCache(project, projectDto, snapshotDto);

return new PersistedComponent(projectDto, snapshotDto);
}

public PersistedComponent processModule(Component module, BatchReport.Component reportComponent, ComponentDto lastModule, SnapshotDto parentSnapshot) {
ComponentDto componentDto = createComponentDto(reportComponent, module);

componentDto.setScope(Scopes.PROJECT);
componentDto.setQualifier(Qualifiers.MODULE);
componentDto.setName(reportComponent.getName());
componentDto.setLongName(componentDto.name());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}
if (reportComponent.hasDescription()) {
componentDto.setDescription(reportComponent.getDescription());
}
componentDto.setParentProjectId(project.getId());
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath(lastModule.moduleUuidPath() + componentDto.uuid() + ComponentDto.MODULE_UUID_PATH_SEP);

ComponentDto moduleDto = persistComponent(module.getRef(), componentDto);
SnapshotDto snapshotDto = persistSnapshot(moduleDto, reportComponent.getVersion(), parentSnapshot);

addToCache(module, moduleDto, snapshotDto);
return new PersistedComponent(moduleDto, snapshotDto);
}

public PersistedComponent processDirectory(org.sonar.server.computation.component.Component directory, BatchReport.Component reportComponent,
ComponentDto lastModule, SnapshotDto parentSnapshot) {
ComponentDto componentDto = createComponentDto(reportComponent, directory);

componentDto.setScope(Scopes.DIRECTORY);
componentDto.setQualifier(Qualifiers.DIRECTORY);
componentDto.setName(reportComponent.getPath());
componentDto.setLongName(reportComponent.getPath());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}

componentDto.setParentProjectId(lastModule.getId());
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath(lastModule.moduleUuidPath());

ComponentDto directoryDto = persistComponent(directory.getRef(), componentDto);
SnapshotDto snapshotDto = persistSnapshot(directoryDto, null, parentSnapshot);

addToCache(directory, directoryDto, snapshotDto);
return new PersistedComponent(directoryDto, snapshotDto);
}

public void processFile(org.sonar.server.computation.component.Component file, BatchReport.Component reportComponent,
ComponentDto lastModule, SnapshotDto parentSnapshot) {
ComponentDto componentDto = createComponentDto(reportComponent, file);

componentDto.setScope(Scopes.FILE);
componentDto.setQualifier(getFileQualifier(reportComponent));
componentDto.setName(FilenameUtils.getName(reportComponent.getPath()));
componentDto.setLongName(reportComponent.getPath());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}
if (reportComponent.hasLanguage()) {
componentDto.setLanguage(reportComponent.getLanguage());
}

componentDto.setParentProjectId(lastModule.getId());
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath(lastModule.moduleUuidPath());

ComponentDto fileDto = persistComponent(file.getRef(), componentDto);
SnapshotDto snapshotDto = persistSnapshot(fileDto, null, parentSnapshot);

addToCache(file, fileDto, snapshotDto);
}

private ComponentDto createComponentDto(BatchReport.Component reportComponent, org.sonar.server.computation.component.Component component) {
String componentKey = component.getKey();
String componentUuid = component.getUuid();

ComponentDto componentDto = new ComponentDto();
componentDto.setUuid(componentUuid);
componentDto.setKey(componentKey);
componentDto.setDeprecatedKey(componentKey);
componentDto.setEnabled(true);
return componentDto;
}

private ComponentDto persistComponent(int componentRef, ComponentDto componentDto) {
ComponentDto existingComponent = componentDtosByKey.get(componentDto.getKey());
if (existingComponent == null) {
dbClient.componentDao().insert(dbSession, componentDto);
return componentDto;
} else {
if (updateComponent(existingComponent, componentDto)) {
dbClient.componentDao().update(dbSession, existingComponent);
}
return existingComponent;
}
}

private SnapshotDto persistSnapshot(ComponentDto componentDto, @Nullable String version, @Nullable SnapshotDto parentSnapshot){
SnapshotDto snapshotDto = new SnapshotDto();
// .setRootProjectId(project.getId())
// .setVersion(version)
// .setComponentId(componentDto.getId())
// .setQualifier(componentDto.qualifier())
// .setScope(componentDto.scope())
// .setCreatedAt(analysisDate)
// .setBuildDate(system2.now());
//
// if (parentSnapshot != null) {
// snapshotDto
// .setParentId(parentSnapshot.getId())
// .setRootId(parentSnapshot.getRootId() == null ? parentSnapshot.getId() : parentSnapshot.getRootId())
// .setDepth(parentSnapshot.getDepth() + 1)
// .setPath(parentSnapshot.getPath() + parentSnapshot.getId() + ".");
// } else {
// snapshotDto
// .setPath("")
// .setDepth(0);
// }
// dbClient.snapshotDao().insert(dbSession, snapshotDto);
return snapshotDto;
}

private void addToCache(Component component, ComponentDto componentDto, SnapshotDto snapshotDto) {
dbIdsRepositor.setComponentId(component, componentDto.getId());
}

private boolean updateComponent(ComponentDto existingComponent, ComponentDto newComponent) {
boolean isUpdated = false;
if (!StringUtils.equals(existingComponent.name(), newComponent.name())) {
existingComponent.setName(newComponent.name());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.description(), newComponent.description())) {
existingComponent.setDescription(newComponent.description());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.path(), newComponent.path())) {
existingComponent.setPath(newComponent.path());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.moduleUuid(), newComponent.moduleUuid())) {
existingComponent.setModuleUuid(newComponent.moduleUuid());
isUpdated = true;
}
if (!existingComponent.moduleUuidPath().equals(newComponent.moduleUuidPath())) {
existingComponent.setModuleUuidPath(newComponent.moduleUuidPath());
isUpdated = true;
}
if (!ObjectUtils.equals(existingComponent.parentProjectId(), newComponent.parentProjectId())) {
existingComponent.setParentProjectId(newComponent.parentProjectId());
isUpdated = true;
}
return isUpdated;
}

private String getFileQualifier(BatchReport.Component reportComponent) {
return reportComponent.getIsTest() ? Qualifiers.UNIT_TEST_FILE : Qualifiers.FILE;
}

private class PersistedComponent {
private ComponentDto componentDto;
private SnapshotDto parentSnapshot;

public PersistedComponent(ComponentDto componentDto, SnapshotDto parentSnapshot) {
this.componentDto = componentDto;
this.parentSnapshot = parentSnapshot;
}
}

}

private static Map<String, ComponentDto> componentDtosByKey(List<ComponentDto> components) {
return Maps.uniqueIndex(components, new NonNullInputFunction<ComponentDto, String>() {
@Override
public String doApply(ComponentDto input) {
return input.key();
}
});
}

@Override
public String getDescription() {
return "Feed components and snapshots";
}
}

+ 0
- 260
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistComponentsStep.java View File

@@ -1,260 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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.server.computation.step;

import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.batch.protocol.output.BatchReport;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.util.NonNullInputFunction;
import org.sonar.server.computation.batch.BatchReportReader;
import org.sonar.server.computation.component.Component;
import org.sonar.server.computation.component.DbIdsRepository;
import org.sonar.server.computation.component.TreeRootHolder;
import org.sonar.server.db.DbClient;

public class PersistComponentsStep implements ComputationStep {

private final DbClient dbClient;
private final DbIdsRepository dbIdsRepository;
private final BatchReportReader reportReader;
private final TreeRootHolder treeRootHolder;

public PersistComponentsStep(DbClient dbClient, DbIdsRepository dbIdsRepository, BatchReportReader reportReader, TreeRootHolder treeRootHolder) {
this.dbClient = dbClient;
this.dbIdsRepository = dbIdsRepository;
this.reportReader = reportReader;
this.treeRootHolder = treeRootHolder;
}

@Override
public void execute() {
DbSession session = dbClient.openSession(false);
try {
Component root = treeRootHolder.getRoot();
List<ComponentDto> components = dbClient.componentDao().selectComponentsFromProjectKey(session, root.getKey());
Map<String, ComponentDto> componentDtosByKey = componentDtosByKey(components);
ComponentContext componentContext = new ComponentContext(session, componentDtosByKey);

ComponentDto projectDto = processProject(root, reportReader.readComponent(root.getRef()), componentContext);
processChildren(componentContext, root, projectDto, projectDto);
session.commit();
} finally {
session.close();
}
}

private void recursivelyProcessComponent(ComponentContext componentContext, Component component, ComponentDto parentModule, ComponentDto project) {
BatchReport.Component reportComponent = reportReader.readComponent(component.getRef());

switch (component.getType()) {
case MODULE:
ComponentDto moduleDto = processModule(component, reportComponent, componentContext, parentModule, project.getId());
processChildren(componentContext, component, moduleDto, project);
break;
case DIRECTORY:
processDirectory(component, reportComponent, componentContext, parentModule, project.getId());
processChildren(componentContext, component, parentModule, project);
break;
case FILE:
processFile(component, reportComponent, componentContext, parentModule, project.getId());
processChildren(componentContext, component, parentModule, project);
break;
default:
throw new IllegalStateException(String.format("Unsupported component type '%s'", component.getType()));
}
}

private void processChildren(ComponentContext componentContext, Component component, ComponentDto parentModule, ComponentDto project) {
for (Component child : component.getChildren()) {
recursivelyProcessComponent(componentContext, child, parentModule, project);
}
}

public ComponentDto processProject(Component project, BatchReport.Component reportComponent, ComponentContext componentContext) {
ComponentDto componentDto = createComponentDto(project);

componentDto.setScope(Scopes.PROJECT);
componentDto.setQualifier(Qualifiers.PROJECT);
componentDto.setName(reportComponent.getName());
componentDto.setLongName(componentDto.name());
if (reportComponent.hasDescription()) {
componentDto.setDescription(reportComponent.getDescription());
}
componentDto.setProjectUuid(componentDto.uuid());
componentDto.setModuleUuidPath(ComponentDto.MODULE_UUID_PATH_SEP + componentDto.uuid() + ComponentDto.MODULE_UUID_PATH_SEP);

return persistComponent(project, componentDto, componentContext);
}

public ComponentDto processModule(Component module, BatchReport.Component reportComponent, ComponentContext componentContext, ComponentDto lastModule, long projectId) {
ComponentDto componentDto = createComponentDto(module);

componentDto.setScope(Scopes.PROJECT);
componentDto.setQualifier(Qualifiers.MODULE);
componentDto.setName(reportComponent.getName());
componentDto.setLongName(componentDto.name());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}
if (reportComponent.hasDescription()) {
componentDto.setDescription(reportComponent.getDescription());
}
componentDto.setParentProjectId(projectId);
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath((lastModule.moduleUuidPath() + componentDto.uuid() + ComponentDto.MODULE_UUID_PATH_SEP));

return persistComponent(module, componentDto, componentContext);
}

public void processDirectory(Component directory, BatchReport.Component reportComponent, ComponentContext componentContext, ComponentDto lastModule, long projectId) {
ComponentDto componentDto = createComponentDto(directory);

componentDto.setScope(Scopes.DIRECTORY);
componentDto.setQualifier(Qualifiers.DIRECTORY);
componentDto.setName(reportComponent.getPath());
componentDto.setLongName(reportComponent.getPath());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}

componentDto.setParentProjectId(lastModule.getId());
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath(lastModule.moduleUuidPath());

persistComponent(directory, componentDto, componentContext);
}

public void processFile(Component file, BatchReport.Component reportComponent, ComponentContext componentContext, ComponentDto lastModule, long projectId) {
ComponentDto componentDto = createComponentDto(file);

componentDto.setScope(Scopes.FILE);
componentDto.setQualifier(getFileQualifier(reportComponent));
componentDto.setName(FilenameUtils.getName(reportComponent.getPath()));
componentDto.setLongName(reportComponent.getPath());
if (reportComponent.hasPath()) {
componentDto.setPath(reportComponent.getPath());
}
if (reportComponent.hasLanguage()) {
componentDto.setLanguage(reportComponent.getLanguage());
}

componentDto.setParentProjectId(lastModule.getId());
componentDto.setProjectUuid(lastModule.projectUuid());
componentDto.setModuleUuid(lastModule.uuid());
componentDto.setModuleUuidPath(lastModule.moduleUuidPath());

persistComponent(file, componentDto, componentContext);
}

private ComponentDto createComponentDto(Component component) {
String componentKey = component.getKey();
String componentUuid = component.getUuid();

ComponentDto componentDto = new ComponentDto();
componentDto.setUuid(componentUuid);
componentDto.setKey(componentKey);
componentDto.setDeprecatedKey(componentKey);
componentDto.setEnabled(true);
return componentDto;
}

private ComponentDto persistComponent(Component component, ComponentDto componentDto, ComponentContext componentContext) {
ComponentDto existingComponent = componentContext.componentDtosByKey.get(componentDto.getKey());
if (existingComponent == null) {
dbClient.componentDao().insert(componentContext.dbSession, componentDto);
dbIdsRepository.setComponentId(component, componentDto.getId());
return componentDto;
} else {
if (updateComponent(existingComponent, componentDto)) {
dbClient.componentDao().update(componentContext.dbSession, existingComponent);
}
dbIdsRepository.setComponentId(component, existingComponent.getId());
return existingComponent;
}
}

private static boolean updateComponent(ComponentDto existingComponent, ComponentDto newComponent) {
boolean isUpdated = false;
if (!StringUtils.equals(existingComponent.name(), newComponent.name())) {
existingComponent.setName(newComponent.name());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.description(), newComponent.description())) {
existingComponent.setDescription(newComponent.description());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.path(), newComponent.path())) {
existingComponent.setPath(newComponent.path());
isUpdated = true;
}
if (!StringUtils.equals(existingComponent.moduleUuid(), newComponent.moduleUuid())) {
existingComponent.setModuleUuid(newComponent.moduleUuid());
isUpdated = true;
}
if (!existingComponent.moduleUuidPath().equals(newComponent.moduleUuidPath())) {
existingComponent.setModuleUuidPath(newComponent.moduleUuidPath());
isUpdated = true;
}
if (!ObjectUtils.equals(existingComponent.parentProjectId(), newComponent.parentProjectId())) {
existingComponent.setParentProjectId(newComponent.parentProjectId());
isUpdated = true;
}
return isUpdated;
}

private static String getFileQualifier(BatchReport.Component reportComponent) {
return reportComponent.getIsTest() ? Qualifiers.UNIT_TEST_FILE : Qualifiers.FILE;
}

private Map<String, ComponentDto> componentDtosByKey(List<ComponentDto> components) {
return Maps.uniqueIndex(components, new NonNullInputFunction<ComponentDto, String>() {
@Override
public String doApply(ComponentDto input) {
return input.key();
}
});
}

private static class ComponentContext {
private final Map<String, ComponentDto> componentDtosByKey;
private final DbSession dbSession;

public ComponentContext(DbSession dbSession, Map<String, ComponentDto> componentDtosByKey) {
this.componentDtosByKey = componentDtosByKey;
this.dbSession = dbSession;
}
}

@Override
public String getDescription() {
return "Feed components cache";
}
}

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistIssuesStep.java View File

@@ -96,7 +96,7 @@ public class PersistIssuesStep implements ComputationStep {
}
}

private void insertChanges(IssueChangeMapper mapper, DefaultIssue issue) {
private static void insertChanges(IssueChangeMapper mapper, DefaultIssue issue) {
for (IssueComment comment : issue.comments()) {
DefaultIssueComment c = (DefaultIssueComment) comment;
if (c.isNew()) {

+ 3
- 3
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistTestsStep.java View File

@@ -160,11 +160,11 @@ public class PersistTestsStep implements ComputationStep {
BatchReport.Component component) {
Set<String> unprocessedCoverageDetailNames = new HashSet<>(coveredFilesByName.rowKeySet());
unprocessedCoverageDetailNames.removeAll(testsByName.keySet());
boolean hasUnprocessedCoverageDetails = !unprocessedCoverageDetailNames.isEmpty();
if (hasUnprocessedCoverageDetails) {
boolean hasUnprocessedCoverage = !unprocessedCoverageDetailNames.isEmpty();
if (hasUnprocessedCoverage) {
LOG.trace("The following test coverages for file '{}' have not been taken into account: {}", component.getPath(), Joiner.on(", ").join(unprocessedCoverageDetailNames));
}
return hasUnprocessedCoverageDetails;
return hasUnprocessedCoverage;
}

private List<FileSourceDb.Test> addCoveredFilesToTests(Multimap<String, FileSourceDb.Test.Builder> testsByName,

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/computation/step/PopulateComponentsUuidAndKeyStep.java View File

@@ -115,7 +115,7 @@ public class PopulateComponentsUuidAndKeyStep implements ComputationStep {
feedComponent((ComponentImpl) component, componentKey, componentContext.componentUuidsByKey);
}

private void feedComponent(ComponentImpl component, String componentKey, Map<String, String> componentUuidByKey) {
private static void feedComponent(ComponentImpl component, String componentKey, Map<String, String> componentUuidByKey) {
component.setKey(componentKey);

String componentUuid = componentUuidByKey.get(componentKey);

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/config/ws/PropertiesWs.java View File

@@ -36,7 +36,7 @@ public class PropertiesWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.6")

+ 5
- 5
server/sonar-server/src/main/java/org/sonar/server/dashboard/template/ProjectTimeMachineDashboard.java View File

@@ -55,7 +55,7 @@ public final class ProjectTimeMachineDashboard extends DashboardTemplate {
return dashboard;
}

private void addFirstColumn(Dashboard dashboard) {
private static void addFirstColumn(Dashboard dashboard) {
Widget timelineWidget = dashboard.addWidget("timeline", 1);
timelineWidget.setProperty(METRIC1, CoreMetrics.COMPLEXITY_KEY);
timelineWidget.setProperty(METRIC2, CoreMetrics.TECHNICAL_DEBT_KEY);
@@ -83,7 +83,7 @@ public final class ProjectTimeMachineDashboard extends DashboardTemplate {
duplicationTimeMachineWidget.setProperty(METRIC4, CoreMetrics.DUPLICATED_FILES_KEY);
}

private void addSecondColumn(Dashboard dashboard) {
private static void addSecondColumn(Dashboard dashboard) {
Widget rulesTimeMachineWidget = addTimeMachineWidgetOnSecondColumn(dashboard);
rulesTimeMachineWidget.setProperty(METRIC1, CoreMetrics.VIOLATIONS_KEY);
rulesTimeMachineWidget.setProperty(METRIC2, CoreMetrics.BLOCKER_VIOLATIONS_KEY);
@@ -110,15 +110,15 @@ public final class ProjectTimeMachineDashboard extends DashboardTemplate {
testsTimeMachineWidget.setProperty(METRIC8, CoreMetrics.TEST_EXECUTION_TIME_KEY);
}

private Widget addTimeMachineWidgetOnFirstColumn(Dashboard dashboard) {
private static Widget addTimeMachineWidgetOnFirstColumn(Dashboard dashboard) {
return addTimeMachineWidget(dashboard, 1);
}

private Widget addTimeMachineWidgetOnSecondColumn(Dashboard dashboard) {
private static Widget addTimeMachineWidgetOnSecondColumn(Dashboard dashboard) {
return addTimeMachineWidget(dashboard, 2);
}

private Widget addTimeMachineWidget(Dashboard dashboard, int columnIndex) {
private static Widget addTimeMachineWidget(Dashboard dashboard, int columnIndex) {
Widget widget = dashboard.addWidget("time_machine", columnIndex);
widget.setProperty("displaySparkLine", "true");
return widget;

+ 1
- 3
server/sonar-server/src/main/java/org/sonar/server/db/migrations/v50/ReplaceIssueFiltersProjectKeyByUuid.java View File

@@ -25,9 +25,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.annotation.Nullable;

import org.apache.commons.dbutils.DbUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.persistence.Database;
@@ -103,7 +101,7 @@ public class ReplaceIssueFiltersProjectKeyByUuid extends BaseDataChange {
return newFields.toString();
}

private void append(PreparedStatement pstmt, StringBuilder newFields, @Nullable String projectKey) throws SQLException {
private static void append(PreparedStatement pstmt, StringBuilder newFields, @Nullable String projectKey) throws SQLException {
if (projectKey != null) {
pstmt.setString(1, projectKey);
ResultSet rs = null;

+ 3
- 6
server/sonar-server/src/main/java/org/sonar/server/db/migrations/v51/AddNewCharacteristics.java View File

@@ -19,13 +19,13 @@
*/
package org.sonar.server.db.migrations.v51;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.MessageException;
@@ -34,9 +34,6 @@ import org.sonar.core.persistence.Database;
import org.sonar.server.db.migrations.BaseDataChange;
import org.sonar.server.db.migrations.Select;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

/**
* See http://jira.sonarsource.com/browse/SONAR-6187
*
@@ -97,7 +94,7 @@ public class AddNewCharacteristics extends BaseDataChange {
*
* If the characteristic 'Usability' is already at the right place, nothing will be done.
*/
private int moveCharacteristicsDownToBeAbleToInsertUsability(CharacteristicsContext characteristicsContext) throws SQLException {
private static int moveCharacteristicsDownToBeAbleToInsertUsability(CharacteristicsContext characteristicsContext) throws SQLException {
Characteristic security = characteristicsContext.findCharacteristicByKey(SECURITY_KEY);
Characteristic usability = characteristicsContext.findCharacteristicByKey(USABILITY_KEY);


+ 7
- 9
server/sonar-server/src/main/java/org/sonar/server/debt/DebtCharacteristicsXMLImporter.java View File

@@ -20,6 +20,12 @@

package org.sonar.server.debt;

import java.io.Reader;
import java.io.StringReader;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.StringUtils;
import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.staxmate.SMInputFactory;
@@ -30,14 +36,6 @@ import org.sonar.api.server.debt.internal.DefaultDebtCharacteristic;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.server.debt.DebtModelXMLExporter.DebtModel;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

import java.io.Reader;
import java.io.StringReader;

import static org.sonar.server.debt.DebtModelXMLExporter.CHARACTERISTIC;
import static org.sonar.server.debt.DebtModelXMLExporter.CHARACTERISTIC_KEY;
import static org.sonar.server.debt.DebtModelXMLExporter.CHARACTERISTIC_NAME;
@@ -74,7 +72,7 @@ public class DebtCharacteristicsXMLImporter {
return debtModel;
}

private SMInputFactory initStax() {
private static SMInputFactory initStax() {
XMLInputFactory xmlFactory = XMLInputFactory2.newInstance();
xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);

+ 5
- 7
server/sonar-server/src/main/java/org/sonar/server/debt/DebtModelOperations.java View File

@@ -22,6 +22,10 @@ package org.sonar.server.debt;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.Date;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.ibatis.session.SqlSession;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtCharacteristic;
@@ -38,12 +42,6 @@ import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonar.server.util.Validation;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Date;
import java.util.List;

@ServerSide
public class DebtModelOperations {

@@ -150,7 +148,7 @@ public class DebtModelOperations {
}
}

private int getOrder(CharacteristicDto characteristicDto) {
private static int getOrder(CharacteristicDto characteristicDto) {
Integer order = characteristicDto.getOrder();
if (order == null) {
throw new IllegalArgumentException(String.format("The order of the characteristic '%s' should not be null", characteristicDto.getKey()));

+ 18
- 20
server/sonar-server/src/main/java/org/sonar/server/debt/DebtModelXMLExporter.java View File

@@ -24,14 +24,13 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.debt.DebtCharacteristic;
import org.sonar.api.server.debt.internal.DefaultDebtCharacteristic;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.xml.transform.OutputKeys;
@@ -41,14 +40,13 @@ import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtCharacteristic;
import org.sonar.api.server.debt.internal.DefaultDebtCharacteristic;
import org.xml.sax.InputSource;

import static com.google.common.collect.Lists.newArrayList;

@@ -147,7 +145,7 @@ public class DebtModelXMLExporter {
return result;
}

private void processProperty(String key, @Nullable String val, String text, StringBuilder xml) {
private static void processProperty(String key, @Nullable String val, String text, StringBuilder xml) {
xml.append("<" + PROPERTY + "><" + PROPERTY_KEY + ">");
xml.append(StringEscapeUtils.escapeXml(key));
xml.append("</" + PROPERTY_KEY + ">");
@@ -164,7 +162,7 @@ public class DebtModelXMLExporter {
xml.append("</" + PROPERTY + ">");
}

private String prettyFormatXml(String xml) {
private static String prettyFormatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
@@ -240,7 +238,7 @@ public class DebtModelXMLExporter {
});
}

private List<DebtCharacteristic> sortByOrder(List<DebtCharacteristic> characteristics) {
private static List<DebtCharacteristic> sortByOrder(List<DebtCharacteristic> characteristics) {
Collections.sort(characteristics, new Ordering<DebtCharacteristic>() {
@Override
public int compare(@Nullable DebtCharacteristic left, @Nullable DebtCharacteristic right) {
@@ -253,7 +251,7 @@ public class DebtModelXMLExporter {
return characteristics;
}

private List<DebtCharacteristic> sortByName(List<DebtCharacteristic> characteristics) {
private static List<DebtCharacteristic> sortByName(List<DebtCharacteristic> characteristics) {
Collections.sort(characteristics, new Ordering<DebtCharacteristic>() {
@Override
public int compare(@Nullable DebtCharacteristic left, @Nullable DebtCharacteristic right) {

+ 11
- 13
server/sonar-server/src/main/java/org/sonar/server/debt/DebtRulesXMLImporter.java View File

@@ -23,28 +23,26 @@ package org.sonar.server.debt;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.server.debt.DebtModelXMLExporter.RuleDebt;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

import java.io.Reader;
import java.io.StringReader;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static org.sonar.server.debt.DebtModelXMLExporter.CHARACTERISTIC;
import static org.sonar.server.debt.DebtModelXMLExporter.CHARACTERISTIC_KEY;
@@ -88,7 +86,7 @@ public class DebtRulesXMLImporter {
return ruleDebts;
}

private SMInputFactory initStax() {
private static SMInputFactory initStax() {
XMLInputFactory xmlFactory = XMLInputFactory2.newInstance();
xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
@@ -141,7 +139,7 @@ public class DebtRulesXMLImporter {
return null;
}

private Property processProperty(ValidationMessages validationMessages, SMInputCursor cursor) throws XMLStreamException {
private static Property processProperty(ValidationMessages validationMessages, SMInputCursor cursor) throws XMLStreamException {
SMInputCursor c = cursor.childElementCursor();
String key = null;
int value = 0;
@@ -183,7 +181,7 @@ public class DebtRulesXMLImporter {
}

@CheckForNull
private RuleDebt createRuleDebt(RuleKey ruleKey, String function, @Nullable String coefficient, @Nullable String offset, ValidationMessages validationMessages) {
private static RuleDebt createRuleDebt(RuleKey ruleKey, String function, @Nullable String coefficient, @Nullable String offset, ValidationMessages validationMessages) {
if ("linear_threshold".equals(function) && coefficient != null) {
validationMessages.addWarningText(String.format("Linear with threshold function is no longer used, remediation function of '%s' is replaced by linear.", ruleKey));
return new RuleDebt().setRuleKey(ruleKey).setFunction(DebtRemediationFunction.Type.LINEAR.name()).setCoefficient(coefficient);

+ 6
- 8
server/sonar-server/src/main/java/org/sonar/server/duplication/ws/DuplicationsJsonWriter.java View File

@@ -21,17 +21,15 @@
package org.sonar.server.duplication.ws;

import com.google.common.annotations.VisibleForTesting;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.server.component.db.ComponentDao;

import javax.annotation.Nullable;

import java.util.List;
import java.util.Map;

import static com.google.common.collect.Maps.newHashMap;

@ServerSide
@@ -65,7 +63,7 @@ public class DuplicationsJsonWriter {
}
}

private void writeDuplication(Map<String, String> refByComponentKey, DuplicationsParser.Duplication duplication, JsonWriter json) {
private static void writeDuplication(Map<String, String> refByComponentKey, DuplicationsParser.Duplication duplication, JsonWriter json) {
String ref = null;
ComponentDto componentDto = duplication.file();
if (componentDto != null) {
@@ -104,13 +102,13 @@ public class DuplicationsJsonWriter {
}
}

private void addFile(JsonWriter json, ComponentDto file) {
private static void addFile(JsonWriter json, ComponentDto file) {
json.prop("key", file.key());
json.prop("uuid", file.uuid());
json.prop("name", file.longName());
}

private void addProject(JsonWriter json, @Nullable ComponentDto project, @Nullable ComponentDto subProject) {
private static void addProject(JsonWriter json, @Nullable ComponentDto project, @Nullable ComponentDto subProject) {
if (project != null) {
json.prop("project", project.key());
json.prop("projectUuid", project.uuid());

+ 3
- 4
server/sonar-server/src/main/java/org/sonar/server/es/request/ProxySearchRequestBuilder.java View File

@@ -20,6 +20,8 @@

package org.sonar.server.es.request;

import java.io.IOException;
import java.util.Arrays;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
@@ -31,9 +33,6 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.sonar.api.utils.log.Profiler;
import org.sonar.server.es.EsClient;

import java.io.IOException;
import java.util.Arrays;

public class ProxySearchRequestBuilder extends SearchRequestBuilder {

public ProxySearchRequestBuilder(Client client) {
@@ -82,7 +81,7 @@ public class ProxySearchRequestBuilder extends SearchRequestBuilder {
return message.toString();
}

private String xContentToString(ToXContent toXContent) {
private static String xContentToString(ToXContent toXContent) {
try {
XContentBuilder builder = XContentFactory.jsonBuilder();
toXContent.toXContent(builder, ToXContent.EMPTY_PARAMS);

+ 4
- 5
server/sonar-server/src/main/java/org/sonar/server/issue/CommentAction.java View File

@@ -21,15 +21,14 @@
package org.sonar.server.issue;

import com.google.common.base.Strings;
import org.sonar.api.server.ServerSide;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.IssueUpdater;
import org.sonar.server.user.UserSession;

import java.util.Collection;
import java.util.Map;

@ServerSide
public class CommentAction extends Action {

@@ -55,7 +54,7 @@ public class CommentAction extends Action {
return true;
}

private String comment(Map<String, Object> properties) {
private static String comment(Map<String, Object> properties) {
String param = (String) properties.get(COMMENT_PROPERTY);
if (Strings.isNullOrEmpty(param)) {
throw new IllegalArgumentException("Missing parameter : '" + COMMENT_PROPERTY + "'");

+ 14
- 16
server/sonar-server/src/main/java/org/sonar/server/issue/InternalRubyIssueService.java View File

@@ -26,8 +26,13 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.issue.ActionPlan;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.IssueComment;
@@ -36,6 +41,7 @@ import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.DefaultIssueComment;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.SonarException;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.ActionPlanStats;
@@ -55,14 +61,6 @@ import org.sonar.server.user.UserSession;
import org.sonar.server.util.RubyUtils;
import org.sonar.server.util.Validation;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -385,7 +383,7 @@ public class InternalRubyIssueService {
}
}

private Date checkAndReturnDeadline(String deadLineParam, Result<ActionPlan> result) {
private static Date checkAndReturnDeadline(String deadLineParam, Result<ActionPlan> result) {
Date deadLine = null;
if (!Strings.isNullOrEmpty(deadLineParam)) {
try {
@@ -492,7 +490,7 @@ public class InternalRubyIssueService {
return execute(props);
}

private void overrideProps(Map<String, Object> props, Map<String, Object> overrideProps) {
private static void overrideProps(Map<String, Object> props, Map<String, Object> overrideProps) {
for (Map.Entry<String, Object> entry : overrideProps.entrySet()) {
props.put(entry.getKey(), entry.getValue());
}
@@ -609,32 +607,32 @@ public class InternalRubyIssueService {
return issueBulkChangeService.execute(issueBulkChangeQuery, userSession);
}

private void checkMandatoryParameter(String value, String paramName, Result result) {
private static void checkMandatoryParameter(String value, String paramName, Result result) {
if (Strings.isNullOrEmpty(value)) {
result.addError(Result.Message.ofL10n(Validation.CANT_BE_EMPTY_MESSAGE, paramName));
}
}

private void checkMandatorySizeParameter(String value, String paramName, Integer size, Result result) {
private static void checkMandatorySizeParameter(String value, String paramName, Integer size, Result result) {
checkMandatoryParameter(value, paramName, result);
if (!Strings.isNullOrEmpty(value) && value.length() > size) {
result.addError(Result.Message.ofL10n(Validation.IS_TOO_LONG_MESSAGE, paramName, size));
}
}

private void checkOptionalSizeParameter(String value, String paramName, Integer size, Result result) {
private static void checkOptionalSizeParameter(String value, String paramName, Integer size, Result result) {
if (!Strings.isNullOrEmpty(value) && value.length() > size) {
result.addError(Result.Message.ofL10n(Validation.IS_TOO_LONG_MESSAGE, paramName, size));
}
}

private void checkOptionalSizeParameter(String value, String paramName, Integer size) {
private static void checkOptionalSizeParameter(String value, String paramName, Integer size) {
if (!Strings.isNullOrEmpty(value) && value.length() > size) {
throw new BadRequestException(Validation.IS_TOO_LONG_MESSAGE, paramName, size);
}
}

public int maxPageSize() {
public static int maxPageSize() {
return QueryContext.MAX_LIMIT;
}


+ 11
- 13
server/sonar-server/src/main/java/org/sonar/server/issue/IssueBulkChangeService.java View File

@@ -25,10 +25,18 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.IssueChangeContext;
import org.sonar.core.notification.NotificationManager;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import org.sonar.api.utils.log.Logger;
@@ -36,6 +44,7 @@ import org.sonar.api.utils.log.Loggers;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.issue.db.IssueDto;
import org.sonar.core.issue.db.IssueStorage;
import org.sonar.core.notification.NotificationManager;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.persistence.MyBatis;
import org.sonar.server.db.DbClient;
@@ -46,17 +55,6 @@ import org.sonar.server.issue.notification.IssueChangeNotification;
import org.sonar.server.rule.DefaultRuleFinder;
import org.sonar.server.user.UserSession;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
@@ -167,7 +165,7 @@ public class IssueBulkChangeService {
return bulkActions;
}

private void applyAction(Action action, ActionContext actionContext, IssueBulkChangeQuery issueBulkChangeQuery, IssueBulkChangeResult result) {
private static void applyAction(Action action, ActionContext actionContext, IssueBulkChangeQuery issueBulkChangeQuery, IssueBulkChangeResult result) {
Issue issue = actionContext.issue();
try {
if (action.supports(issue) && action.execute(issueBulkChangeQuery.properties(action.key()), actionContext)) {

+ 3
- 5
server/sonar-server/src/main/java/org/sonar/server/issue/SetSeverityAction.java View File

@@ -20,20 +20,18 @@

package org.sonar.server.issue;

import com.google.common.base.Strings;
import java.util.Collection;
import java.util.Map;

import org.sonar.api.server.ServerSide;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.condition.Condition;
import org.sonar.api.issue.condition.IsUnResolved;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.server.ServerSide;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.IssueUpdater;
import org.sonar.server.user.UserSession;

import com.google.common.base.Strings;

@ServerSide
public class SetSeverityAction extends Action {

@@ -69,7 +67,7 @@ public class SetSeverityAction extends Action {
return issueUpdater.setManualSeverity((DefaultIssue) context.issue(), severity(properties), context.issueChangeContext());
}

private String severity(Map<String, Object> properties) {
private static String severity(Map<String, Object> properties) {
String param = (String) properties.get("severity");
if (Strings.isNullOrEmpty(param)) {
throw new IllegalArgumentException("Missing parameter : 'severity'");

+ 5
- 7
server/sonar-server/src/main/java/org/sonar/server/issue/TransitionAction.java View File

@@ -20,21 +20,19 @@

package org.sonar.server.issue;

import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.workflow.IssueWorkflow;
import org.sonar.core.issue.workflow.Transition;
import org.sonar.server.user.UserSession;

import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;

@ServerSide
public class TransitionAction extends Action {

@@ -77,7 +75,7 @@ public class TransitionAction extends Action {
}, null) != null;
}

private String transition(Map<String, Object> properties) {
private static String transition(Map<String, Object> properties) {
String param = (String) properties.get("transition");
if (Strings.isNullOrEmpty(param)) {
throw new IllegalArgumentException("Missing parameter : 'transition'");

+ 8
- 10
server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanService.java View File

@@ -22,10 +22,15 @@ package org.sonar.server.issue.actionplan;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import org.sonar.api.server.ServerSide;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.api.issue.ActionPlan;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.IssueChangeContext;
import org.sonar.api.server.ServerSide;
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.ActionPlanDeadlineComparator;
import org.sonar.core.issue.ActionPlanStats;
@@ -45,13 +50,6 @@ import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;

import javax.annotation.CheckForNull;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -205,11 +203,11 @@ public class ActionPlanService {
return resourceDto;
}

private void checkUserCanAccessProject(String projectKey, UserSession userSession) {
private static void checkUserCanAccessProject(String projectKey, UserSession userSession) {
userSession.checkProjectPermission(UserRole.USER, projectKey);
}

private void checkUserIsProjectAdministrator(String projectKey, UserSession userSession) {
private static void checkUserIsProjectAdministrator(String projectKey, UserSession userSession) {
userSession.checkProjectPermission(UserRole.ADMIN, projectKey);
}


+ 7
- 7
server/sonar-server/src/main/java/org/sonar/server/issue/actionplan/ActionPlanWs.java View File

@@ -41,17 +41,17 @@ public class ActionPlanWs implements WebService {
controller.done();
}

private void defineSearchAction(NewController controller) {
private static void defineSearchAction(NewController controller) {
WebService.NewAction action = controller.createAction("search")
.setDescription("Get a list of action plans. Requires Browse permission on project")
.setSince("3.6")
.setHandler(RailsHandler.INSTANCE)
.setResponseExample(Resources.getResource(this.getClass(), "example-search.json"));
.setResponseExample(Resources.getResource(ActionPlanWs.class, "example-search.json"));
addProjectParam(action);
addFormatParam(action);
}

private void defineCreateAction(NewController controller) {
private static void defineCreateAction(NewController controller) {
WebService.NewAction action = controller.createAction("create")
.setDescription("Create an action plan. Requires Administer permission on project")
.setSince("3.6")
@@ -64,7 +64,7 @@ public class ActionPlanWs implements WebService {
addFormatParam(action);
}

private void defineUpdateAction(NewController controller) {
private static void defineUpdateAction(NewController controller) {
WebService.NewAction action = controller.createAction("update")
.setDescription("Update an action plan. Requires Administer permission on project")
.setSince("3.6")
@@ -77,7 +77,7 @@ public class ActionPlanWs implements WebService {
addFormatParam(action);
}

private void defineDeleteAction(NewController controller) {
private static void defineDeleteAction(NewController controller) {
WebService.NewAction action = controller.createAction("delete")
.setDescription("Delete an action plan. Requires Administer permission on project")
.setSince("3.6")
@@ -87,7 +87,7 @@ public class ActionPlanWs implements WebService {
addFormatParam(action);
}

private void defineOpenAction(NewController controller) {
private static void defineOpenAction(NewController controller) {
WebService.NewAction action = controller.createAction("open")
.setDescription("Open an action plan. Requires Administer permission on project")
.setSince("3.6")
@@ -97,7 +97,7 @@ public class ActionPlanWs implements WebService {
addFormatParam(action);
}

private void defineCloseAction(NewController controller) {
private static void defineCloseAction(NewController controller) {
WebService.NewAction action = controller.createAction("close")
.setDescription("Close an action plan. Requires Administer permission on project")
.setSince("3.6")

+ 14
- 14
server/sonar-server/src/main/java/org/sonar/server/issue/ws/IssuesWs.java View File

@@ -75,12 +75,12 @@ public class IssuesWs implements WebService {
defineBulkChangeAction(controller);
}

private void defineChangelogAction(NewController controller) {
private static void defineChangelogAction(NewController controller) {
WebService.NewAction action = controller.createAction(CHANGELOG_ACTION)
.setDescription("Display changelog of an issue")
.setSince("4.1")
.setHandler(RailsHandler.INSTANCE)
.setResponseExample(Resources.getResource(this.getClass(), "example-changelog.json"));
.setResponseExample(Resources.getResource(IssuesWs.class, "example-changelog.json"));

action.createParam("issue")
.setDescription("Key of the issue")
@@ -89,7 +89,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineAssignAction(NewController controller) {
private static void defineAssignAction(NewController controller) {
WebService.NewAction action = controller.createAction(ASSIGN_ACTION)
.setDescription("Assign/Unassign an issue. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -106,7 +106,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineAddCommentAction(NewController controller) {
private static void defineAddCommentAction(NewController controller) {
WebService.NewAction action = controller.createAction(ADD_COMMENT_ACTION)
.setDescription("Add a comment. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -123,7 +123,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineDeleteCommentAction(NewController controller) {
private static void defineDeleteCommentAction(NewController controller) {
WebService.NewAction action = controller.createAction(DELETE_COMMENT_ACTION)
.setDescription("Delete a comment. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -136,7 +136,7 @@ public class IssuesWs implements WebService {
.setExampleValue("392160d3-a4f2-4c52-a565-e4542cfa2096");
}

private void defineEditCommentAction(NewController controller) {
private static void defineEditCommentAction(NewController controller) {
WebService.NewAction action = controller.createAction(EDIT_COMMENT_ACTION)
.setDescription("Edit a comment. Requires authentication and User role on project")
.setSince("3.6")
@@ -153,7 +153,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineSetSeverityAction(NewController controller) {
private static void defineSetSeverityAction(NewController controller) {
WebService.NewAction action = controller.createAction(SET_SEVERITY_ACTION)
.setDescription("Change severity. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -171,7 +171,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void definePlanAction(NewController controller) {
private static void definePlanAction(NewController controller) {
WebService.NewAction action = controller.createAction(PLAN_ACTION)
.setDescription("Plan/Unplan an issue. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -188,7 +188,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineDoTransitionAction(NewController controller) {
private static void defineDoTransitionAction(NewController controller) {
WebService.NewAction action = controller.createAction(DO_TRANSITION_ACTION)
.setDescription("Do workflow transition on an issue. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -206,12 +206,12 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineTransitionsAction(NewController controller) {
private static void defineTransitionsAction(NewController controller) {
WebService.NewAction action = controller.createAction(TRANSITIONS_ACTION)
.setDescription("Get Possible Workflow Transitions for an Issue. Requires Browse permission on project")
.setSince("3.6")
.setHandler(RailsHandler.INSTANCE)
.setResponseExample(Resources.getResource(this.getClass(), "example-transitions.json"));
.setResponseExample(Resources.getResource(IssuesWs.class, "example-transitions.json"));

action.createParam("issue")
.setDescription("Key of the issue")
@@ -219,7 +219,7 @@ public class IssuesWs implements WebService {
.setExampleValue("5bccd6e8-f525-43a2-8d76-fcb13dde79ef");
}

private void defineCreateAction(NewController controller) {
private static void defineCreateAction(NewController controller) {
WebService.NewAction action = controller.createAction(CREATE_ACTION)
.setDescription("Create a manual issue. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -248,7 +248,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineDoActionAction(NewController controller) {
private static void defineDoActionAction(NewController controller) {
WebService.NewAction action = controller.createAction(DO_ACTION_ACTION)
.setDescription("Do workflow transition on an issue. Requires authentication and Browse permission on project")
.setSince("3.6")
@@ -265,7 +265,7 @@ public class IssuesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineBulkChangeAction(NewController controller) {
private static void defineBulkChangeAction(NewController controller) {
WebService.NewAction action = controller.createAction(BULK_CHANGE_ACTION)
.setDescription("Bulk change on issues. Requires authentication and User role on project(s)")
.setSince("3.7")

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/issue/ws/SearchAction.java View File

@@ -684,7 +684,7 @@ public class SearchAction implements IssuesWsAction {
json.endArray();
}

private void writeUsers(JsonWriter json, Map<String, User> usersByLogin) {
private static void writeUsers(JsonWriter json, Map<String, User> usersByLogin) {
json.name("users").beginArray();
for (User user : usersByLogin.values()) {
json.beginObject()

+ 9
- 11
server/sonar-server/src/main/java/org/sonar/server/measure/MeasureFilterSql.java View File

@@ -23,16 +23,6 @@ import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.core.component.SnapshotDto;
import org.sonar.core.persistence.Database;
import org.sonar.core.persistence.dialect.MsSql;
import org.sonar.core.persistence.dialect.Oracle;

import javax.annotation.Nullable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -40,6 +30,14 @@ import java.sql.SQLException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.core.component.SnapshotDto;
import org.sonar.core.persistence.Database;
import org.sonar.core.persistence.dialect.MsSql;
import org.sonar.core.persistence.dialect.Oracle;

class MeasureFilterSql {

@@ -257,7 +255,7 @@ class MeasureFilterSql {
/**
* Replace escape percent and underscore by adding a slash just before
*/
private String escapePercentAndUnderscrore(String value) {
private static String escapePercentAndUnderscrore(String value) {
return value.replaceAll("%", "\\\\%").replaceAll("_", "\\\\_");
}


+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/measure/ws/ManualMeasuresWs.java View File

@@ -36,7 +36,7 @@ public class ManualMeasuresWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.10")

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/metric/ws/CreateAction.java View File

@@ -116,7 +116,7 @@ public class CreateAction implements MetricsWsAction {
}
}

private MetricDto newMetricTemplate(Request request) {
private static MetricDto newMetricTemplate(Request request) {
String key = request.mandatoryParam(PARAM_KEY);
String name = request.mandatoryParam(PARAM_NAME);
String type = Metric.ValueType.valueOf(request.mandatoryParam(PARAM_TYPE)).name();

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/metric/ws/MetricsWs.java View File

@@ -47,7 +47,7 @@ public class MetricsWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.6")

+ 6
- 8
server/sonar-server/src/main/java/org/sonar/server/permission/InternalPermissionService.java View File

@@ -20,8 +20,12 @@

package org.sonar.server.permission;

import org.sonar.api.server.ServerSide;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.server.ServerSide;
import org.sonar.api.web.UserRole;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.permission.GlobalPermissions;
@@ -36,12 +40,6 @@ import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.issue.index.IssueAuthorizationIndexer;
import org.sonar.server.user.UserSession;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.List;
import java.util.Map;

/**
* Used by ruby code <pre>Internal.permissions</pre>
*/
@@ -261,7 +259,7 @@ public class InternalPermissionService {
}
}

private Object badRequestIfNullResult(@Nullable Object component, String objectType, String objectKey) {
private static Object badRequestIfNullResult(@Nullable Object component, String objectType, String objectKey) {
if (component == null) {
throw new BadRequestException(String.format(NOT_FOUND_FORMAT, objectType, objectKey));
}

+ 9
- 11
server/sonar-server/src/main/java/org/sonar/server/permission/PermissionFinder.java View File

@@ -21,9 +21,12 @@ package org.sonar.server.permission;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.Paging;
import org.sonar.core.permission.GroupWithPermission;
import org.sonar.core.permission.GroupWithPermissionDto;
@@ -38,11 +41,6 @@ import org.sonar.core.resource.ResourceDto;
import org.sonar.core.resource.ResourceQuery;
import org.sonar.server.exceptions.NotFoundException;

import javax.annotation.Nullable;

import java.util.Collection;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

@ServerSide
@@ -97,7 +95,7 @@ public class PermissionFinder {
return new UserWithPermissionQueryResult(toUserWithPermissionList(dtos), hasMoreResults);
}

private List<UserWithPermission> toUserWithPermissionList(List<UserWithPermissionDto> dtos) {
private static List<UserWithPermission> toUserWithPermissionList(List<UserWithPermissionDto> dtos) {
List<UserWithPermission> users = newArrayList();
for (UserWithPermissionDto dto : dtos) {
users.add(dto.toUserWithPermission());
@@ -106,7 +104,7 @@ public class PermissionFinder {
}

@Nullable
private Long componentId(String componentKey) {
private Long componentId(@Nullable String componentKey) {
if (componentKey == null) {
return null;
} else {
@@ -135,13 +133,13 @@ public class PermissionFinder {
return dto.getId();
}

private int offset(PermissionQuery query) {
private static int offset(PermissionQuery query) {
int pageSize = query.pageSize();
int pageIndex = query.pageIndex();
return (pageIndex - 1) * pageSize;
}

private int limit(PermissionQuery query) {
private static int limit(PermissionQuery query) {
// Add one to page size in order to be able to know if there's more results or not
return query.pageSize() + 1;
}
@@ -176,7 +174,7 @@ public class PermissionFinder {
}
}

private List<GroupWithPermission> pagedGroups(Collection<GroupWithPermissionDto> dtos, Paging paging) {
private static List<GroupWithPermission> pagedGroups(Collection<GroupWithPermissionDto> dtos, Paging paging) {
List<GroupWithPermission> groups = newArrayList();
int index = 0;
for (GroupWithPermissionDto dto : dtos) {

+ 2
- 2
server/sonar-server/src/main/java/org/sonar/server/permission/ws/PermissionsWs.java View File

@@ -41,7 +41,7 @@ public class PermissionsWs implements WebService {
controller.done();
}

private void defineAddAction(NewController controller) {
private static void defineAddAction(NewController controller) {
NewAction action = controller.createAction("add")
.setDescription("Add a global or a project permission. Requires Administer System permission for global permissions, " +
"requires Administer permission on project for project permissions")
@@ -65,7 +65,7 @@ public class PermissionsWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineRemoveAction(NewController controller) {
private static void defineRemoveAction(NewController controller) {
NewAction action = controller.createAction("remove")
.setDescription("Remove a global or a project permission. Requires Administer System permission for global permissions, " +
"requires Administer permission on project for project permissions")

+ 4
- 5
server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java View File

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

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.sonar.api.server.ServerSide;
@@ -32,9 +34,6 @@ import org.sonar.server.search.IndexDefinition;
import org.sonar.server.source.index.SourceLineIndexDefinition;
import org.sonar.server.view.index.ViewIndexDefinition;

import java.sql.Connection;
import java.sql.SQLException;

@ServerSide
public class BackendCleanup {

@@ -138,7 +137,7 @@ public class BackendCleanup {
}
}

private void deleteWhereResourceIdNotNull(String tableName, Connection connection) {
private static void deleteWhereResourceIdNotNull(String tableName, Connection connection) {
try {
connection.prepareStatement("DELETE FROM " + tableName + " WHERE resource_id IS NOT NULL").execute();
// commit is useless on some databases
@@ -148,7 +147,7 @@ public class BackendCleanup {
}
}

private void deleteManualRules(Connection connection) {
private static void deleteManualRules(Connection connection) {
try {
connection.prepareStatement("DELETE FROM rules WHERE rules.plugin_name='manual'").execute();
// commit is useless on some databases

+ 3
- 5
server/sonar-server/src/main/java/org/sonar/server/qualitygate/ws/ShowAction.java View File

@@ -21,6 +21,8 @@
package org.sonar.server.qualitygate.ws;

import com.google.common.io.Resources;
import java.util.Collection;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
@@ -30,10 +32,6 @@ import org.sonar.core.qualitygate.db.QualityGateDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.qualitygate.QualityGates;

import javax.annotation.Nullable;

import java.util.Collection;

public class ShowAction implements QGateWsAction {

private final QualityGates qualityGates;
@@ -82,7 +80,7 @@ public class ShowAction implements QGateWsAction {
writer.endObject().close();
}

private void checkOneOfIdOrNamePresent(@Nullable Long qGateId, @Nullable String qGateName) {
private static void checkOneOfIdOrNamePresent(@Nullable Long qGateId, @Nullable String qGateName) {
if (qGateId == null && qGateName == null) {
throw new BadRequestException("Either one of 'id' or 'name' is required.");
} else if (qGateId != null && qGateName != null) {

+ 13
- 15
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackuper.java View File

@@ -23,14 +23,25 @@ import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.Reader;
import java.io.Writer;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.text.XmlWriter;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.qualityprofile.db.QualityProfileDto;
@@ -38,19 +49,6 @@ import org.sonar.server.db.DbClient;
import org.sonar.server.qualityprofile.index.ActiveRuleIndex;
import org.sonar.server.search.IndexClient;

import javax.annotation.Nullable;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

import java.io.Reader;
import java.io.Writer;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@ServerSide
public class QProfileBackuper {

@@ -79,7 +77,7 @@ public class QProfileBackuper {
writeXml(writer, profile, activeRules.iterator());
}

private void writeXml(Writer writer, QualityProfileDto profile, Iterator<ActiveRule> activeRules) {
private static void writeXml(Writer writer, QualityProfileDto profile, Iterator<ActiveRule> activeRules) {
XmlWriter xml = XmlWriter.of(writer).declaration();
xml.begin("profile");
xml.prop("name", profile.getName());

+ 14
- 15
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporters.java View File

@@ -19,9 +19,19 @@
*/
package org.sonar.server.qualityprofile;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
@@ -29,24 +39,13 @@ import org.sonar.api.rules.ActiveRuleParam;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.qualityprofile.db.QualityProfileDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@ServerSide
public class QProfileExporters {

@@ -169,7 +168,7 @@ public class QProfileExporters {
throw new BadRequestException("No such importer : " + importerKey);
}

private void processValidationMessages(ValidationMessages messages, QProfileResult result) {
private static void processValidationMessages(ValidationMessages messages, QProfileResult result) {
if (!messages.getErrors().isEmpty()) {
throw new BadRequestException(messages);
}
@@ -177,7 +176,7 @@ public class QProfileExporters {
result.addInfos(messages.getInfos());
}

private RuleActivation toRuleActivation(org.sonar.api.rules.ActiveRule activeRule) {
private static RuleActivation toRuleActivation(org.sonar.api.rules.ActiveRule activeRule) {
RuleActivation ruleActivation = new RuleActivation(activeRule.getRule().ruleKey());
ruleActivation.setSeverity(activeRule.getSeverity().name());
for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {

+ 2
- 2
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileProjectOperations.java View File

@@ -122,11 +122,11 @@ public class QProfileProjectOperations {
return qualityProfile;
}

private void checkPermission(UserSession userSession) {
private static void checkPermission(UserSession userSession) {
userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
}

private void checkPermission(UserSession userSession, String projectKey) {
private static void checkPermission(UserSession userSession, String projectKey) {
if (!userSession.hasGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN) && !userSession.hasProjectPermission(UserRole.ADMIN, projectKey)) {
throw new ForbiddenException("Insufficient privileges");
}

+ 3
- 6
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java View File

@@ -20,18 +20,15 @@

package org.sonar.server.qualityprofile;

import com.google.common.base.Strings;
import java.util.List;

import javax.annotation.CheckForNull;

import org.sonar.api.server.ServerSide;
import org.sonar.api.component.Component;
import org.sonar.api.server.ServerSide;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.user.UserSession;
import org.sonar.server.util.Validation;

import com.google.common.base.Strings;

/**
* Use {@link org.sonar.server.qualityprofile.QProfileService} instead
*/
@@ -121,7 +118,7 @@ public class QProfiles {
projectOperations.removeAllProjects(profileKey, userSession);
}

private void checkProfileNameParam(String name) {
private static void checkProfileNameParam(String name) {
if (Strings.isNullOrEmpty(name)) {
throw new BadRequestException("quality_profiles.please_type_profile_name");
}

+ 8
- 8
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ProfilesWs.java View File

@@ -44,12 +44,12 @@ public class ProfilesWs implements WebService {
controller.done();
}

private void defineListAction(NewController controller) {
private static void defineListAction(NewController controller) {
WebService.NewAction action = controller.createAction("list")
.setDescription("Get a list of profiles")
.setSince("3.3")
.setHandler(RailsHandler.INSTANCE)
.setResponseExample(Resources.getResource(this.getClass(), "example-list.json"));
.setResponseExample(Resources.getResource(ProfilesWs.class, "example-list.json"));

action.createParam("language")
.setDescription("Profile language")
@@ -60,12 +60,12 @@ public class ProfilesWs implements WebService {
RailsHandler.addJsonOnlyFormatParam(action);
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
WebService.NewAction action = controller.createAction("index")
.setDescription("Get a profile")
.setSince("3.3")
.setHandler(RailsHandler.INSTANCE)
.setResponseExample(Resources.getResource(this.getClass(), "example-index.json"));
.setResponseExample(Resources.getResource(ProfilesWs.class, "example-index.json"));

action.createParam("language")
.setDescription("Profile language")
@@ -77,7 +77,7 @@ public class ProfilesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineBackupAction(NewController controller) {
private static void defineBackupAction(NewController controller) {
WebService.NewAction action = controller.createAction("backup")
.setDescription("Backup a quality profile. Requires Administer Quality Profiles permission")
.setSince("3.1")
@@ -94,7 +94,7 @@ public class ProfilesWs implements WebService {
RailsHandler.addFormatParam(action);
}

private void defineRestoreAction(NewController controller) {
private static void defineRestoreAction(NewController controller) {
WebService.NewAction action = controller.createAction("restore")
.setDescription("Restore a quality profile backup. Requires Administer Quality Profiles permission")
.setSince("3.1")
@@ -107,7 +107,7 @@ public class ProfilesWs implements WebService {
RailsHandler.addJsonOnlyFormatParam(action);
}

private void defineDestroyAction(NewController controller) {
private static void defineDestroyAction(NewController controller) {
WebService.NewAction action = controller.createAction("destroy")
.setDescription("Delete a quality profile. Requires Administer Quality Profiles permission")
.setSince("3.3")
@@ -124,7 +124,7 @@ public class ProfilesWs implements WebService {
.setExampleValue("Sonar way");
}

private void defineSetAsDefaultAction(NewController controller) {
private static void defineSetAsDefaultAction(NewController controller) {
WebService.NewAction action = controller.createAction("set_as_default")
.setDescription("Set a quality profile as Default. Requires Administer Quality Profiles permission")
.setSince("3.3")

+ 7
- 9
server/sonar-server/src/main/java/org/sonar/server/rule/DeprecatedRulesDefinitionLoader.java View File

@@ -21,13 +21,18 @@ package org.sonar.server.rule;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.io.Reader;
import java.util.Collection;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleParam;
import org.sonar.api.rules.RuleRepository;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.server.rule.RulesDefinition;
@@ -40,13 +45,6 @@ import org.sonar.server.debt.DebtModelXMLExporter;
import org.sonar.server.debt.DebtModelXMLExporter.RuleDebt;
import org.sonar.server.debt.DebtRulesXMLImporter;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.io.Reader;
import java.util.Collection;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -124,7 +122,7 @@ public class DeprecatedRulesDefinitionLoader {
}
}

private DebtRemediationFunction remediationFunction(DebtRemediationFunction.Type function, @Nullable String coefficient, @Nullable String offset,
private static DebtRemediationFunction remediationFunction(DebtRemediationFunction.Type function, @Nullable String coefficient, @Nullable String offset,
RulesDefinition.DebtRemediationFunctions functions, String repoKey, String ruleKey) {
if (DebtRemediationFunction.Type.LINEAR.equals(function) && coefficient != null) {
return functions.linear(coefficient);

+ 9
- 6
server/sonar-server/src/main/java/org/sonar/server/rule/RegisterRules.java View File

@@ -25,6 +25,14 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.picocontainer.Startable;
@@ -49,11 +57,6 @@ import org.sonar.server.db.DbClient;
import org.sonar.server.qualityprofile.RuleActivator;
import org.sonar.server.startup.RegisterDebtModel;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -160,7 +163,7 @@ public class RegisterRules implements Startable {
}

@CheckForNull
private CharacteristicDto characteristic(RulesDefinition.Rule ruleDef, @Nullable Integer overridingCharacteristicId, Map<String, CharacteristicDto> allCharacteristics) {
private static CharacteristicDto characteristic(RulesDefinition.Rule ruleDef, @Nullable Integer overridingCharacteristicId, Map<String, CharacteristicDto> allCharacteristics) {
String subCharacteristic = ruleDef.debtSubCharacteristic();
String repo = ruleDef.repository().key();
String ruleKey = ruleDef.key();

+ 4
- 5
server/sonar-server/src/main/java/org/sonar/server/rule/RuleOperations.java View File

@@ -21,9 +21,11 @@
package org.sonar.server.rule;

import com.google.common.base.Strings;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.core.permission.GlobalPermissions;
@@ -36,9 +38,6 @@ import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

/**
* @deprecated to be dropped in 4.4
*/
@@ -151,7 +150,7 @@ public class RuleOperations {
.isEquals();
}

private void checkPermission(UserSession userSession) {
private static void checkPermission(UserSession userSession) {
userSession.checkLoggedIn();
userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
}

+ 12
- 13
server/sonar-server/src/main/java/org/sonar/server/rule/RuleUpdater.java View File

@@ -22,12 +22,16 @@ package org.sonar.server.rule;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.sonar.api.server.ServerSide;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ServerSide;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.utils.System2;
import org.sonar.core.persistence.DbSession;
@@ -39,11 +43,6 @@ import org.sonar.core.technicaldebt.db.CharacteristicDto;
import org.sonar.server.db.DbClient;
import org.sonar.server.user.UserSession;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;

@ServerSide
@@ -141,7 +140,7 @@ public class RuleUpdater {
}
}

private void updateName(RuleUpdate update, Context context) {
private static void updateName(RuleUpdate update, Context context) {
String name = update.getName();
if (Strings.isNullOrEmpty(name)) {
throw new IllegalArgumentException("The name is missing");
@@ -150,7 +149,7 @@ public class RuleUpdater {
}
}

private void updateDescription(RuleUpdate update, Context context) {
private static void updateDescription(RuleUpdate update, Context context) {
String description = update.getMarkdownDescription();
if (Strings.isNullOrEmpty(description)) {
throw new IllegalArgumentException("The description is missing");
@@ -159,7 +158,7 @@ public class RuleUpdater {
}
}

private void updateSeverity(RuleUpdate update, Context context) {
private static void updateSeverity(RuleUpdate update, Context context) {
String severity = update.getSeverity();
if (Strings.isNullOrEmpty(severity) || !Severity.ALL.contains(severity)) {
throw new IllegalArgumentException("The severity is invalid");
@@ -168,7 +167,7 @@ public class RuleUpdater {
}
}

private void updateStatus(RuleUpdate update, Context context) {
private static void updateStatus(RuleUpdate update, Context context) {
RuleStatus status = update.getStatus();
if (status == null) {
throw new IllegalArgumentException("The status is missing");
@@ -177,7 +176,7 @@ public class RuleUpdater {
}
}

private void updateTags(RuleUpdate update, Context context) {
private static void updateTags(RuleUpdate update, Context context) {
Set<String> tags = update.getTags();
if (tags == null || tags.isEmpty()) {
context.rule.setTags(Collections.<String>emptySet());
@@ -186,7 +185,7 @@ public class RuleUpdater {
}
}

private void updateDebtSubCharacteristic(RuleUpdate update, Context context) {
private static void updateDebtSubCharacteristic(RuleUpdate update, Context context) {
if (update.getDebtSubCharacteristicKey() == null) {
// set to "none"
Integer id = context.rule.getDefaultSubCharacteristicId() != null ? RuleDto.DISABLED_CHARACTERISTIC_ID : null;
@@ -216,7 +215,7 @@ public class RuleUpdater {
}
}

private void updateDebtRemediationFunction(RuleUpdate update, Context context) {
private static void updateDebtRemediationFunction(RuleUpdate update, Context context) {
Integer subChar = context.rule.getSubCharacteristicId();
boolean noChar =
(context.rule.getDefaultSubCharacteristicId() == null && subChar == null) ||

+ 26
- 9
server/sonar-server/src/main/java/org/sonar/server/search/BaseIndex.java View File

@@ -23,17 +23,40 @@ import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.count.CountRequestBuilder;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.get.*;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequestBuilder;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
@@ -49,12 +72,6 @@ import org.sonar.api.utils.log.Loggers;
import org.sonar.core.persistence.Dto;
import org.sonar.server.exceptions.NotFoundException;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.io.Serializable;
import java.util.*;

/**
* @deprecated replaced by {@link org.sonar.server.es.BaseIndex}
*/
@@ -273,7 +290,7 @@ public abstract class BaseIndex<DOMAIN, DTO extends Dto<KEY>, KEY extends Serial
}
}

private Map mapUuidPathField(IndexField field) {
private static Map mapUuidPathField(IndexField field) {
return ImmutableMap.of(
"type", "string",
"index", "analyzed",

+ 4
- 6
server/sonar-server/src/main/java/org/sonar/server/source/HtmlTextDecorator.java View File

@@ -20,15 +20,13 @@
package org.sonar.server.source;

import com.google.common.io.Closeables;
import org.sonar.api.utils.log.Loggers;

import javax.annotation.Nullable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.utils.log.Loggers;

import static com.google.common.collect.Lists.newArrayList;

@@ -127,11 +125,11 @@ class HtmlTextDecorator {
}
}

private boolean canAddLine(int currentLine, @Nullable Integer from) {
private static boolean canAddLine(int currentLine, @Nullable Integer from) {
return from == null || currentLine >= from;
}

private boolean shouldStop(int currentLine, @Nullable Integer to) {
private static boolean shouldStop(int currentLine, @Nullable Integer to) {
return to != null && to < currentLine;
}


+ 2
- 1
server/sonar-server/src/main/java/org/sonar/server/source/db/FileSourceDao.java View File

@@ -72,8 +72,9 @@ public class FileSourceDao implements DaoComponent {
ResultSet rs = null;
Reader reader = null;
try {
pstmt = connection.prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type = '" + Type.SOURCE +"'");
pstmt = connection.prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type=?");
pstmt.setString(1, fileUuid);
pstmt.setString(2, Type.SOURCE);
rs = pstmt.executeQuery();
if (rs.next()) {
reader = rs.getCharacterStream(1);

+ 4
- 6
server/sonar-server/src/main/java/org/sonar/server/startup/JdbcDriverDeployer.java View File

@@ -19,17 +19,15 @@
*/
package org.sonar.server.startup;

import java.io.File;
import java.io.IOException;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.sonar.api.config.Settings;
import org.sonar.home.cache.FileHashes;
import org.sonar.process.ProcessProperties;
import org.sonar.server.platform.DefaultServerFileSystem;

import javax.annotation.Nullable;

import java.io.File;
import java.io.IOException;

public class JdbcDriverDeployer {

private final DefaultServerFileSystem fileSystem;
@@ -66,7 +64,7 @@ public class JdbcDriverDeployer {
}
}

private String driverIndexContent(@Nullable File deployedDriver) {
private static String driverIndexContent(@Nullable File deployedDriver) {
if (deployedDriver != null) {
String hash = new FileHashes().of(deployedDriver);
return deployedDriver.getName() + "|" + hash;

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java View File

@@ -61,7 +61,7 @@ public final class LogServerId {
}
}

private void addQuotedValue(PropertyDto property, StringBuilder message) {
private static void addQuotedValue(PropertyDto property, StringBuilder message) {
message.append("\"");
message.append(property.getValue());
message.append("\"\n");

+ 2
- 3
server/sonar-server/src/main/java/org/sonar/server/user/GroupMembershipFinder.java View File

@@ -20,6 +20,7 @@

package org.sonar.server.user;

import java.util.List;
import org.sonar.api.server.ServerSide;
import org.sonar.core.user.GroupMembership;
import org.sonar.core.user.GroupMembershipDao;
@@ -29,8 +30,6 @@ import org.sonar.core.user.UserDao;
import org.sonar.core.user.UserDto;
import org.sonar.server.exceptions.NotFoundException;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

@ServerSide
@@ -88,7 +87,7 @@ public class GroupMembershipFinder {
return userDto.getId();
}

private List<GroupMembership> toGroupMembership(List<GroupMembershipDto> dtos) {
private static List<GroupMembership> toGroupMembership(List<GroupMembershipDto> dtos) {
List<GroupMembership> groups = newArrayList();
for (GroupMembershipDto groupMembershipDto : dtos) {
groups.add(groupMembershipDto.toGroupMembership());

+ 2
- 3
server/sonar-server/src/main/java/org/sonar/server/user/GroupMembershipService.java View File

@@ -20,12 +20,11 @@

package org.sonar.server.user;

import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.core.user.GroupMembershipQuery;
import org.sonar.server.util.RubyUtils;

import java.util.Map;

/**
* Used by ruby code <pre>Internal.group_membership</pre>
*/
@@ -55,7 +54,7 @@ public class GroupMembershipService {
return builder.build();
}

private String membership(Map<String, Object> params) {
private static String membership(Map<String, Object> params) {
String selected = (String) params.get("selected");
if (SELECTED_MEMBERSHIP.equals(selected)) {
return GroupMembershipQuery.IN;

+ 3
- 4
server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndexer.java View File

@@ -20,6 +20,8 @@

package org.sonar.server.user.index;

import java.sql.Connection;
import java.util.Iterator;
import org.apache.commons.dbutils.DbUtils;
import org.elasticsearch.action.update.UpdateRequest;
import org.sonar.core.persistence.DbSession;
@@ -28,9 +30,6 @@ import org.sonar.server.es.BaseIndexer;
import org.sonar.server.es.BulkIndexer;
import org.sonar.server.es.EsClient;

import java.sql.Connection;
import java.util.Iterator;

public class UserIndexer extends BaseIndexer {

private final DbClient dbClient;
@@ -71,7 +70,7 @@ public class UserIndexer extends BaseIndexer {
return maxUpdatedAt;
}

private UpdateRequest newUpsertRequest(UserDoc user) {
private static UpdateRequest newUpsertRequest(UserDoc user) {
return new UpdateRequest(UserIndexDefinition.INDEX, UserIndexDefinition.TYPE_USER, user.login())
.doc(user.getFields())
.upsert(user.getFields());

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/user/ws/FavoritesWs.java View File

@@ -36,7 +36,7 @@ public class FavoritesWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.6")

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/user/ws/UpdateAction.java View File

@@ -105,7 +105,7 @@ public class UpdateAction implements UsersWsAction {
json.endObject().close();
}

private void writeUser(JsonWriter json, UserDoc user) {
private static void writeUser(JsonWriter json, UserDoc user) {
json.name("user").beginObject()
.prop("login", user.login())
.prop("name", user.name())

+ 1
- 1
server/sonar-server/src/main/java/org/sonar/server/user/ws/UserPropertiesWs.java View File

@@ -36,7 +36,7 @@ public class UserPropertiesWs implements WebService {
controller.done();
}

private void defineIndexAction(NewController controller) {
private static void defineIndexAction(NewController controller) {
controller.createAction("index")
.setDescription("Documentation of this web service is available <a href=\"http://redirect.sonarsource.com/doc/old-web-service-api.html\">here</a>")
.setSince("2.6")

+ 3
- 4
server/sonar-server/src/main/java/org/sonar/server/view/index/ViewIndexer.java View File

@@ -20,6 +20,8 @@

package org.sonar.server.view.index;

import java.util.List;
import java.util.Map;
import org.elasticsearch.action.update.UpdateRequest;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.component.UuidWithProjectUuidDto;
@@ -30,9 +32,6 @@ import org.sonar.server.es.BulkIndexer;
import org.sonar.server.es.EsClient;
import org.sonar.server.issue.index.IssueIndex;

import java.util.List;
import java.util.Map;

import static com.google.common.collect.Maps.newHashMap;

public class ViewIndexer extends BaseIndexer {
@@ -121,7 +120,7 @@ public class ViewIndexer extends BaseIndexer {
}
}

private UpdateRequest newUpsertRequest(ViewDoc doc) {
private static UpdateRequest newUpsertRequest(ViewDoc doc) {
return new UpdateRequest(ViewIndexDefinition.INDEX, ViewIndexDefinition.TYPE_VIEW, doc.uuid())
.doc(doc.getFields())
.upsert(doc.getFields());

server/sonar-server/src/test/java/org/sonar/server/computation/step/PersistComponentsStepTest.java → server/sonar-server/src/test/java/org/sonar/server/computation/step/PersistComponentsAndSnapshotsStepTest.java View File

@@ -26,6 +26,7 @@ import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.sonar.api.utils.System2;
import org.sonar.batch.protocol.Constants;
import org.sonar.batch.protocol.output.BatchReport;
import org.sonar.core.component.ComponentDto;
@@ -42,9 +43,10 @@ import org.sonar.server.db.DbClient;
import org.sonar.test.DbTests;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

@Category(DbTests.class)
public class PersistComponentsStepTest extends BaseStepTest {
public class PersistComponentsAndSnapshotsStepTest extends BaseStepTest {

private static final String PROJECT_KEY = "PROJECT_KEY";

@@ -52,17 +54,20 @@ public class PersistComponentsStepTest extends BaseStepTest {
public static DbTester dbTester = new DbTester();

@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();

@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
public BatchReportReaderRule reportReader = new BatchReportReaderRule();

System2 system2 = mock(System2.class);

DbIdsRepository dbIdsRepository;

DbSession session;

DbClient dbClient;

PersistComponentsStep sut;
PersistComponentsAndSnapshotsStep sut;

@Before
public void setup() throws Exception {
@@ -70,8 +75,10 @@ public class PersistComponentsStepTest extends BaseStepTest {
session = dbTester.myBatis().openSession(false);
dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), new ComponentDao());

reportReader.setMetadata(BatchReport.Metadata.newBuilder().build());

dbIdsRepository = new DbIdsRepository();
sut = new PersistComponentsStep(dbClient, dbIdsRepository, reportReader, treeRootHolder);
sut = new PersistComponentsAndSnapshotsStep(system2, dbClient, treeRootHolder, reportReader, dbIdsRepository);
}

@Override
@@ -86,10 +93,6 @@ public class PersistComponentsStepTest extends BaseStepTest {

@Test
public void persist_components() throws Exception {
reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -191,10 +194,6 @@ public class PersistComponentsStepTest extends BaseStepTest {

@Test
public void persist_file_directly_attached_on_root_directory() throws Exception {
reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -217,6 +216,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
treeRootHolder.setRoot(new DumbComponent(Component.Type.PROJECT, 1, "ABCD", PROJECT_KEY,
new DumbComponent(Component.Type.DIRECTORY, 2, "CDEF", PROJECT_KEY + ":/",
new DumbComponent(Component.Type.FILE, 3, "DEFG", PROJECT_KEY + ":pom.xml"))));

sut.execute();

ComponentDto directory = dbClient.componentDao().selectNullableByKey(session, "PROJECT_KEY:/");
@@ -232,10 +232,6 @@ public class PersistComponentsStepTest extends BaseStepTest {

@Test
public void persist_unit_test() throws Exception {
reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -259,6 +255,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
treeRootHolder.setRoot(new DumbComponent(Component.Type.PROJECT, 1, "ABCD", PROJECT_KEY,
new DumbComponent(Component.Type.DIRECTORY, 2, "CDEF", PROJECT_KEY + ":src/test/java/dir",
new DumbComponent(Component.Type.FILE, 3, "DEFG", PROJECT_KEY + ":src/test/java/dir/FooTest.java"))));

sut.execute();

ComponentDto file = dbClient.componentDao().selectNullableByKey(session, PROJECT_KEY + ":src/test/java/dir/FooTest.java");
@@ -278,10 +275,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, module);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -312,6 +305,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_KEY",
new DumbComponent(Component.Type.DIRECTORY, 3, "CDEF", "MODULE_KEY:src/main/java/dir",
new DumbComponent(Component.Type.FILE, 4, "DEFG", "MODULE_KEY:src/main/java/dir/Foo.java")))));

sut.execute();

assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(4);
@@ -345,10 +339,6 @@ public class PersistComponentsStepTest extends BaseStepTest {

@Test
public void compute_parent_project_id() throws Exception {
reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -388,6 +378,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
new DumbComponent(Component.Type.MODULE, 3, "CDEF", "SUB_MODULE_1_KEY",
new DumbComponent(Component.Type.MODULE, 4, "DEFG", "SUB_MODULE_2_KEY",
new DumbComponent(Component.Type.DIRECTORY, 5, "EFGH", "SUB_MODULE_2_KEY:src/main/java/dir"))))));

sut.execute();

assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(5);
@@ -415,10 +406,6 @@ public class PersistComponentsStepTest extends BaseStepTest {

@Test
public void persist_multi_modules() throws Exception {
reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -451,6 +438,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_A",
new DumbComponent(Component.Type.MODULE, 3, "DEFG", "SUB_MODULE_A")),
new DumbComponent(Component.Type.MODULE, 4, "CDEF", "MODULE_B")));

sut.execute();

assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(4);
@@ -491,10 +479,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, directory, file);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -525,6 +509,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_KEY",
new DumbComponent(Component.Type.DIRECTORY, 3, "CDEF", "MODULE_KEY:src/main/java/dir",
new DumbComponent(Component.Type.FILE, 4, "DEFG", "MODULE_KEY:src/main/java/dir/Foo.java")))));

sut.execute();

assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(4);
@@ -578,10 +563,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, module);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -599,6 +580,7 @@ public class PersistComponentsStepTest extends BaseStepTest {

treeRootHolder.setRoot(new DumbComponent(Component.Type.PROJECT, 1, "ABCD", PROJECT_KEY,
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_KEY")));
sut.execute();

ComponentDto projectReloaded = dbClient.componentDao().selectNullableByKey(session, PROJECT_KEY);
@@ -616,10 +598,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, module);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -638,6 +616,7 @@ public class PersistComponentsStepTest extends BaseStepTest {

treeRootHolder.setRoot(new DumbComponent(Component.Type.PROJECT, 1, "ABCD", PROJECT_KEY,
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_KEY")));
sut.execute();

ComponentDto projectReloaded = dbClient.componentDao().selectNullableByKey(session, PROJECT_KEY);
@@ -655,10 +634,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, module);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -676,6 +651,7 @@ public class PersistComponentsStepTest extends BaseStepTest {

treeRootHolder.setRoot(new DumbComponent(Component.Type.PROJECT, 1, "ABCD", PROJECT_KEY,
new DumbComponent(Component.Type.MODULE, 2, "BCDE", "MODULE_KEY")));

sut.execute();

ComponentDto moduleReloaded = dbClient.componentDao().selectNullableByKey(session, "MODULE_KEY");
@@ -694,10 +670,6 @@ public class PersistComponentsStepTest extends BaseStepTest {
dbClient.componentDao().insert(session, directory, file);
session.commit();

reportReader.setMetadata(BatchReport.Metadata.newBuilder()
.setRootComponentRef(1)
.build());

reportReader.putComponent(BatchReport.Component.newBuilder()
.setRef(1)
.setType(Constants.ComponentType.PROJECT)
@@ -737,6 +709,7 @@ public class PersistComponentsStepTest extends BaseStepTest {
new DumbComponent(Component.Type.MODULE, 3, "BCDE", "MODULE_B",
new DumbComponent(Component.Type.DIRECTORY, 4, "CDEF", "MODULE_B:src/main/java/dir",
new DumbComponent(Component.Type.FILE, 5, "DEFG", "MODULE_B:src/main/java/dir/Foo.java"))))));

sut.execute();

assertThat(dbTester.countRowsOfTable("projects")).isEqualTo(5);

+ 4
- 6
sonar-batch-protocol/src/main/java/org/sonar/batch/protocol/output/BatchReportReader.java View File

@@ -19,14 +19,12 @@
*/
package org.sonar.batch.protocol.output;

import org.sonar.batch.protocol.ProtobufUtil;
import org.sonar.batch.protocol.output.BatchReport.Issues;

import javax.annotation.CheckForNull;

import java.io.File;
import java.util.Collections;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.batch.protocol.ProtobufUtil;
import org.sonar.batch.protocol.output.BatchReport.Issues;

public class BatchReportReader {

@@ -161,7 +159,7 @@ public class BatchReportReader {
return null;
}

private boolean doesFileExists(File file) {
private static boolean doesFileExists(File file) {
return file.exists() && file.isFile();
}
}

+ 2
- 3
sonar-batch/src/main/java/org/sonar/batch/DefaultFileLinesContext.java View File

@@ -23,6 +23,7 @@ import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
import org.sonar.api.batch.SonarIndex;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.measures.Measure;
@@ -33,8 +34,6 @@ import org.sonar.api.resources.ResourceUtils;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.api.utils.KeyValueFormat.Converter;

import java.util.Map;

public class DefaultFileLinesContext implements FileLinesContext {

private final SonarIndex index;
@@ -143,7 +142,7 @@ public class DefaultFileLinesContext implements FileLinesContext {
* @see #loadData(String, Converter)
* @see #save()
*/
private boolean shouldSave(Map<Integer, Object> lines) {
private static boolean shouldSave(Map<Integer, Object> lines) {
return !(lines instanceof ImmutableMap);
}


+ 1
- 1
sonar-batch/src/main/java/org/sonar/batch/compute/AbstractNewCoverageFileAnalyzer.java View File

@@ -175,7 +175,7 @@ public abstract class AbstractNewCoverageFileAnalyzer implements Decorator {
context.saveMeasure(newUncoveredConditions);
}

private Map<Integer, Integer> parseCountByLine(@Nullable Measure measure) {
private static Map<Integer, Integer> parseCountByLine(@Nullable Measure measure) {
if (measure != null && measure.hasData()) {
return KeyValueFormat.parseIntInt(measure.getData());
}

+ 7
- 7
sonar-batch/src/main/java/org/sonar/batch/compute/CountUnresolvedIssuesDecorator.java View File

@@ -146,7 +146,7 @@ public class CountUnresolvedIssuesDecorator implements Decorator {
}
}

private void saveTotalIssues(DecoratorContext context, Collection<Issue> issues) {
private static void saveTotalIssues(DecoratorContext context, Collection<Issue> issues) {
if (context.getMeasure(CoreMetrics.VIOLATIONS) == null) {
Collection<Measure> childrenIssues = context.getChildrenMeasures(CoreMetrics.VIOLATIONS);
Double sum = MeasureUtils.sum(true, childrenIssues);
@@ -161,7 +161,7 @@ public class CountUnresolvedIssuesDecorator implements Decorator {
}
}

private void saveIssuesForSeverity(DecoratorContext context, RulePriority ruleSeverity, Multiset<RulePriority> severitiesBag) {
private static void saveIssuesForSeverity(DecoratorContext context, RulePriority ruleSeverity, Multiset<RulePriority> severitiesBag) {
Metric metric = SeverityUtils.severityToIssueMetric(ruleSeverity);
if (context.getMeasure(metric) == null) {
Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
@@ -248,11 +248,11 @@ public class CountUnresolvedIssuesDecorator implements Decorator {
context.saveMeasure(measure);
}

private void saveMeasure(DecoratorContext context, Metric metric, int value) {
private static void saveMeasure(DecoratorContext context, Metric metric, int value) {
context.saveMeasure(metric, (double) (value + sumChildren(context, metric)));
}

private int sumChildren(DecoratorContext context, Metric metric) {
private static int sumChildren(DecoratorContext context, Metric metric) {
int sum = 0;
if (!ResourceUtils.isFile(context.getResource())) {
sum = MeasureUtils.sum(true, context.getChildrenMeasures(metric)).intValue();
@@ -260,7 +260,7 @@ public class CountUnresolvedIssuesDecorator implements Decorator {
return sum;
}

private Multiset<RuleKey> initRules(Map<RulePriority, Multiset<RuleKey>> rulesPerSeverity, RulePriority severity) {
private static Multiset<RuleKey> initRules(Map<RulePriority, Multiset<RuleKey>> rulesPerSeverity, RulePriority severity) {
Multiset<RuleKey> rulesBag = rulesPerSeverity.get(severity);
if (rulesBag == null) {
rulesBag = HashMultiset.create();
@@ -289,11 +289,11 @@ public class CountUnresolvedIssuesDecorator implements Decorator {
return count;
}

private boolean isAfter(Issue issue, @Nullable Date date) {
private static boolean isAfter(Issue issue, @Nullable Date date) {
return date == null || (issue.creationDate() != null && DateUtils.truncatedCompareTo(issue.creationDate(), date, Calendar.SECOND) > 0);
}

private boolean shouldSaveNewMetrics(DecoratorContext context) {
private static boolean shouldSaveNewMetrics(DecoratorContext context) {
return context.getMeasure(CoreMetrics.NEW_VIOLATIONS) == null;
}


+ 1
- 1
sonar-batch/src/main/java/org/sonar/batch/compute/TimeMachineConfigurationPersister.java View File

@@ -74,7 +74,7 @@ public final class TimeMachineConfigurationPersister implements Decorator {
return true;
}

private void updatePeriodParams(Snapshot snapshot, PastSnapshot pastSnapshot) {
private static void updatePeriodParams(Snapshot snapshot, PastSnapshot pastSnapshot) {
int periodIndex = pastSnapshot.getIndex();
snapshot.setPeriodMode(periodIndex, pastSnapshot.getMode());
snapshot.setPeriodModeParameter(periodIndex, pastSnapshot.getModeParameter());

+ 7
- 9
sonar-batch/src/main/java/org/sonar/batch/debt/DebtDecorator.java View File

@@ -21,6 +21,12 @@
package org.sonar.batch.debt;

import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.Decorator;
import org.sonar.api.batch.DecoratorBarriers;
import org.sonar.api.batch.DecoratorContext;
@@ -47,14 +53,6 @@ import org.sonar.api.rules.RuleFinder;
import org.sonar.api.technicaldebt.batch.Characteristic;
import org.sonar.api.technicaldebt.batch.TechnicalDebtModel;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;

@@ -182,7 +180,7 @@ public final class DebtDecorator implements Decorator {
}
}

private void saveMeasure(DecoratorContext context, Measure measure, Double value, boolean inMemory) {
private static void saveMeasure(DecoratorContext context, Measure measure, Double value, boolean inMemory) {
measure.setValue(value);
if (inMemory) {
measure.setPersistenceMode(PersistenceMode.MEMORY);

+ 3
- 4
sonar-batch/src/main/java/org/sonar/batch/debt/DebtModelProvider.java View File

@@ -22,6 +22,8 @@ package org.sonar.batch.debt;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.List;
import javax.annotation.Nullable;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.batch.debt.DebtCharacteristic;
import org.sonar.api.batch.debt.DebtModel;
@@ -32,9 +34,6 @@ import org.sonar.api.utils.log.Profiler;
import org.sonar.core.technicaldebt.db.CharacteristicDao;
import org.sonar.core.technicaldebt.db.CharacteristicDto;

import javax.annotation.Nullable;
import java.util.List;

public class DebtModelProvider extends ProviderAdapter {

private DebtModel model;
@@ -48,7 +47,7 @@ public class DebtModelProvider extends ProviderAdapter {
return model;
}

private DebtModel load(CharacteristicDao dao) {
private static DebtModel load(CharacteristicDao dao) {
DefaultDebtModel debtModel = new DefaultDebtModel();

List<CharacteristicDto> allCharacteristics = dao.selectEnabledCharacteristics();

+ 14
- 16
sonar-batch/src/main/java/org/sonar/batch/debt/IssueChangelogDebtCalculator.java View File

@@ -22,16 +22,6 @@ package org.sonar.batch.debt;

import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import org.apache.commons.lang.time.DateUtils;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.core.issue.IssueUpdater;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
@@ -39,6 +29,14 @@ import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.time.DateUtils;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.issue.Issue;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.core.issue.IssueUpdater;

import static com.google.common.collect.Lists.newArrayList;

@@ -82,7 +80,7 @@ public class IssueChangelogDebtCalculator {
* SONAR-5059
*/
@CheckForNull
private Long subtractNeverNegative(@Nullable Long value, Long with) {
private static Long subtractNeverNegative(@Nullable Long value, @Nullable Long with) {
Long result = (value != null ? value : 0) - (with != null ? with : 0);
return result > 0 ? result : null;
}
@@ -103,7 +101,7 @@ public class IssueChangelogDebtCalculator {
return Collections.emptyList();
}

private List<FieldDiffs> changesOnField(Collection<FieldDiffs> fieldDiffs) {
private static List<FieldDiffs> changesOnField(Collection<FieldDiffs> fieldDiffs) {
List<FieldDiffs> diffs = newArrayList();
for (FieldDiffs fieldDiff : fieldDiffs) {
if (fieldDiff.diffs().containsKey(IssueUpdater.TECHNICAL_DEBT)) {
@@ -114,7 +112,7 @@ public class IssueChangelogDebtCalculator {
}

@CheckForNull
private Long newValue(FieldDiffs fieldDiffs) {
private static Long newValue(FieldDiffs fieldDiffs) {
for (Map.Entry<String, FieldDiffs.Diff> entry : fieldDiffs.diffs().entrySet()) {
if (entry.getKey().equals(IssueUpdater.TECHNICAL_DEBT)) {
return entry.getValue().newValueLong();
@@ -124,7 +122,7 @@ public class IssueChangelogDebtCalculator {
}

@CheckForNull
private Long oldValue(FieldDiffs fieldDiffs) {
private static Long oldValue(FieldDiffs fieldDiffs) {
for (Map.Entry<String, FieldDiffs.Diff> entry : fieldDiffs.diffs().entrySet()) {
if (entry.getKey().equals(IssueUpdater.TECHNICAL_DEBT)) {
return entry.getValue().oldValueLong();
@@ -133,11 +131,11 @@ public class IssueChangelogDebtCalculator {
return null;
}

private boolean isAfter(@Nullable Date currentDate, @Nullable Date pastDate) {
private static boolean isAfter(@Nullable Date currentDate, @Nullable Date pastDate) {
return pastDate == null || (currentDate != null && DateUtils.truncatedCompareTo(currentDate, pastDate, Calendar.SECOND) > 0);
}

private boolean isLesserOrEqual(@Nullable Date currentDate, @Nullable Date pastDate) {
private static boolean isLesserOrEqual(@Nullable Date currentDate, @Nullable Date pastDate) {
return (currentDate != null) && (pastDate == null || (DateUtils.truncatedCompareTo(currentDate, pastDate, Calendar.SECOND) <= 0));
}


+ 5
- 7
sonar-batch/src/main/java/org/sonar/batch/debt/NewDebtDecorator.java View File

@@ -21,6 +21,10 @@
package org.sonar.batch.debt;

import com.google.common.collect.ImmutableList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.batch.Decorator;
import org.sonar.api.batch.DecoratorBarriers;
import org.sonar.api.batch.DecoratorContext;
@@ -39,12 +43,6 @@ import org.sonar.api.resources.Resource;
import org.sonar.batch.components.Period;
import org.sonar.batch.components.TimeMachineConfiguration;

import javax.annotation.Nullable;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -109,7 +107,7 @@ public final class NewDebtDecorator implements Decorator {
return result;
}

private boolean shouldSaveNewMetrics(DecoratorContext context) {
private static boolean shouldSaveNewMetrics(DecoratorContext context) {
return context.getMeasure(CoreMetrics.NEW_TECHNICAL_DEBT) == null;
}


+ 6
- 8
sonar-batch/src/main/java/org/sonar/batch/debt/SqaleRatingDecorator.java View File

@@ -22,6 +22,10 @@ package org.sonar.batch.debt;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.api.batch.Decorator;
import org.sonar.api.batch.DecoratorContext;
import org.sonar.api.batch.DependedUpon;
@@ -35,12 +39,6 @@ import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.api.resources.ResourceUtils;

import javax.annotation.Nullable;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
* Decorator that computes Sqale Rating metric
*/
@@ -95,7 +93,7 @@ public class SqaleRatingDecorator implements Decorator {
}
}

private Measure createRatingMeasure(int rating) {
private static Measure createRatingMeasure(int rating) {
return new Measure(CoreMetrics.SQALE_RATING).setIntValue(rating).setData(toRatingLetter(rating));
}

@@ -132,7 +130,7 @@ public class SqaleRatingDecorator implements Decorator {
return sum;
}

private long getMeasureValue(DecoratorContext context, Metric metric) {
private static long getMeasureValue(DecoratorContext context, Metric metric) {
Measure measure = context.getMeasure(metric);
if (measure != null) {
return measure.getValue().longValue();

+ 3
- 4
sonar-batch/src/main/java/org/sonar/batch/debt/SqaleRatingSettings.java View File

@@ -20,13 +20,12 @@

package org.sonar.batch.debt;

import org.sonar.api.batch.BatchSide;
import javax.annotation.Nullable;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.config.Settings;
import org.sonar.api.measures.Metric;

import javax.annotation.Nullable;

@BatchSide
public class SqaleRatingSettings {

@@ -76,7 +75,7 @@ public class SqaleRatingSettings {
return getMetricForKey(settings.getString(CoreProperties.SIZE_METRIC), metrics);
}

private Metric getMetricForKey(String sizeMetricKey, Metric[] metrics) {
private static Metric getMetricForKey(String sizeMetricKey, Metric[] metrics) {
for (Metric metric : metrics) {
if (metric.getKey().equals(sizeMetricKey)) {
return metric;

+ 2
- 3
sonar-batch/src/main/java/org/sonar/batch/issue/ModuleIssues.java View File

@@ -21,6 +21,7 @@ package org.sonar.batch.issue;

import com.google.common.base.Objects;
import com.google.common.base.Strings;
import javax.annotation.Nullable;
import org.sonar.api.batch.debt.DebtRemediationFunction;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
@@ -35,8 +36,6 @@ import org.sonar.api.utils.Duration;
import org.sonar.api.utils.MessageException;
import org.sonar.core.issue.DefaultIssueBuilder;

import javax.annotation.Nullable;

/**
* Initialize the issues raised during scan.
*/
@@ -98,7 +97,7 @@ public class ModuleIssues {
return false;
}

private void validateRule(DefaultIssue issue, Rule rule) {
private static void validateRule(DefaultIssue issue, @Nullable Rule rule) {
RuleKey ruleKey = issue.ruleKey();
if (rule == null) {
throw MessageException.of(String.format("The rule '%s' does not exist.", ruleKey));

+ 4
- 5
sonar-batch/src/main/java/org/sonar/batch/rule/RulesProvider.java View File

@@ -22,6 +22,8 @@ package org.sonar.batch.rule;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.List;
import javax.annotation.Nullable;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.batch.debt.DebtCharacteristic;
import org.sonar.api.batch.debt.DebtModel;
@@ -38,9 +40,6 @@ import org.sonar.core.rule.RuleDao;
import org.sonar.core.rule.RuleDto;
import org.sonar.core.rule.RuleParamDto;

import javax.annotation.Nullable;
import java.util.List;

/**
* Loads all enabled and non manual rules
*/
@@ -88,7 +87,7 @@ public class RulesProvider extends ProviderAdapter {
return rulesBuilder.build();
}

private DebtCharacteristic effectiveCharacteristic(RuleDto ruleDto, RuleKey ruleKey, DefaultDebtModel debtModel) {
private static DebtCharacteristic effectiveCharacteristic(RuleDto ruleDto, RuleKey ruleKey, DefaultDebtModel debtModel) {
Integer subCharacteristicId = ruleDto.getSubCharacteristicId();
Integer defaultSubCharacteristicId = ruleDto.getDefaultSubCharacteristicId();
Integer effectiveSubCharacteristicId = subCharacteristicId != null ? subCharacteristicId : defaultSubCharacteristicId;
@@ -121,7 +120,7 @@ public class RulesProvider extends ProviderAdapter {
* Return true is the characteristic has not been overridden and a default characteristic is existing or
* if the characteristic has been overridden but is not disabled
*/
private boolean hasCharacteristic(RuleDto ruleDto) {
private static boolean hasCharacteristic(RuleDto ruleDto) {
Integer subCharacteristicId = ruleDto.getSubCharacteristicId();
return (subCharacteristicId == null && ruleDto.getDefaultSubCharacteristicId() != null) ||
(subCharacteristicId != null && !RuleDto.DISABLED_CHARACTERISTIC_ID.equals(subCharacteristicId));

+ 6
- 8
sonar-core/src/main/java/org/sonar/core/notification/DefaultNotificationManager.java View File

@@ -25,6 +25,11 @@ import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import java.io.IOException;
import java.io.InvalidClassException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.RequiresDB;
@@ -35,13 +40,6 @@ import org.sonar.core.notification.db.NotificationQueueDao;
import org.sonar.core.notification.db.NotificationQueueDto;
import org.sonar.core.properties.PropertiesDao;

import javax.annotation.Nullable;

import java.io.IOException;
import java.io.InvalidClassException;
import java.util.Arrays;
import java.util.List;

/**
* @since 2.10
*/
@@ -175,7 +173,7 @@ public class DefaultNotificationManager implements NotificationManager {
return Arrays.asList(notificationChannels);
}

private void addUsersToRecipientListForChannel(List<String> users, SetMultimap<String, NotificationChannel> recipients, NotificationChannel channel) {
private static void addUsersToRecipientListForChannel(List<String> users, SetMultimap<String, NotificationChannel> recipients, NotificationChannel channel) {
for (String username : users) {
recipients.put(username, channel);
}

+ 3
- 5
sonar-core/src/main/java/org/sonar/core/permission/PermissionQuery.java View File

@@ -22,12 +22,10 @@ package org.sonar.core.permission;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang.StringUtils;

import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.Set;
import org.apache.commons.lang.StringUtils;

/**
* Query used to get users and groups from a permission
@@ -70,7 +68,7 @@ public class PermissionQuery {
this.pageIndex = builder.pageIndex;
}

private String searchToSql(@Nullable String s) {
private static String searchToSql(@Nullable String s) {
String sql = null;
if (s != null) {
sql = StringUtils.replace(StringUtils.upperCase(s), "%", "/%");

+ 6
- 7
sonar-core/src/main/java/org/sonar/core/resource/ResourceKeyUpdaterDao.java View File

@@ -22,15 +22,14 @@ package org.sonar.core.resource;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.persistence.MyBatis;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.persistence.MyBatis;

/**
* Class used to rename the key of a project and its resources.
@@ -117,11 +116,11 @@ public class ResourceKeyUpdaterDao {
}
}

private String computeNewKey(ResourceDto resource, String stringToReplace, String replacementString) {
private static String computeNewKey(ResourceDto resource, String stringToReplace, String replacementString) {
return resource.getKey().replaceAll(stringToReplace, replacementString);
}

private void runBatchUpdateForAllResources(Collection<ResourceDto> resources, String oldKey, String newKey, ResourceKeyUpdaterMapper mapper) {
private static void runBatchUpdateForAllResources(Collection<ResourceDto> resources, String oldKey, String newKey, ResourceKeyUpdaterMapper mapper) {
for (ResourceDto resource : resources) {
String resourceKey = resource.getKey();
resource.setKey(newKey + resourceKey.substring(oldKey.length(), resourceKey.length()));

+ 12
- 14
sonar-core/src/main/java/org/sonar/core/timemachine/Periods.java View File

@@ -19,22 +19,20 @@
*/
package org.sonar.core.timemachine;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.CoreProperties;
import org.sonar.api.server.ServerSide;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.batch.RequiresDB;
import org.sonar.api.config.Settings;
import org.sonar.api.database.model.Snapshot;
import org.sonar.api.i18n.I18n;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.sonar.api.server.ServerSide;

import static org.sonar.api.utils.DateUtils.longToDate;

@@ -133,7 +131,7 @@ public class Periods {
}

@CheckForNull
private String convertDate(Date date) {
private static String convertDate(Date date) {
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd");
return dateFormat.format(date);
@@ -141,7 +139,7 @@ public class Periods {
return null;
}

private Locale getLocale() {
private static Locale getLocale() {
return Locale.ENGLISH;
}

@@ -168,7 +166,7 @@ public class Periods {
}
}

private Integer findByDays(String property) {
private static Integer findByDays(String property) {
try {
return Integer.parseInt(property);
} catch (NumberFormatException e) {
@@ -176,7 +174,7 @@ public class Periods {
}
}

private Date findByDate(String property) {
private static Date findByDate(String property) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(property);

+ 1
- 1
sonar-core/src/main/java/org/sonar/core/user/GroupMembershipQuery.java View File

@@ -64,7 +64,7 @@ public class GroupMembershipQuery {
this.pageIndex = builder.pageIndex;
}

private String groupSearchToSql(@Nullable String s) {
private static String groupSearchToSql(@Nullable String s) {
String sql = null;
if (s != null) {
sql = StringUtils.replace(StringUtils.upperCase(s), "%", "/%");

+ 3
- 5
sonar-plugin-api/src/main/java/org/sonar/api/issue/internal/FieldDiffs.java View File

@@ -22,13 +22,11 @@ package org.sonar.api.issue.internal;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

/**
* PLUGINS MUST NOT USE THIS CLASS, EXCEPT FOR UNIT TESTING.
@@ -168,7 +166,7 @@ public class FieldDiffs implements Serializable {
}

@CheckForNull
private Long toLong(Serializable value) {
private static Long toLong(@Nullable Serializable value) {
if (value != null && !"".equals(value)) {
try {
return Long.valueOf((String) value);

+ 2
- 3
sonar-plugin-api/src/main/java/org/sonar/api/measures/AverageFormula.java View File

@@ -20,9 +20,8 @@

package org.sonar.api.measures;

import org.sonar.api.resources.ResourceUtils;

import java.util.List;
import org.sonar.api.resources.ResourceUtils;

import static com.google.common.collect.Lists.newArrayList;

@@ -130,7 +129,7 @@ public class AverageFormula implements Formula {
return result;
}

private boolean shouldDecorateResource(FormulaData data, FormulaContext context) {
private static boolean shouldDecorateResource(FormulaData data, FormulaContext context) {
return !MeasureUtils.hasValue(data.getMeasure(context.getTargetMetric()));
}
}

+ 14
- 16
sonar-plugin-api/src/main/java/org/sonar/api/rules/Rule.java View File

@@ -22,16 +22,10 @@ package org.sonar.api.rules;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.SonarException;
import org.sonar.check.Cardinality;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.persistence.Column;
@@ -48,11 +42,15 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.SonarException;
import org.sonar.check.Cardinality;

@Entity
@Table(name = "rules")
@@ -560,7 +558,7 @@ public class Rule {
}

@CheckForNull
private String removeNewLineCharacters(@Nullable String text) {
private static String removeNewLineCharacters(@Nullable String text) {
String removedCRLF = StringUtils.remove(text, "\n");
removedCRLF = StringUtils.remove(removedCRLF, "\r");
removedCRLF = StringUtils.remove(removedCRLF, "\n\r");

+ 2
- 3
sonar-plugin-api/src/main/java/org/sonar/api/server/rule/RuleParamType.java View File

@@ -19,12 +19,11 @@
*/
package org.sonar.api.server.rule;

import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.PropertyType;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
@@ -75,7 +74,7 @@ public final class RuleParamType {
this.multiple = multiple;
}

private String valuesToCsv(String... values) {
private static String valuesToCsv(String... values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(StringEscapeUtils.escapeCsv(value));

+ 5
- 7
sonar-plugin-api/src/main/java/org/sonar/api/utils/Durations.java View File

@@ -20,16 +20,14 @@

package org.sonar.api.utils;

import java.util.Locale;
import javax.annotation.CheckForNull;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.config.Settings;
import org.sonar.api.i18n.I18n;
import org.sonar.api.server.ServerSide;

import javax.annotation.CheckForNull;

import java.util.Locale;

/**
* Used through ruby code <pre>Internal.durations</pre>
*
@@ -133,15 +131,15 @@ public class Durations {
return i18n.message(locale, key, null, parameter);
}

private boolean displayHours(int days, int hours) {
private static boolean displayHours(int days, int hours) {
return hours > 0 && days < 10;
}

private boolean displayMinutes(int days, int hours, int minutes) {
private static boolean displayMinutes(int days, int hours, int minutes) {
return minutes > 0 && hours < 10 && days == 0;
}

private void addSpaceIfNeeded(StringBuilder message) {
private static void addSpaceIfNeeded(StringBuilder message) {
if (message.length() > 0) {
message.append(" ");
}

Loading…
Cancel
Save