Browse Source

SONAR-10555 enforce at API level that project version is never null

tags/7.5
Sébastien Lesaint 5 years ago
parent
commit
1e405ab5a8
63 changed files with 394 additions and 433 deletions
  1. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImpl.java
  2. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImpl.java
  3. 9
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/Component.java
  4. 49
    23
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentImpl.java
  5. 10
    11
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilder.java
  6. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DepthTraversalTypeAwareCrawler.java
  7. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/MapBasedDbIdsRepository.java
  8. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathAwareCrawler.java
  9. 41
    0
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectAttributes.java
  10. 0
    19
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ReportAttributes.java
  11. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/VisitorsCrawler.java
  12. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/Duplication.java
  13. 2
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImpl.java
  14. 2
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplications.java
  15. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStep.java
  16. 3
    4
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImpl.java
  17. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IntegrateIssuesVisitor.java
  18. 1
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitor.java
  19. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ShortBranchIssuesLoader.java
  20. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerMergeBranchInputFactory.java
  21. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactory.java
  22. 2
    4
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepository.java
  23. 1
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoader.java
  24. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImpl.java
  25. 4
    5
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImpl.java
  26. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/HighlightingLineReader.java
  27. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/SymbolsLineReader.java
  28. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/DuplicationDataMeasuresStep.java
  29. 3
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStep.java
  30. 1
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStep.java
  31. 4
    4
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisStep.java
  32. 3
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStep.java
  33. 5
    7
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStep.java
  34. 1
    1
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistFileSourcesStep.java
  35. 2
    2
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistTestsStep.java
  36. 3
    3
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStep.java
  37. 7
    7
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStep.java
  38. 4
    4
      server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ValidateProjectStep.java
  39. 2
    2
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplTest.java
  40. 2
    2
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CallRecorderPathAwareVisitor.java
  41. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CallRecorderTypeAwareVisitor.java
  42. 18
    14
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java
  43. 44
    152
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java
  44. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/MutableDbIdsRepositoryRule.java
  45. 24
    7
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportComponent.java
  46. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeComponentProvider.java
  47. 8
    3
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsComponent.java
  48. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java
  49. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java
  50. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java
  51. 27
    27
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepTest.java
  52. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java
  53. 4
    4
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java
  54. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryRule.java
  55. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoaderTest.java
  56. 2
    2
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepTest.java
  57. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepTest.java
  58. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java
  59. 47
    48
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStepTest.java
  60. 1
    1
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistLiveMeasuresStepTest.java
  61. 14
    11
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java
  62. 2
    2
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepTest.java
  63. 8
    8
      server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java

+ 2
- 2
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImpl.java View File

@@ -169,7 +169,7 @@ public class MeasureComputerContextImpl implements MeasureComputerContext {
checkArgument(definition.getOutputMetrics().contains(metric.getKey()), "Only metrics in %s can be used to add measures. Metric '%s' is not allowed.",
definition.getOutputMetrics(), metric.getKey());
if (measureRepository.getRawMeasure(internalComponent, metric).isPresent()) {
throw new UnsupportedOperationException(String.format("A measure on metric '%s' already exists on component '%s'", metric.getKey(), internalComponent.getKey()));
throw new UnsupportedOperationException(String.format("A measure on metric '%s' already exists on component '%s'", metric.getKey(), internalComponent.getDbKey()));
}
}

@@ -180,7 +180,7 @@ public class MeasureComputerContextImpl implements MeasureComputerContext {

private static Component newComponent(org.sonar.ce.task.projectanalysis.component.Component component) {
return new ComponentImpl(
component.getKey(),
component.getDbKey(),
Component.Type.valueOf(component.getType().name()),
component.getType() == org.sonar.ce.task.projectanalysis.component.Component.Type.FILE
? new ComponentImpl.FileAttributesImpl(component.getFileAttributes().getLanguageKey(), component.getFileAttributes().isUnitTest())

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

@@ -112,7 +112,7 @@ public class BranchPersisterImpl implements BranchPersister {
branchDto.setUuidPath(UUID_PATH_OF_ROOT);
branchDto.setModuleUuidPath(UUID_PATH_SEPARATOR + branchUuid + UUID_PATH_SEPARATOR);
branchDto.setMainBranchProjectUuid(mainBranchProjectUuid);
branchDto.setDbKey(treeRootHolder.getRoot().getKey());
branchDto.setDbKey(treeRootHolder.getRoot().getDbKey());
branchDto.setCreatedAt(new Date(system2.now()));
dbClient.componentDao().insert(dbSession, branchDto);
return branchDto;

+ 9
- 3
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/Component.java View File

@@ -80,15 +80,14 @@ public interface Component {
* It may differ from keys listed in scanner report
* when analyzing a branch.
*/
String getKey();
String getDbKey();

/**
* Returns the key as it will be displayed in the ui.
* If legacy branch feature is used, the key will contain the branch name
* If new branch feature is used, the key will not contain the branch name
*/
// TODO to be renamed getKey() and rename existing getKey to getDbKey
String getPublicKey();
String getKey();

/**
* The component name.
@@ -103,6 +102,13 @@ public interface Component {

List<Component> getChildren();

/**
* Returns the attributes specific to components of type {@link Type#PROJECT}.
*
* @throws IllegalStateException when the component's type is not {@link Type#PROJECT}.
*/
ProjectAttributes getProjectAttributes();

/**
* Returns the attributes specific to components of type {@link Type#PROJECT}, {@link Type#MODULE},
* {@link Type#DIRECTORY} or {@link Type#FILE}.

+ 49
- 23
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentImpl.java View File

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

import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
@@ -39,14 +40,15 @@ public class ComponentImpl implements Component {
private final Type type;
private final Status status;
private final String name;
private final String dbKey;
private final String key;
private final String publicKey;
private final String uuid;

@CheckForNull
private final String description;
private final List<Component> children;
@CheckForNull
private final ProjectAttributes projectAttributes;
private final ReportAttributes reportAttributes;
@CheckForNull
private final FileAttributes fileAttributes;
@@ -54,11 +56,12 @@ public class ComponentImpl implements Component {
private ComponentImpl(Builder builder) {
this.type = builder.type;
this.status = builder.status;
this.key = builder.key;
this.publicKey = builder.publicKey;
this.dbKey = builder.dbKey;
this.key = MoreObjects.firstNonNull(builder.key, builder.dbKey);
this.name = builder.name;
this.description = builder.description;
this.uuid = builder.uuid;
this.projectAttributes = builder.projectAttributes;
this.reportAttributes = builder.reportAttributes;
this.fileAttributes = builder.fileAttributes;
this.children = ImmutableList.copyOf(builder.children);
@@ -80,13 +83,13 @@ public class ComponentImpl implements Component {
}

@Override
public String getKey() {
return key;
public String getDbKey() {
return dbKey;
}

@Override
public String getPublicKey() {
return publicKey;
public String getKey() {
return key;
}

@Override
@@ -105,6 +108,12 @@ public class ComponentImpl implements Component {
return children;
}

@Override
public ProjectAttributes getProjectAttributes() {
checkState(this.type == Type.PROJECT, "Only component of type PROJECT have a ProjectAttributes object");
return this.projectAttributes;
}

@Override
public ReportAttributes getReportAttributes() {
return this.reportAttributes;
@@ -137,7 +146,8 @@ public class ComponentImpl implements Component {

public static final class Builder {

private static final String KEY_CANNOT_BE_NULL = "key can't be null";
private static final String DB_KEY_CANNOT_BE_NULL = "DB key can't be null";
private static final String KEY_CANNOT_BE_NULL = "Key can't be null";
private static final String UUID_CANNOT_BE_NULL = "uuid can't be null";
private static final String REPORT_ATTRIBUTES_CANNOT_BE_NULL = "reportAttributes can't be null";
private static final String NAME_CANNOT_BE_NULL = "name can't be null";
@@ -145,10 +155,11 @@ public class ComponentImpl implements Component {

private final Type type;
private Status status;
private ProjectAttributes projectAttributes;
private ReportAttributes reportAttributes;
private String uuid;
private String dbKey;
private String key;
private String publicKey;
private String name;
private String description;
private FileAttributes fileAttributes;
@@ -158,11 +169,6 @@ public class ComponentImpl implements Component {
this.type = requireNonNull(type, "type can't be null");
}

public Builder setReportAttributes(ReportAttributes reportAttributes) {
this.reportAttributes = requireNonNull(reportAttributes, REPORT_ATTRIBUTES_CANNOT_BE_NULL);
return this;
}

public Builder setUuid(String s) {
this.uuid = requireNonNull(s, UUID_CANNOT_BE_NULL);
return this;
@@ -178,13 +184,13 @@ public class ComponentImpl implements Component {
return this;
}

public Builder setKey(String s) {
this.key = requireNonNull(s, KEY_CANNOT_BE_NULL);
public Builder setDbKey(String s) {
this.dbKey = requireNonNull(s, DB_KEY_CANNOT_BE_NULL);
return this;
}

public Builder setPublicKey(String publicKey) {
this.publicKey = requireNonNull(publicKey);
public Builder setKey(String key) {
this.key = requireNonNull(key, KEY_CANNOT_BE_NULL);
return this;
}

@@ -198,6 +204,17 @@ public class ComponentImpl implements Component {
return this;
}

public Builder setProjectAttributes(ProjectAttributes projectAttributes) {
checkProjectAttributes(projectAttributes);
this.projectAttributes = projectAttributes;
return this;
}

public Builder setReportAttributes(ReportAttributes reportAttributes) {
this.reportAttributes = requireNonNull(reportAttributes, REPORT_ATTRIBUTES_CANNOT_BE_NULL);
return this;
}

public Builder setFileAttributes(@Nullable FileAttributes fileAttributes) {
this.fileAttributes = fileAttributes;
return this;
@@ -214,23 +231,32 @@ public class ComponentImpl implements Component {
public ComponentImpl build() {
requireNonNull(reportAttributes, REPORT_ATTRIBUTES_CANNOT_BE_NULL);
requireNonNull(uuid, UUID_CANNOT_BE_NULL);
requireNonNull(key, KEY_CANNOT_BE_NULL);
requireNonNull(dbKey, DB_KEY_CANNOT_BE_NULL);
requireNonNull(name, NAME_CANNOT_BE_NULL);
requireNonNull(status, STATUS_CANNOT_BE_NULL);
checkProjectAttributes(this.projectAttributes);
return new ComponentImpl(this);
}

private void checkProjectAttributes(@Nullable ProjectAttributes projectAttributes) {
checkArgument(type != Type.PROJECT ^ projectAttributes != null, "ProjectAttributes must and can only be set for type PROJECT");
}
}

@Override
public String toString() {
return "ComponentImpl{" +
"key='" + key + '\'' +
", type=" + type +
", uuid='" + uuid + '\'' +
"type=" + type +
", status=" + status +
", name='" + name + '\'' +
", dbKey='" + dbKey + '\'' +
", key='" + key + '\'' +
", uuid='" + uuid + '\'' +
", description='" + description + '\'' +
", fileAttributes=" + fileAttributes +
", children=" + children +
", projectAttributes=" + projectAttributes +
", reportAttributes=" + reportAttributes +
", fileAttributes=" + fileAttributes +
'}';
}


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

@@ -101,12 +101,11 @@ public class ComponentTreeBuilder {
String projectPublicKey = publicKeyGenerator.generateKey(component, null);
ComponentImpl.Builder builder = ComponentImpl.builder(Component.Type.PROJECT)
.setUuid(uuid)
.setKey(projectKey)
.setPublicKey(projectPublicKey)
.setDbKey(projectKey)
.setKey(projectPublicKey)
.setStatus(convertStatus(component.getStatus()))
.setReportAttributes(createAttributesBuilder(component, scmBasePath)
.setVersion(createProjectVersion(component))
.build())
.setProjectAttributes(new ProjectAttributes(createProjectVersion(component)))
.setReportAttributes(createAttributesBuilder(component, scmBasePath).build())
.addChildren(buildChildren(component, component, scmBasePath));
setNameAndDescription(component, builder);
return builder.build();
@@ -116,8 +115,8 @@ public class ComponentTreeBuilder {
String modulePublicKey = publicKeyGenerator.generateKey(component, null);
return ComponentImpl.builder(Component.Type.MODULE)
.setUuid(uuidSupplier.apply(moduleKey))
.setKey(moduleKey)
.setPublicKey(modulePublicKey)
.setDbKey(moduleKey)
.setKey(modulePublicKey)
.setName(nameOfOthers(component, modulePublicKey))
.setStatus(convertStatus(component.getStatus()))
.setDescription(trimToNull(component.getDescription()))
@@ -131,8 +130,8 @@ public class ComponentTreeBuilder {
String publicKey = publicKeyGenerator.generateKey(closestModule, component);
return ComponentImpl.builder(convertDirOrFileType(component.getType()))
.setUuid(uuidSupplier.apply(key))
.setKey(key)
.setPublicKey(publicKey)
.setDbKey(key)
.setKey(publicKey)
.setName(nameOfOthers(component, publicKey))
.setStatus(convertStatus(component.getStatus()))
.setDescription(trimToNull(component.getDescription()))
@@ -153,8 +152,8 @@ public class ComponentTreeBuilder {
private static ComponentImpl.Builder changedComponentBuilder(Component component) {
return ComponentImpl.builder(component.getType())
.setUuid(component.getUuid())
.setDbKey(component.getDbKey())
.setKey(component.getKey())
.setPublicKey(component.getPublicKey())
.setStatus(component.getStatus())
.setReportAttributes(component.getReportAttributes())
.setName(component.getName())
@@ -181,6 +180,7 @@ public class ComponentTreeBuilder {

private static Component buildChangedProject(Component component) {
return changedComponentBuilder(component)
.setProjectAttributes(new ProjectAttributes(component.getProjectAttributes().getVersion()))
.addChildren(buildChangedComponentChildren(component))
.build();
}
@@ -268,7 +268,6 @@ public class ComponentTreeBuilder {

private static ReportAttributes.Builder createAttributesBuilder(ScannerReport.Component component, @Nullable String scmBasePath) {
return ReportAttributes.newBuilder(component.getRef())
.setVersion(trimToNull(component.getVersion()))
.setPath(trimToNull(component.getPath()))
.setScmPath(computeScmPath(scmBasePath, component.getProjectRelativePath()));
}

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

@@ -38,7 +38,7 @@ public final class DepthTraversalTypeAwareCrawler implements ComponentCrawler {
try {
visitImpl(component);
} catch (RuntimeException e) {
VisitException.rethrowOrWrap(e, "Visit of Component {key=%s,uuid=%s,type=%s} failed", component.getKey(), component.getUuid(), component.getType());
VisitException.rethrowOrWrap(e, "Visit of Component {key=%s,uuid=%s,type=%s} failed", component.getDbKey(), component.getUuid(), component.getType());
}
}


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

@@ -46,7 +46,7 @@ public final class MapBasedDbIdsRepository<T> implements MutableDbIdsRepository
T ref = componentToKey.apply(component);
Long existingComponentId = componentIdsByRef.get(ref);
checkState(existingComponentId == null,
"Component id '%s' is already registered in repository for Component '%s', can not set new id '%s'", existingComponentId, component.getKey(), componentId);
"Component id '%s' is already registered in repository for Component '%s', can not set new id '%s'", existingComponentId, component.getDbKey(), componentId);
componentIdsByRef.put(ref, componentId);
return this;
}
@@ -55,7 +55,7 @@ public final class MapBasedDbIdsRepository<T> implements MutableDbIdsRepository
public long getComponentId(Component component) {
T ref = componentToKey.apply(component);
Long componentId = componentIdsByRef.get(ref);
checkState(componentId != null, "No component id registered in repository for Component '%s'", component.getKey());
checkState(componentId != null, "No component id registered in repository for Component '%s'", component.getDbKey());
return componentId;
}


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

@@ -52,7 +52,7 @@ public final class PathAwareCrawler<T> implements ComponentCrawler {
VisitException.rethrowOrWrap(
e,
"Visit failed for Component {key=%s,type=%s} %s",
component.getKey(), component.getType(), new ComponentPathPrinter<>(stack));
component.getDbKey(), component.getType(), new ComponentPathPrinter<>(stack));
}
}

@@ -174,7 +174,7 @@ public final class PathAwareCrawler<T> implements ComponentCrawler {
@Override
@Nonnull
public String apply(@Nonnull PathAwareVisitor.PathElement<?> input) {
return format("%s(type=%s)", input.getComponent().getKey(), input.getComponent().getType());
return format("%s(type=%s)", input.getComponent().getDbKey(), input.getComponent().getType());
}
}
}

+ 41
- 0
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectAttributes.java View File

@@ -0,0 +1,41 @@
/*
* SonarQube
* Copyright (C) 2009-2018 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;

import java.util.Objects;

public class ProjectAttributes {
private final String version;

public ProjectAttributes(String version) {
this.version = Objects.requireNonNull(version, "version can't be null");
}

public String getVersion() {
return version;
}

@Override
public String toString() {
return "ProjectAttributes{" +
"version='" + version + '\'' +
'}';
}
}

+ 0
- 19
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ReportAttributes.java View File

@@ -31,15 +31,12 @@ import javax.annotation.concurrent.Immutable;
public class ReportAttributes {
private final int ref;
@CheckForNull
private final String version;
@CheckForNull
private final String path;
@CheckForNull
private final String scmPath;

private ReportAttributes(Builder builder) {
this.ref = builder.ref;
this.version = builder.version;
this.path = builder.path;
this.scmPath = builder.scmPath;
}
@@ -51,8 +48,6 @@ public class ReportAttributes {
public static class Builder {
private final int ref;
@CheckForNull
private String version;
@CheckForNull
private String path;
@CheckForNull
private String scmPath;
@@ -61,11 +56,6 @@ public class ReportAttributes {
this.ref = ref;
}

public Builder setVersion(@Nullable String version) {
this.version = version;
return this;
}

public Builder setPath(@Nullable String path) {
this.path = path;
return this;
@@ -88,14 +78,6 @@ public class ReportAttributes {
return ref;
}

/**
* The project or module version as defined in the batch report.
*/
@CheckForNull
public String getVersion() {
return this.version;
}

/**
* The path of the report component, must be non null for module, directories and files.
*/
@@ -118,7 +100,6 @@ public class ReportAttributes {
public String toString() {
return "ReportAttributes{" +
"ref=" + ref +
", version='" + version + '\'' +
", path='" + path + '\'' +
", scmPath='" + scmPath + '\'' +
'}';

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

@@ -74,7 +74,7 @@ public class VisitorsCrawler implements ComponentCrawler {
VisitException.rethrowOrWrap(
e,
"Visit of Component {key=%s,type=%s} failed",
component.getKey(), component.getType());
component.getDbKey(), component.getType());
}
}

@@ -113,7 +113,7 @@ public class VisitorsCrawler implements ComponentCrawler {

private void visitNode(Component component, VisitorWrapper visitor) {
Profiler profiler = Profiler.create(Loggers.get(visitor.getWrappedVisitor().getClass()))
.startTrace("Visiting component {}", component.getKey());
.startTrace("Visiting component {}", component.getDbKey());
visitor.visitAny(component);
switch (component.getType()) {
case PROJECT:

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

@@ -169,7 +169,7 @@ public final class Duplication {
return "";
}
if (duplicate instanceof InProjectDuplicate) {
return ((InProjectDuplicate) duplicate).getFile().getKey();
return ((InProjectDuplicate) duplicate).getFile().getDbKey();
}
if (duplicate instanceof CrossProjectDuplicate) {
return ((CrossProjectDuplicate) duplicate).getFileKey();

+ 2
- 3
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImpl.java View File

@@ -24,7 +24,6 @@ import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.Collections;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.Component;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -40,7 +39,7 @@ public class DuplicationRepositoryImpl implements DuplicationRepository {
public Iterable<Duplication> getDuplications(Component file) {
checkFileComponentArgument(file);

Collection<Duplication> res = this.duplications.asMap().get(file.getKey());
Collection<Duplication> res = this.duplications.asMap().get(file.getDbKey());
if (res == null) {
return Collections.emptyList();
}
@@ -52,7 +51,7 @@ public class DuplicationRepositoryImpl implements DuplicationRepository {
checkFileComponentArgument(file);
checkNotNull(duplication, "duplication can not be null");

duplications.put(file.getKey(), duplication);
duplications.put(file.getDbKey(), duplication);
}

private static void checkFileComponentArgument(Component file) {

+ 2
- 3
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplications.java View File

@@ -38,7 +38,6 @@ import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.CloneIndex;
import org.sonar.duplications.index.ClonePart;
import org.sonar.duplications.index.PackedMemoryCloneIndex;
import org.sonar.ce.task.projectanalysis.component.Component;

import static com.google.common.collect.FluentIterable.from;

@@ -88,7 +87,7 @@ public class IntegrateCrossProjectDuplications {
for (CloneGroup duplication : duplications) {
cloneGroupCount++;
if (cloneGroupCount > MAX_CLONE_GROUP_PER_FILE) {
LOGGER.warn("Too many duplication groups on file {}. Keeping only the first {} groups.", file.getKey(), MAX_CLONE_GROUP_PER_FILE);
LOGGER.warn("Too many duplication groups on file {}. Keeping only the first {} groups.", file.getDbKey(), MAX_CLONE_GROUP_PER_FILE);
break;
}
addDuplication(file, duplication);
@@ -170,7 +169,7 @@ public class IntegrateCrossProjectDuplications {
public boolean apply(@Nonnull ClonePart input) {
if (counter == MAX_CLONE_PART_PER_GROUP) {
LOGGER.warn("Too many duplication references on file {} for block at line {}. Keeping only the first {} references.",
file.getKey(), originPart.getStartLine(), MAX_CLONE_PART_PER_GROUP);
file.getDbKey(), originPart.getStartLine(), MAX_CLONE_PART_PER_GROUP);
}
boolean res = counter <= MAX_CLONE_GROUP_PER_FILE;
counter++;

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

@@ -180,7 +180,7 @@ public class FileMoveDetectionStep implements ComputationStep {
new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) {
@Override
public void visitFile(Component file) {
builder.put(file.getKey(), file);
builder.put(file.getDbKey(), file);
}
}).visit(root);
return builder.build();

+ 3
- 4
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImpl.java View File

@@ -23,7 +23,6 @@ import com.google.common.base.Optional;
import java.util.HashMap;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.Component;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
@@ -38,11 +37,11 @@ public class MutableMovedFilesRepositoryImpl implements MutableMovedFilesReposit
requireNonNull(originalFile, "originalFile can't be null");
checkArgument(file.getType() == Component.Type.FILE, "file must be of type FILE");

OriginalFile existingOriginalFile = originalFiles.get(file.getKey());
OriginalFile existingOriginalFile = originalFiles.get(file.getDbKey());
checkState(existingOriginalFile == null || existingOriginalFile.equals(originalFile),
"Original file %s already registered for file %s. Unable to register %s.", existingOriginalFile, file, originalFile);
if (existingOriginalFile == null) {
originalFiles.put(file.getKey(), originalFile);
originalFiles.put(file.getDbKey(), originalFile);
}
}

@@ -53,6 +52,6 @@ public class MutableMovedFilesRepositoryImpl implements MutableMovedFilesReposit
return Optional.absent();
}

return Optional.fromNullable(originalFiles.get(file.getKey()));
return Optional.fromNullable(originalFiles.get(file.getDbKey()));
}
}

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

@@ -69,7 +69,7 @@ public class IntegrateIssuesVisitor extends TypeAwareVisitorAdapter {
copyIssues(component, tracking.issuesToCopy(), cacheAppender);
issueVisitors.afterComponent(component);
} catch (Exception e) {
throw new IllegalStateException(String.format("Fail to process issues of component '%s'", component.getKey()), e);
throw new IllegalStateException(String.format("Fail to process issues of component '%s'", component.getDbKey()), e);
}
}


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

@@ -25,7 +25,6 @@ import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile;
import org.sonar.server.issue.IssueFieldsSetter;
@@ -60,7 +59,7 @@ public class MovedIssueVisitor extends IssueVisitor {
// changes the issue's component uuid, add a change and set issue as changed to enforce it is persisted to DB
issueUpdater.setIssueMoved(issue, component.getUuid(), IssueChangeContext.createUser(new Date(analysisMetadataHolder.getAnalysisDate()), null));
// other fields (such as module, modulePath, componentKey) are read-only and set/reset for consistency only
issue.setComponentKey(component.getPublicKey());
issue.setComponentKey(component.getKey());
issue.setModuleUuid(null);
issue.setModuleUuidPath(null);
}

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

@@ -52,7 +52,7 @@ public class ShortBranchIssuesLoader {
}

public Collection<ShortBranchIssue> loadCandidateIssuesForMergingInTargetBranch(Component component) {
String componentKey = ComponentDto.removeBranchAndPullRequestFromKey(component.getKey());
String componentKey = ComponentDto.removeBranchAndPullRequestFromKey(component.getDbKey());
Set<String> uuids = shortBranchComponentsWithIssues.getUuids(componentKey);
if (uuids.isEmpty()) {
return Collections.emptyList();

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

@@ -46,7 +46,7 @@ public class TrackerMergeBranchInputFactory {
}

public Input<DefaultIssue> create(Component component) {
String mergeBranchComponentUuid = mergeBranchComponentUuids.getUuid(component.getKey());
String mergeBranchComponentUuid = mergeBranchComponentUuids.getUuid(component.getDbKey());
return new MergeLazyInput(component.getType(), mergeBranchComponentUuid);
}


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

@@ -259,9 +259,9 @@ public class TrackerRawInputFactory {
issue.setResolution(null);
issue.setStatus(Issue.STATUS_OPEN);
issue.setComponentUuid(component.getUuid());
issue.setComponentKey(component.getPublicKey());
issue.setComponentKey(component.getKey());
issue.setProjectUuid(treeRootHolder.getRoot().getUuid());
issue.setProjectKey(treeRootHolder.getRoot().getPublicKey());
issue.setProjectKey(treeRootHolder.getRoot().getKey());
return issue;
}


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

@@ -32,8 +32,6 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.FluentIterable.from;
@@ -80,7 +78,7 @@ public final class MapBasedRawMeasureRepository<T> implements MeasureRepository
throw new UnsupportedOperationException(
format(
"a measure can be set only once for a specific Component (key=%s), Metric (key=%s). Use update method",
component.getKey(),
component.getDbKey(),
metric.getKey()));
}
add(component, metric, measure, OverridePolicy.OVERRIDE);
@@ -96,7 +94,7 @@ public final class MapBasedRawMeasureRepository<T> implements MeasureRepository
throw new UnsupportedOperationException(
format(
"a measure can be updated only if one already exists for a specific Component (key=%s), Metric (key=%s). Use add method",
component.getKey(),
component.getDbKey(),
metric.getKey()));
}
add(component, metric, measure, OverridePolicy.OVERRIDE);

+ 1
- 3
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoader.java View File

@@ -29,8 +29,6 @@ import org.sonar.db.DbSession;
import org.sonar.db.source.FileSourceDto;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.MergeBranchComponentUuids;

public class ScmInfoDbLoader {
private static final Logger LOGGER = Loggers.get(ScmInfoDbLoader.class);
@@ -69,7 +67,7 @@ public class ScmInfoDbLoader {
// at this point, it's the first analysis but had copyFromPrevious flag true
Branch branch = analysisMetadataHolder.getBranch();
if (branch.getMergeBranchUuid().isPresent()) {
return Optional.ofNullable(mergeBranchComponentUuid.getUuid(file.getKey()));
return Optional.ofNullable(mergeBranchComponentUuid.getUuid(file.getDbKey()));
}

return Optional.empty();

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

@@ -72,7 +72,7 @@ public class ScmInfoRepositoryImpl implements ScmInfoRepository {
ScannerReport.Changesets changesets = scannerReportReader.readChangesets(component.getReportAttributes().getRef());

if (changesets == null) {
LOGGER.trace("No SCM info for file '{}'", component.getKey());
LOGGER.trace("No SCM info for file '{}'", component.getDbKey());
// SCM not available. It might have been available before - copy information for unchanged lines but don't keep author and revision.
return generateAndMergeDb(component, false);
}
@@ -85,7 +85,7 @@ public class ScmInfoRepositoryImpl implements ScmInfoRepository {
}

private static Optional<ScmInfo> getScmInfoFromReport(Component file, ScannerReport.Changesets changesets) {
LOGGER.trace("Reading SCM info from report for file '{}'", file.getKey());
LOGGER.trace("Reading SCM info from report for file '{}'", file.getDbKey());
return Optional.of(new ReportScmInfo(changesets));
}


+ 4
- 5
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImpl.java View File

@@ -25,7 +25,6 @@ import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.hash.SourceHashComputer;
import org.sonar.core.util.CloseableIterator;
import org.sonar.ce.task.projectanalysis.component.Component;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
@@ -44,12 +43,12 @@ public class SourceHashRepositoryImpl implements SourceHashRepository {
@Override
public String getRawSourceHash(Component file) {
checkComponentArgument(file);
if (rawSourceHashesByKey.containsKey(file.getKey())) {
return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey()));
if (rawSourceHashesByKey.containsKey(file.getDbKey())) {
return checkSourceHash(file.getDbKey(), rawSourceHashesByKey.get(file.getDbKey()));
} else {
String newSourceHash = computeRawSourceHash(file);
rawSourceHashesByKey.put(file.getKey(), newSourceHash);
return checkSourceHash(file.getKey(), newSourceHash);
rawSourceHashesByKey.put(file.getDbKey(), newSourceHash);
return checkSourceHash(file.getDbKey(), newSourceHash);
}
}


+ 1
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/HighlightingLineReader.java View File

@@ -78,7 +78,7 @@ public class HighlightingLineReader implements LineReader {
processHighlightings(lineBuilder);
} catch (RangeOffsetConverterException e) {
isHighlightingValid = false;
LOG.warn(format("Inconsistency detected in Highlighting data. Highlighting will be ignored for file '%s'", file.getKey()), e);
LOG.warn(format("Inconsistency detected in Highlighting data. Highlighting will be ignored for file '%s'", file.getDbKey()), e);
}
}


+ 1
- 1
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/SymbolsLineReader.java View File

@@ -70,7 +70,7 @@ public class SymbolsLineReader implements LineReader {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
areSymbolsValid = false;
LOG.warn(format("Inconsistency detected in Symbols data. Symbols will be ignored for file '%s'", file.getKey()), e);
LOG.warn(format("Inconsistency detected in Symbols data. Symbols will be ignored for file '%s'", file.getDbKey()), e);
}
}


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

@@ -82,7 +82,7 @@ public class DuplicationDataMeasuresStep implements ComputationStep {
}

private void computeDuplications(Component component, Iterable<Duplication> duplications) {
String duplicationXml = createXmlDuplications(component.getKey(), duplications);
String duplicationXml = createXmlDuplications(component.getDbKey(), duplications);
measureRepository.add(
component,
duplicationDataMetric,
@@ -110,7 +110,7 @@ public class DuplicationDataMeasuresStep implements ComputationStep {
appendDuplication(xml, componentKey, duplicate);
} else if (duplicate instanceof InProjectDuplicate) {
// Duplication is on a different file
appendDuplication(xml, ((InProjectDuplicate) duplicate).getFile().getKey(), duplicate);
appendDuplication(xml, ((InProjectDuplicate) duplicate).getFile().getDbKey(), duplicate);
} else if (duplicate instanceof CrossProjectDuplicate) {
// componentKey is only set for cross project duplications
String crossProjectComponentKey = ((CrossProjectDuplicate) duplicate).getFileKey();

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

@@ -99,7 +99,7 @@ public class LoadCrossProjectDuplicationsRepositoryStep implements ComputationSt
List<CpdTextBlock> cpdTextBlocks;
try (CloseableIterator<CpdTextBlock> blocksIt = reportReader.readCpdTextBlocks(file.getReportAttributes().getRef())) {
cpdTextBlocks = newArrayList(blocksIt);
LOGGER.trace("Found {} cpd blocks on file {}", cpdTextBlocks.size(), file.getKey());
LOGGER.trace("Found {} cpd blocks on file {}", cpdTextBlocks.size(), file.getDbKey());
if (cpdTextBlocks.isEmpty()) {
return;
}
@@ -112,8 +112,8 @@ public class LoadCrossProjectDuplicationsRepositoryStep implements ComputationSt
}

Collection<Block> duplicatedBlocks = from(dtos).transform(DtoToBlock.INSTANCE).toList();
Collection<Block> originBlocks = from(cpdTextBlocks).transform(new CpdTextBlockToBlock(file.getKey())).toList();
LOGGER.trace("Found {} duplicated cpd blocks on file {}", duplicatedBlocks.size(), file.getKey());
Collection<Block> originBlocks = from(cpdTextBlocks).transform(new CpdTextBlockToBlock(file.getDbKey())).toList();
LOGGER.trace("Found {} duplicated cpd blocks on file {}", duplicatedBlocks.size(), file.getDbKey());

integrateCrossProjectDuplications.computeCpd(file, originBlocks, duplicatedBlocks);
}

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

@@ -84,9 +84,8 @@ public class LoadPeriodsStep implements ComputationStep {

@CheckForNull
private Period buildPeriod(Component projectOrView, DbSession session) {
boolean isReportType = projectOrView.getType().isReportType();
PeriodResolver periodResolver = new PeriodResolver(dbClient, session, projectOrView.getUuid(), analysisMetadataHolder.getAnalysisDate(),
isReportType ? projectOrView.getReportAttributes().getVersion() : null);
projectOrView.getProjectAttributes().getVersion());

Configuration config = configRepository.getConfiguration();
Period period = periodResolver.resolve(config);

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

@@ -76,14 +76,14 @@ public class PersistAnalysisStep implements ComputationStep {

@Override
public void visitProject(Component project) {
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), project, true);
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), project);
updateSnapshotPeriods(snapshot);
persist(snapshot, dbSession);
}

@Override
public void visitView(Component view) {
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), view, false);
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), view);
updateSnapshotPeriods(snapshot);
persist(snapshot, dbSession);
}
@@ -98,11 +98,11 @@ public class PersistAnalysisStep implements ComputationStep {
snapshotDto.setPeriodDate(period.getSnapshotDate());
}

private SnapshotDto createAnalysis(String snapshotUuid, Component component, boolean setVersion) {
private SnapshotDto createAnalysis(String snapshotUuid, Component component) {
String componentUuid = component.getUuid();
return new SnapshotDto()
.setUuid(snapshotUuid)
.setVersion(setVersion ? component.getReportAttributes().getVersion() : null)
.setVersion(component.getType() == Component.Type.PROJECT ? component.getProjectAttributes().getVersion() : null)
.setComponentUuid(componentUuid)
.setLast(false)
.setStatus(SnapshotDto.STATUS_UNPROCESSED)

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

@@ -143,7 +143,7 @@ public class PersistComponentsStep implements ComputationStep {
}

private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByKeys) {
String rootKey = root.getKey();
String rootKey = root.getDbKey();
ComponentDto rootDto = existingDtosByKeys.get(rootKey);
if (rootDto == null) {
if (Component.Type.VIEW == root.getType()) {
@@ -159,7 +159,7 @@ public class PersistComponentsStep implements ComputationStep {
* disabled components.
*/
private Map<String, ComponentDto> indexExistingDtosByKey(DbSession session) {
return dbClient.componentDao().selectAllComponentsFromProjectKey(session, treeRootHolder.getRoot().getKey())
return dbClient.componentDao().selectAllComponentsFromProjectKey(session, treeRootHolder.getRoot().getDbKey())
.stream()
.collect(Collectors.toMap(ComponentDto::getDbKey, Function.identity()));
}
@@ -386,7 +386,7 @@ public class PersistComponentsStep implements ComputationStep {
}

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

ComponentDto componentDto = new ComponentDto();

+ 5
- 7
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStep.java View File

@@ -101,13 +101,11 @@ public class PersistEventsStep implements ComputationStep {
}

private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
String version = component.getReportAttributes().getVersion();
if (version != null) {
deletePreviousEventsHavingSameVersion(session, version, component);
dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
.setName(version)
.setCategory(EventDto.CATEGORY_VERSION));
}
String version = component.getProjectAttributes().getVersion();
deletePreviousEventsHavingSameVersion(session, version, component);
dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
.setName(version)
.setCategory(EventDto.CATEGORY_VERSION));
}

private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {

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

@@ -97,7 +97,7 @@ public class PersistFileSourcesStep implements ComputationStep {
FileSourceDataComputer.Data fileSourceData = fileSourceDataComputer.compute(file);
persistSource(fileSourceData, file);
} catch (Exception e) {
throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getKey()), e);
throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getDbKey()), e);
}
}


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

@@ -98,7 +98,7 @@ public class PersistTestsStep implements ComputationStep {
this.session = session;
this.existingFileSourcesByUuid = new HashMap<>();
this.projectUuid = treeRootHolder.getRoot().getUuid();
this.projectKey = treeRootHolder.getRoot().getKey();
this.projectKey = treeRootHolder.getRoot().getDbKey();
session.select("org.sonar.db.source.FileSourceMapper.selectHashesForProject",
ImmutableMap.of("projectUuid", treeRootHolder.getRoot().getUuid(), "dataType", Type.TEST),
context -> {
@@ -118,7 +118,7 @@ public class PersistTestsStep implements ComputationStep {
Multimap<String, DbFileSources.Test.Builder> testsByName = buildDbTests(component.getReportAttributes().getRef());
Table<String, String, DbFileSources.Test.CoveredFile.Builder> coveredFilesByName = loadCoverageDetails(component.getReportAttributes().getRef());
List<DbFileSources.Test> tests = addCoveredFilesToTests(testsByName, coveredFilesByName);
if (checkIfThereAreUnprocessedCoverageDetails(testsByName, coveredFilesByName, component.getKey())) {
if (checkIfThereAreUnprocessedCoverageDetails(testsByName, coveredFilesByName, component.getDbKey())) {
hasUnprocessedCoverageDetails = true;
}


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

@@ -100,7 +100,7 @@ public class QualityGateEventsStep implements ComputationStep {
}

if (!baseMeasure.get().hasQualityGateStatus()) {
LOGGER.warn(String.format("Previous Quality gate status for project %s is not a supported value. Can not compute Quality Gate event", project.getKey()));
LOGGER.warn(String.format("Previous Quality gate status for project %s is not a supported value. Can not compute Quality Gate event", project.getDbKey()));
checkNewQualityGate(project, rawStatus);
return;
}
@@ -131,8 +131,8 @@ public class QualityGateEventsStep implements ComputationStep {
Notification notification = new Notification("alerts")
.setDefaultMessage(String.format("Alert on %s: %s", project.getName(), label))
.setFieldValue("projectName", project.getName())
.setFieldValue("projectKey", project.getPublicKey())
.setFieldValue("projectVersion", project.getReportAttributes().getVersion())
.setFieldValue("projectKey", project.getKey())
.setFieldValue("projectVersion", project.getProjectAttributes().getVersion())
.setFieldValue("alertName", label)
.setFieldValue("alertText", rawStatus.getText())
.setFieldValue("alertLevel", rawStatus.getStatus().toString())

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

@@ -154,8 +154,8 @@ public class SendIssueNotificationsStep implements ComputationStep {
changeNotification.setRuleName(rules.getByKey(issue.ruleKey()).getName());
changeNotification.setIssue(issue);
changeNotification.setAssignee(usersDtoByUuids.get(issue.assignee()));
changeNotification.setProject(project.getPublicKey(), project.getName(), getBranchName(), getPullRequest());
getComponentKey(issue).ifPresent(c -> changeNotification.setComponent(c.getPublicKey(), c.getName()));
changeNotification.setProject(project.getKey(), project.getName(), getBranchName(), getPullRequest());
getComponentKey(issue).ifPresent(c -> changeNotification.setComponent(c.getKey(), c.getName()));
notificationStatistics.issueChangesDeliveries += service.deliver(changeNotification);
notificationStatistics.issueChanges++;
}
@@ -164,8 +164,8 @@ public class SendIssueNotificationsStep implements ComputationStep {
NewIssuesStatistics.Stats globalStatistics = statistics.globalStatistics();
NewIssuesNotification notification = newIssuesNotificationFactory
.newNewIssuesNotification()
.setProject(project.getPublicKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getReportAttributes().getVersion())
.setProject(project.getKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getProjectAttributes().getVersion())
.setAnalysisDate(new Date(analysisDate))
.setStatistics(project.getName(), globalStatistics)
.setDebt(Duration.create(globalStatistics.effort().getOnLeak()));
@@ -185,8 +185,8 @@ public class SendIssueNotificationsStep implements ComputationStep {
.newMyNewIssuesNotification()
.setAssignee(userDtoByUuid.get(assigneeUuid));
myNewIssuesNotification
.setProject(project.getPublicKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getReportAttributes().getVersion())
.setProject(project.getKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getProjectAttributes().getVersion())
.setAnalysisDate(new Date(analysisDate))
.setStatistics(project.getName(), assigneeStatistics)
.setDebt(Duration.create(assigneeStatistics.effort().getOnLeak()));
@@ -212,7 +212,7 @@ public class SendIssueNotificationsStep implements ComputationStep {
new TypeAwareVisitorAdapter(CrawlerDepthLimit.LEAVES, POST_ORDER) {
@Override
public void visitAny(Component component) {
builder.put(component.getKey(), component);
builder.put(component.getDbKey(), component);
}
}).visit(this.treeRootHolder.getRoot());
this.componentsByDbKey = builder.build();

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

@@ -76,7 +76,7 @@ public class ValidateProjectStep implements ComputationStep {
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
Component root = treeRootHolder.getRoot();
List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getKey());
List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getDbKey());
Map<String, ComponentDto> baseModulesByKey = from(baseModules).uniqueIndex(ComponentDto::getDbKey);
ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
new DepthTraversalTypeAwareCrawler(visitor).visit(root);
@@ -111,7 +111,7 @@ public class ValidateProjectStep implements ComputationStep {
@Override
public void visitProject(Component rawProject) {
this.rawProject = rawProject;
String rawProjectKey = rawProject.getKey();
String rawProjectKey = rawProject.getDbKey();

Optional<ComponentDto> baseProject = loadBaseComponent(rawProjectKey);
validateAnalysisDate(baseProject);
@@ -132,8 +132,8 @@ public class ValidateProjectStep implements ComputationStep {

@Override
public void visitModule(Component rawModule) {
String rawProjectKey = rawProject.getKey();
String rawModuleKey = rawModule.getKey();
String rawProjectKey = rawProject.getDbKey();
String rawModuleKey = rawModule.getDbKey();
validateBatchKey(rawModule);

Optional<ComponentDto> baseModule = loadBaseComponent(rawModuleKey);

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

@@ -70,7 +70,7 @@ public class BranchPersisterImplTest {
treeRootHolder.setRoot(BRANCH);

// add main branch in project table and in metadata
ComponentDto dto = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getKey());
ComponentDto dto = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getDbKey());
analysisMetadataHolder.setProject(Project.from(dto));
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), dto);

@@ -91,7 +91,7 @@ public class BranchPersisterImplTest {
treeRootHolder.setRoot(BRANCH);

// add main branch in project table and in metadata
ComponentDto dto = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getKey());
ComponentDto dto = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), MAIN.getUuid()).setDbKey(MAIN.getDbKey());
analysisMetadataHolder.setProject(Project.from(dto));
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), dto);


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

@@ -35,7 +35,7 @@ class CallRecorderPathAwareVisitor extends PathAwareVisitorAdapter<Integer> {
super(maxDepth, order, new SimpleStackElementFactory<Integer>() {
@Override
public Integer createForAny(Component component) {
return component.getType().isReportType() ? component.getReportAttributes().getRef() : Integer.valueOf(component.getKey());
return component.getType().isReportType() ? component.getReportAttributes().getRef() : Integer.valueOf(component.getDbKey());
}
});
}
@@ -86,7 +86,7 @@ class CallRecorderPathAwareVisitor extends PathAwareVisitorAdapter<Integer> {
}

private static PathAwareCallRecord viewsCallRecord(Component component, Path<Integer> path, String method) {
return PathAwareCallRecord.viewsCallRecord(method, component.getKey(), path.current(), getParent(path), path.root(),
return PathAwareCallRecord.viewsCallRecord(method, component.getDbKey(), path.current(), getParent(path), path.root(),
toValueList(path));
}


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

@@ -74,7 +74,7 @@ class CallRecorderTypeAwareVisitor extends TypeAwareVisitorAdapter {
}

private static CallRecord viewsCallRecord(Component component, String method) {
return CallRecord.viewsCallRecord(method, component.getKey());
return CallRecord.viewsCallRecord(method, component.getDbKey());
}

}

+ 18
- 14
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java View File

@@ -30,6 +30,7 @@ import static com.google.common.base.Strings.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ComponentImpl.builder;

public class ComponentImplTest {
@@ -44,7 +45,7 @@ public class ComponentImplTest {
public void verify_key_uuid_and_name() {
ComponentImpl component = buildSimpleComponent(FILE, KEY).setUuid(UUID).setName("name").build();

assertThat(component.getKey()).isEqualTo(KEY);
assertThat(component.getDbKey()).isEqualTo(KEY);
assertThat(component.getUuid()).isEqualTo(UUID);
assertThat(component.getName()).isEqualTo("name");
}
@@ -69,7 +70,7 @@ public class ComponentImplTest {

builder(Component.Type.DIRECTORY)
.setName("DIR")
.setKey(KEY)
.setDbKey(KEY)
.setUuid(UUID)
.setReportAttributes(ReportAttributes.newBuilder(1).build())
.build();
@@ -86,7 +87,7 @@ public class ComponentImplTest {
public void set_uuid_throws_NPE_if_component_arg_is_Null() {
expectedException.expect(NullPointerException.class);

builder(FILE).setKey(null);
builder(FILE).setDbKey(null);
}

@Test
@@ -100,7 +101,7 @@ public class ComponentImplTest {
public void build_without_uuid_throws_NPE_if_component_arg_is_Null() {
expectedException.expect(NullPointerException.class);

builder(FILE).setKey(KEY).build();
builder(FILE).setDbKey(KEY).build();
}

@Test
@@ -198,14 +199,14 @@ public class ComponentImplTest {
public void build_with_child() {
ComponentImpl child = builder(FILE)
.setName("CHILD_NAME")
.setKey("CHILD_KEY")
.setDbKey("CHILD_KEY")
.setUuid("CHILD_UUID")
.setStatus(Status.UNAVAILABLE)
.setReportAttributes(ReportAttributes.newBuilder(2).build())
.build();
ComponentImpl componentImpl = builder(Component.Type.DIRECTORY)
.setName("DIR")
.setKey(KEY)
.setDbKey(KEY)
.setUuid(UUID)
.setStatus(Status.UNAVAILABLE)
.setReportAttributes(ReportAttributes.newBuilder(1).build())
@@ -214,7 +215,7 @@ public class ComponentImplTest {

assertThat(componentImpl.getChildren()).hasSize(1);
Component childReloaded = componentImpl.getChildren().iterator().next();
assertThat(childReloaded.getKey()).isEqualTo("CHILD_KEY");
assertThat(childReloaded.getDbKey()).isEqualTo("CHILD_KEY");
assertThat(childReloaded.getUuid()).isEqualTo("CHILD_UUID");
assertThat(childReloaded.getType()).isEqualTo(FILE);
}
@@ -237,13 +238,16 @@ public class ComponentImplTest {
assertThat(builder.build().hashCode()).isEqualTo(UUID.hashCode());
}

private static ComponentImpl.Builder buildSimpleComponent(Component.Type type, String key) {
return builder(type)
.setName("name_" + key)
.setKey(key)
private static ComponentImpl.Builder buildSimpleComponent(Component.Type type, String dbKey) {
ComponentImpl.Builder builder = builder(type)
.setName("name_" + dbKey)
.setDbKey(dbKey)
.setStatus(Status.UNAVAILABLE)
.setUuid("uuid_" + key)
.setReportAttributes(ReportAttributes.newBuilder(key.hashCode())
.build());
.setUuid("uuid_" + dbKey)
.setReportAttributes(ReportAttributes.newBuilder(dbKey.hashCode()).build());
if (type == PROJECT) {
builder.setProjectAttributes(new ProjectAttributes("version_1"));
}
return builder;
}
}

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

@@ -101,14 +101,14 @@ public class ComponentTreeBuilderTest {
.build());

assertThat(root.getUuid()).isEqualTo("generated_K1_uuid");
assertThat(root.getKey()).isEqualTo("generated_K1");
assertThat(root.getPublicKey()).isEqualTo("public_K1");
assertThat(root.getDbKey()).isEqualTo("generated_K1");
assertThat(root.getKey()).isEqualTo("public_K1");
assertThat(root.getType()).isEqualTo(Component.Type.PROJECT);
assertThat(root.getName()).isEqualTo(nameInReport);
assertThat(root.getDescription()).isEqualTo(descriptionInReport);
assertThat(root.getReportAttributes().getRef()).isEqualTo(42);
assertThat(root.getReportAttributes().getPath()).isNull();
assertThat(root.getReportAttributes().getVersion()).isEqualTo("6.5");
assertThat(root.getProjectAttributes().getVersion()).isEqualTo("6.5");
assertThatFileAttributesAreNotSet(root);
}

@@ -154,7 +154,7 @@ public class ComponentTreeBuilderTest {
.setType(PROJECT)
.build(), baseAnalysis);

assertThat(root.getReportAttributes().getVersion()).isEqualTo("6.5");
assertThat(root.getProjectAttributes().getVersion()).isEqualTo("6.5");
}

@Test
@@ -165,7 +165,7 @@ public class ComponentTreeBuilderTest {
.setVersion("")
.build(), baseAnalysis);

assertThat(root.getReportAttributes().getVersion()).isEqualTo("6.5");
assertThat(root.getProjectAttributes().getVersion()).isEqualTo("6.5");
}

@Test
@@ -174,7 +174,7 @@ public class ComponentTreeBuilderTest {
.setType(PROJECT)
.build());

assertThat(root.getReportAttributes().getVersion()).isEqualTo("not provided");
assertThat(root.getProjectAttributes().getVersion()).isEqualTo("not provided");
}

@Test
@@ -345,23 +345,23 @@ public class ComponentTreeBuilderTest {
.setLines(1));

Component root = call(project);
assertThat(root.getKey()).isEqualTo("generated_" + projectInDb.getKey());
assertThat(root.getPublicKey()).isEqualTo("public_" + projectInDb.getKey());
assertThat(root.getDbKey()).isEqualTo("generated_" + projectInDb.getKey());
assertThat(root.getKey()).isEqualTo("public_" + projectInDb.getKey());
assertThat(root.getChildren()).hasSize(1);

Component module = root.getChildren().iterator().next();
assertThat(module.getKey()).isEqualTo("generated_M");
assertThat(module.getPublicKey()).isEqualTo("public_M");
assertThat(module.getDbKey()).isEqualTo("generated_M");
assertThat(module.getKey()).isEqualTo("public_M");
assertThat(module.getChildren()).hasSize(1);

Component directory = module.getChildren().iterator().next();
assertThat(directory.getKey()).isEqualTo("generated_M:src/js");
assertThat(directory.getPublicKey()).isEqualTo("public_M:src/js");
assertThat(directory.getDbKey()).isEqualTo("generated_M:src/js");
assertThat(directory.getKey()).isEqualTo("public_M:src/js");
assertThat(directory.getChildren()).hasSize(1);

Component file = directory.getChildren().iterator().next();
assertThat(file.getKey()).isEqualTo("generated_M:src/js/Foo.js");
assertThat(file.getPublicKey()).isEqualTo("public_M:src/js/Foo.js");
assertThat(file.getDbKey()).isEqualTo("generated_M:src/js/Foo.js");
assertThat(file.getKey()).isEqualTo("public_M:src/js/Foo.js");
assertThat(file.getChildren()).isEmpty();
}

@@ -474,36 +474,36 @@ public class ComponentTreeBuilderTest {

Component root = call(project);
Map<Integer, Component> componentsByRef = indexComponentByRef(root);
assertThat(componentsByRef.get(11).getKey()).isEqualTo("generated_module 1");
assertThat(componentsByRef.get(11).getPublicKey()).isEqualTo("public_module 1");
assertThat(componentsByRef.get(12).getKey()).isEqualTo("generated_module 2");
assertThat(componentsByRef.get(12).getPublicKey()).isEqualTo("public_module 2");
assertThat(componentsByRef.get(13).getKey()).isEqualTo("generated_module 3");
assertThat(componentsByRef.get(13).getPublicKey()).isEqualTo("public_module 3");
assertThat(componentsByRef.get(21).getKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(21).getPublicKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(22).getKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(22).getPublicKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(23).getKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(23).getPublicKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(24).getKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(24).getPublicKey()).startsWith("public_module 3:");
assertThat(componentsByRef.get(31).getKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(31).getPublicKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(32).getKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(32).getPublicKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(33).getKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(33).getPublicKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(34).getKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(34).getPublicKey()).startsWith("public_module 3:");
assertThat(componentsByRef.get(35).getKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(35).getPublicKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(36).getKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(36).getPublicKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(37).getKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(37).getPublicKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(38).getKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(38).getPublicKey()).startsWith("public_module 3:");
assertThat(componentsByRef.get(11).getDbKey()).isEqualTo("generated_module 1");
assertThat(componentsByRef.get(11).getKey()).isEqualTo("public_module 1");
assertThat(componentsByRef.get(12).getDbKey()).isEqualTo("generated_module 2");
assertThat(componentsByRef.get(12).getKey()).isEqualTo("public_module 2");
assertThat(componentsByRef.get(13).getDbKey()).isEqualTo("generated_module 3");
assertThat(componentsByRef.get(13).getKey()).isEqualTo("public_module 3");
assertThat(componentsByRef.get(21).getDbKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(21).getKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(22).getDbKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(22).getKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(23).getDbKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(23).getKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(24).getDbKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(24).getKey()).startsWith("public_module 3:");
assertThat(componentsByRef.get(31).getDbKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(31).getKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(32).getDbKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(32).getKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(33).getDbKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(33).getKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(34).getDbKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(34).getKey()).startsWith("public_module 3:");
assertThat(componentsByRef.get(35).getDbKey()).startsWith("generated_project 1:");
assertThat(componentsByRef.get(35).getKey()).startsWith("public_project 1:");
assertThat(componentsByRef.get(36).getDbKey()).startsWith("generated_module 1:");
assertThat(componentsByRef.get(36).getKey()).startsWith("public_module 1:");
assertThat(componentsByRef.get(37).getDbKey()).startsWith("generated_module 2:");
assertThat(componentsByRef.get(37).getKey()).startsWith("public_module 2:");
assertThat(componentsByRef.get(38).getDbKey()).startsWith("generated_module 3:");
assertThat(componentsByRef.get(38).getKey()).startsWith("public_module 3:");
}

@Test
@@ -652,114 +652,6 @@ public class ComponentTreeBuilderTest {
assertThat(file.getDescription()).isEqualTo("d");
}

@Test
public void versions_of_module_directory_and_file_are_set_from_report_if_present() {
ScannerReport.Component project = newBuilder()
.setType(PROJECT)
.setRef(1)
.addChildRef(2)
.build();
scannerComponentProvider.add(newBuilder()
.setRef(2)
.setType(MODULE)
.setVersion("v1")
.addChildRef(3));
scannerComponentProvider.add(newBuilder()
.setRef(3)
.setType(DIRECTORY)
.setVersion("v2")
.setPath("src/js")
.addChildRef(4));
scannerComponentProvider.add(newBuilder()
.setRef(4)
.setType(FILE)
.setVersion("v3")
.setPath("src/js/Foo.js")
.setLines(1));

Component root = call(project);

Component module = root.getChildren().iterator().next();
assertThat(module.getReportAttributes().getVersion()).isEqualTo("v1");

Component directory = module.getChildren().iterator().next();
assertThat(directory.getReportAttributes().getVersion()).isEqualTo("v2");

Component file = directory.getChildren().iterator().next();
assertThat(file.getReportAttributes().getVersion()).isEqualTo("v3");
}

@Test
public void versions_of_module_directory_and_file_are_null_if_absent_from_report() {
ScannerReport.Component project = newBuilder()
.setType(PROJECT)
.setRef(1)
.addChildRef(2)
.build();
scannerComponentProvider.add(newBuilder()
.setRef(2)
.setType(MODULE)
.addChildRef(3));
scannerComponentProvider.add(newBuilder()
.setRef(3)
.setType(DIRECTORY)
.setPath("src/js")
.addChildRef(4));
scannerComponentProvider.add(newBuilder()
.setRef(4)
.setType(FILE)
.setPath("src/js/Foo.js")
.setLines(1));

Component root = call(project);

Component module = root.getChildren().iterator().next();
assertThat(module.getReportAttributes().getVersion()).isNull();

Component directory = module.getChildren().iterator().next();
assertThat(directory.getReportAttributes().getVersion()).isNull();

Component file = directory.getChildren().iterator().next();
assertThat(file.getReportAttributes().getVersion()).isNull();
}

@Test
public void versions_of_module_directory_and_file_are_null_if_empty_in_report() {
ScannerReport.Component project = newBuilder()
.setType(PROJECT)
.setRef(1)
.addChildRef(2)
.build();
scannerComponentProvider.add(newBuilder()
.setRef(2)
.setType(MODULE)
.setVersion("")
.addChildRef(3));
scannerComponentProvider.add(newBuilder()
.setRef(3)
.setType(DIRECTORY)
.setVersion("")
.setPath("src/js")
.addChildRef(4));
scannerComponentProvider.add(newBuilder()
.setRef(4)
.setType(FILE)
.setVersion("")
.setPath("src/js/Foo.js")
.setLines(1));

Component root = call(project);

Component module = root.getChildren().iterator().next();
assertThat(module.getReportAttributes().getVersion()).isNull();

Component directory = module.getChildren().iterator().next();
assertThat(directory.getReportAttributes().getVersion()).isNull();

Component file = directory.getChildren().iterator().next();
assertThat(file.getReportAttributes().getVersion()).isNull();
}

@Test
public void only_nb_of_lines_is_mandatory_on_file_attributes() {
ScannerReport.Component project = newBuilder()

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

@@ -52,7 +52,7 @@ public class MutableDbIdsRepositoryRule extends ExternalResource implements Muta
@Nullable
@Override
public String apply(Component input) {
return input.getType().isReportType() ? String.valueOf(input.getReportAttributes().getRef()) : input.getKey();
return input.getType().isReportType() ? String.valueOf(input.getReportAttributes().getRef()) : input.getDbKey();
}
});
}

+ 24
- 7
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportComponent.java View File

@@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.component;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

@@ -42,7 +43,7 @@ public class ReportComponent implements Component {
.setPublicKey("PUBLIC_PROJECT_KEY")
.setUuid("PROJECT_UUID")
.setName("Project Name")
.setVersion("1.0-SNAPSHOT")
.setProjectVersion("1.0-SNAPSHOT")
.build();

private final Type type;
@@ -53,6 +54,7 @@ public class ReportComponent implements Component {
private final String key;
private final String publicKey;
private final String uuid;
private final ProjectAttributes projectAttributes;
private final ReportAttributes reportAttributes;
private final FileAttributes fileAttributes;
private final List<Component> children;
@@ -65,8 +67,8 @@ public class ReportComponent implements Component {
this.name = builder.name == null ? String.valueOf(builder.key) : builder.name;
this.description = builder.description;
this.uuid = builder.uuid;
this.projectAttributes = Optional.ofNullable(builder.projectVersion).map(ProjectAttributes::new).orElse(null);
this.reportAttributes = ReportAttributes.newBuilder(builder.ref)
.setVersion(builder.version)
.setPath(builder.path)
.build();
this.fileAttributes = builder.fileAttributes == null ? DEFAULT_FILE_ATTRIBUTES : builder.fileAttributes;
@@ -92,7 +94,7 @@ public class ReportComponent implements Component {
}

@Override
public String getKey() {
public String getDbKey() {
if (key == null) {
throw new UnsupportedOperationException(String.format("Component key of ref '%d' has not be fed yet", this.reportAttributes.getRef()));
}
@@ -100,7 +102,7 @@ public class ReportComponent implements Component {
}

@Override
public String getPublicKey() {
public String getKey() {
if (publicKey == null) {
throw new UnsupportedOperationException(String.format("Component key of ref '%d' has not be fed yet", this.reportAttributes.getRef()));
}
@@ -123,6 +125,12 @@ public class ReportComponent implements Component {
return children;
}

@Override
public ProjectAttributes getProjectAttributes() {
checkState(this.type == Type.PROJECT);
return this.projectAttributes;
}

@Override
public ReportAttributes getReportAttributes() {
return this.reportAttributes;
@@ -188,7 +196,7 @@ public class ReportComponent implements Component {
private String key;
private String publicKey;
private String name;
private String version;
private String projectVersion;
private String description;
private String path;
private FileAttributes fileAttributes;
@@ -198,6 +206,9 @@ public class ReportComponent implements Component {
checkArgument(type.isReportType(), "Component type must be a report type");
this.type = type;
this.ref = ref;
if (type == Type.PROJECT) {
this.projectVersion = "toBeDefined";
}
}

public Builder setStatus(Status s) {
@@ -225,8 +236,9 @@ public class ReportComponent implements Component {
return this;
}

public Builder setVersion(@Nullable String s) {
this.version = s;
public Builder setProjectVersion(String s) {
checkProjectVersion(s);
this.projectVersion = s;
return this;
}

@@ -255,8 +267,13 @@ public class ReportComponent implements Component {
}

public ReportComponent build() {
checkProjectVersion(this.projectVersion);
return new ReportComponent(this);
}

private void checkProjectVersion(@Nullable String s) {
checkArgument(type != Type.PROJECT ^ s != null, "Project version must and can only be set on Project");
}
}

}

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

@@ -34,7 +34,7 @@ public final class TreeComponentProvider extends AbstractComponentProvider {
}

private static String getRef(Component component) {
return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getKey();
return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getDbKey();
}

@Override

+ 8
- 3
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsComponent.java View File

@@ -148,7 +148,7 @@ public class ViewsComponent implements Component {
}

@Override
public String getKey() {
public String getDbKey() {
return key;
}

@@ -156,8 +156,8 @@ public class ViewsComponent implements Component {
* Views has no branch feature, the public key is the same as the key
*/
@Override
public String getPublicKey() {
return getKey();
public String getKey() {
return getDbKey();
}

@Override
@@ -177,6 +177,11 @@ public class ViewsComponent implements Component {
return children;
}

@Override
public ProjectAttributes getProjectAttributes() {
throw new IllegalStateException("A component of type " + type + " does not have project attributes");
}

@Override
public ReportAttributes getReportAttributes() {
throw new IllegalStateException("A component of type " + type + " does not have report attributes");

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

@@ -181,7 +181,7 @@ public class ViewsPostOrderDepthTraversalTypeAwareCrawlerTest {
}

private static CallRecord viewsCallRecord(String methodName, Component component) {
return CallRecord.viewsCallRecord(methodName, component.getKey());
return CallRecord.viewsCallRecord(methodName, component.getDbKey());
}

}

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

@@ -181,7 +181,7 @@ public class ViewsPreOrderDepthTraversalTypeAwareCrawlerTest {
}

private static CallRecord viewsCallRecord(String methodName, Component component) {
return CallRecord.viewsCallRecord(methodName, component.getKey());
return CallRecord.viewsCallRecord(methodName, component.getDbKey());
}

}

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

@@ -154,7 +154,7 @@ public class ViewsVisitorsCrawlerTest {
super(maxDepth, order, new SimpleStackElementFactory<Integer>() {
@Override
public Integer createForAny(Component component) {
return Integer.valueOf(component.getKey());
return Integer.valueOf(component.getDbKey());
}
});
}

+ 27
- 27
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepTest.java View File

@@ -296,7 +296,7 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, null);
insertFiles(file1.getKey(), file2.getKey());
insertFiles(file1.getDbKey(), file2.getDbKey());
setFilesInReport(file2, file1);

TestComputationStepContext context = new TestComputationStepContext();
@@ -311,8 +311,8 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, CONTENT1);
ComponentDto[] dtos = insertFiles(file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
ComponentDto[] dtos = insertFiles(file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
setFilesInReport(file2);

TestComputationStepContext context = new TestComputationStepContext();
@@ -331,8 +331,8 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, LESS_CONTENT1);
insertFiles(file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertFiles(file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
setFilesInReport(file2);

TestComputationStepContext context = new TestComputationStepContext();
@@ -350,8 +350,8 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, CONTENT1);
insertFiles(file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT_EMPTY);
insertFiles(file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT_EMPTY);
setFilesInReport(file2);

TestComputationStepContext context = new TestComputationStepContext();
@@ -367,8 +367,8 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, CONTENT1);
insertFiles(key -> newComponentDto(key).setPath(null), file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertFiles(key -> newComponentDto(key).setPath(null), file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
setFilesInReport(file2);

TestComputationStepContext context = new TestComputationStepContext();
@@ -384,8 +384,8 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, CONTENT_EMPTY);
insertFiles(file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertFiles(file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
setFilesInReport(file2);

TestComputationStepContext context = new TestComputationStepContext();
@@ -403,8 +403,8 @@ public class FileMoveDetectionStepTest {
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, CONTENT1);
Component file3 = fileComponent(FILE_3_REF, CONTENT1);
insertFiles(file1.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertFiles(file1.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
setFilesInReport(file2, file3);

TestComputationStepContext context = new TestComputationStepContext();
@@ -421,9 +421,9 @@ public class FileMoveDetectionStepTest {
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, null);
Component file3 = fileComponent(FILE_3_REF, CONTENT1);
insertFiles(file1.getKey(), file2.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertContentOfFileInDb(file2.getKey(), CONTENT1);
insertFiles(file1.getDbKey(), file2.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
insertContentOfFileInDb(file2.getDbKey(), CONTENT1);
setFilesInReport(file3);

TestComputationStepContext context = new TestComputationStepContext();
@@ -439,9 +439,9 @@ public class FileMoveDetectionStepTest {
analysisMetadataHolder.setBaseAnalysis(ANALYSIS);
Component file1 = fileComponent(FILE_1_REF, null);
Component file2 = fileComponent(FILE_2_REF, null);
insertFiles(file1.getKey(), file2.getKey());
insertContentOfFileInDb(file1.getKey(), null);
insertContentOfFileInDb(file2.getKey(), null);
insertFiles(file1.getDbKey(), file2.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), null);
insertContentOfFileInDb(file2.getDbKey(), null);

TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
@@ -465,11 +465,11 @@ public class FileMoveDetectionStepTest {
Component file4 = fileComponent(5, new String[] {"a", "b"});
Component file5 = fileComponent(6, null);
Component file6 = fileComponent(7, LESS_CONTENT2);
ComponentDto[] dtos = insertFiles(file1.getKey(), file2.getKey(), file4.getKey(), file5.getKey());
insertContentOfFileInDb(file1.getKey(), CONTENT1);
insertContentOfFileInDb(file2.getKey(), LESS_CONTENT1);
insertContentOfFileInDb(file4.getKey(), new String[] {"e", "f", "g", "h", "i"});
insertContentOfFileInDb(file5.getKey(), CONTENT2);
ComponentDto[] dtos = insertFiles(file1.getDbKey(), file2.getDbKey(), file4.getDbKey(), file5.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), CONTENT1);
insertContentOfFileInDb(file2.getDbKey(), LESS_CONTENT1);
insertContentOfFileInDb(file4.getDbKey(), new String[] {"e", "f", "g", "h", "i"});
insertContentOfFileInDb(file5.getDbKey(), CONTENT2);
setFilesInReport(file3, file4, file6);

TestComputationStepContext context = new TestComputationStepContext();
@@ -495,9 +495,9 @@ public class FileMoveDetectionStepTest {
Component file2 = fileComponent(FILE_2_REF, null);
Component file3 = fileComponent(FILE_3_REF, arrayOf(118));
Component file4 = fileComponent(5, arrayOf(25));
insertFiles(file1.getKey(), file2.getKey());
insertContentOfFileInDb(file1.getKey(), arrayOf(100));
insertContentOfFileInDb(file2.getKey(), arrayOf(30));
insertFiles(file1.getDbKey(), file2.getDbKey());
insertContentOfFileInDb(file1.getDbKey(), arrayOf(100));
insertContentOfFileInDb(file2.getDbKey(), arrayOf(30));
setFilesInReport(file3, file4);

TestComputationStepContext context = new TestComputationStepContext();

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java View File

@@ -119,7 +119,7 @@ public class MovedIssueVisitorTest {
underTest.onIssue(FILE, issue);

verify(issue).setComponentUuid(FILE.getUuid());
verify(issue).setComponentKey(FILE.getPublicKey());
verify(issue).setComponentKey(FILE.getKey());
verify(issue).setModuleUuid(null);
verify(issue).setModuleUuidPath(null);
verify(issue).setChanged(true);

+ 4
- 4
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java View File

@@ -345,8 +345,8 @@ public class TrackerRawInputFactoryTest {
}

private void assertInitializedIssue(DefaultIssue issue) {
assertThat(issue.projectKey()).isEqualTo(PROJECT.getPublicKey());
assertThat(issue.componentKey()).isEqualTo(FILE.getPublicKey());
assertThat(issue.projectKey()).isEqualTo(PROJECT.getKey());
assertThat(issue.componentKey()).isEqualTo(FILE.getKey());
assertThat(issue.componentUuid()).isEqualTo(FILE.getUuid());
assertThat(issue.resolution()).isNull();
assertThat(issue.status()).isEqualTo(Issue.STATUS_OPEN);
@@ -357,8 +357,8 @@ public class TrackerRawInputFactoryTest {
}

private void assertInitializedExternalIssue(DefaultIssue issue) {
assertThat(issue.projectKey()).isEqualTo(PROJECT.getPublicKey());
assertThat(issue.componentKey()).isEqualTo(FILE.getPublicKey());
assertThat(issue.projectKey()).isEqualTo(PROJECT.getKey());
assertThat(issue.componentKey()).isEqualTo(FILE.getKey());
assertThat(issue.componentUuid()).isEqualTo(FILE.getUuid());
assertThat(issue.resolution()).isNull();
assertThat(issue.status()).isEqualTo(Issue.STATUS_OPEN);

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryRule.java View File

@@ -334,7 +334,7 @@ public class MeasureRepositoryRule extends ExternalResource implements MeasureRe
}

private static String getRef(Component component) {
return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getKey();
return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getDbKey();
}

private static class MatchMetric implements Predicate<Map.Entry<InternalKey, Measure>> {

+ 1
- 1
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoaderTest.java View File

@@ -95,7 +95,7 @@ public class ScmInfoDbLoaderTest {
String hash = computeSourceHash(1);
when(branch.getMergeBranchUuid()).thenReturn(Optional.of("mergeBranchUuid"));

when(mergeBranchComponentUuids.getUuid(FILE.getKey())).thenReturn(mergeFileUuid);
when(mergeBranchComponentUuids.getUuid(FILE.getDbKey())).thenReturn(mergeFileUuid);
addFileSourceInDb("henry", DATE_1, "rev-1", hash, mergeFileUuid);

DbScmInfo scmInfo = underTest.getScmInfo(FILE).get();

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

@@ -502,8 +502,8 @@ public class BuildComponentTreeStepTest {
private void verifyComponent(int ref, String key, String publicKey, @Nullable String uuid) {
Map<Integer, Component> componentsByRef = indexAllComponentsInTreeByRef(treeRootHolder.getRoot());
Component component = componentsByRef.get(ref);
assertThat(component.getKey()).isEqualTo(key);
assertThat(component.getPublicKey()).isEqualTo(publicKey);
assertThat(component.getDbKey()).isEqualTo(key);
assertThat(component.getKey()).isEqualTo(publicKey);
if (uuid != null) {
assertThat(component.getUuid()).isEqualTo(uuid);
} else {

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

@@ -423,7 +423,7 @@ public class LoadPeriodsStepTest extends BaseStepTest {
}

private void setupRoot(ComponentDto project, String version) {
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey()).setVersion(version).build());
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey()).setProjectVersion(version).build());
when(settingsRepository.getConfiguration()).thenReturn(settings.asConfig());
}


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

@@ -55,7 +55,7 @@ public class PersistComponentsStepTest {
String projectKey = randomAlphabetic(20);

doReturn(component).when(treeRootHolder).getRoot();
doReturn(projectKey).when(component).getKey();
doReturn(projectKey).when(component).getDbKey();
doReturn(componentDao).when(dbClient).componentDao();
doReturn(emptyList()).when(componentDao).selectAllComponentsFromProjectKey(any(DbSession.class), eq(projectKey));


+ 47
- 48
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStepTest.java View File

@@ -50,12 +50,16 @@ import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.MODULE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.db.event.EventDto.CATEGORY_ALERT;
import static org.sonar.db.event.EventDto.CATEGORY_PROFILE;
import static org.sonar.db.event.EventDto.CATEGORY_VERSION;

public class PersistEventsStepTest extends BaseStepTest {

private static final long NOW = 1225630680000L;
private static final ReportComponent ROOT = builder(PROJECT, 1)
.setUuid("ABCD")
.setProjectVersion("version_1")
.addChildren(
builder(MODULE, 2)
.setUuid("BCDE")
@@ -100,12 +104,39 @@ public class PersistEventsStepTest extends BaseStepTest {
}

@Test
public void nothing_to_do_when_no_events_in_report() {
treeRootHolder.setRoot(ROOT);
public void create_version_event() {
when(system2.now()).thenReturn(NOW);
Component project = builder(PROJECT, 1)
.setUuid("ABCD")
.setProjectVersion("1.0")
.addChildren(
builder(MODULE, 2)
.setUuid("BCDE")
.addChildren(
builder(DIRECTORY, 3)
.setUuid("Q")
.addChildren(
builder(FILE, 4)
.setUuid("Z")
.build())
.build())
.build())
.build();
treeRootHolder.setRoot(project);

underTest.execute(new TestComputationStepContext());

assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isZero();
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(1);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos).hasSize(1);
EventDto eventDto = eventDtos.iterator().next();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo("1.0");
assertThat(eventDto.getDescription()).isNull();
assertThat(eventDto.getCategory()).isEqualTo(CATEGORY_VERSION);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}

@Test
@@ -117,14 +148,16 @@ public class PersistEventsStepTest extends BaseStepTest {

underTest.execute(new TestComputationStepContext());

assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(1);
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(2);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos).hasSize(1);
EventDto eventDto = eventDtos.iterator().next();
assertThat(eventDtos)
.extracting(EventDto::getCategory)
.containsOnly(CATEGORY_ALERT, CATEGORY_VERSION);
EventDto eventDto = eventDtos.stream().filter(t -> CATEGORY_ALERT.equals(t.getCategory())).findAny().get();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo(alert.getName());
assertThat(eventDto.getDescription()).isEqualTo(alert.getDescription());
assertThat(eventDto.getCategory()).isEqualTo(EventDto.CATEGORY_ALERT);
assertThat(eventDto.getCategory()).isEqualTo(CATEGORY_ALERT);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
@@ -139,10 +172,12 @@ public class PersistEventsStepTest extends BaseStepTest {

underTest.execute(new TestComputationStepContext());

assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(1);
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(2);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos).hasSize(1);
EventDto eventDto = eventDtos.iterator().next();
assertThat(eventDtos)
.extracting(EventDto::getCategory)
.containsOnly(CATEGORY_PROFILE, CATEGORY_VERSION);
EventDto eventDto = eventDtos.stream().filter(t -> CATEGORY_PROFILE.equals(t.getCategory())).findAny().get();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo(profile.getName());
assertThat(eventDto.getDescription()).isEqualTo(profile.getDescription());
@@ -152,42 +187,6 @@ public class PersistEventsStepTest extends BaseStepTest {
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}

@Test
public void create_version_event() {
when(system2.now()).thenReturn(NOW);
Component project = builder(PROJECT, 1)
.setUuid("ABCD")
.setVersion("1.0")
.addChildren(
builder(MODULE, 2)
.setUuid("BCDE")
.addChildren(
builder(DIRECTORY, 3)
.setUuid("Q")
.addChildren(
builder(FILE, 4)
.setUuid("Z")
.build())
.build())
.build())
.build();
treeRootHolder.setRoot(project);

underTest.execute(new TestComputationStepContext());

assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(1);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos).hasSize(1);
EventDto eventDto = eventDtos.iterator().next();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo("1.0");
assertThat(eventDto.getDescription()).isNull();
assertThat(eventDto.getCategory()).isEqualTo(EventDto.CATEGORY_VERSION);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}

@Test
public void keep_one_event_by_version() {
ComponentDto projectDto = dbTester.components().insertPublicProject();
@@ -199,7 +198,7 @@ public class PersistEventsStepTest extends BaseStepTest {

Component project = builder(PROJECT, 1)
.setUuid(projectDto.uuid())
.setVersion("1.5-SNAPSHOT")
.setProjectVersion("1.5-SNAPSHOT")
.addChildren(
builder(MODULE, 2)
.setUuid("BCDE")
@@ -232,7 +231,7 @@ public class PersistEventsStepTest extends BaseStepTest {
private EventDto newVersionEventDto(ComponentDto project, long date, String name) {
return new EventDto().setUuid(uuidFactory.create()).setComponentUuid(project.uuid())
.setAnalysisUuid("analysis_uuid")
.setCategory(EventDto.CATEGORY_VERSION)
.setCategory(CATEGORY_VERSION)
.setName(name).setDate(date).setCreatedAt(date);
}


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

@@ -249,7 +249,7 @@ public class PersistLiveMeasuresStepTest extends BaseStepTest {
.build())
.build();
treeRootHolder.setRoot(project);
analysisMetadataHolder.setProject(new Project(project.getUuid(), project.getKey(), project.getName(), project.getDescription(), emptyList()));
analysisMetadataHolder.setProject(new Project(project.getUuid(), project.getDbKey(), project.getName(), project.getDescription(), emptyList()));

// components as persisted in db
ComponentDto projectDto = insertComponent("project-key", "project-uuid");

+ 14
- 11
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java View File

@@ -59,8 +59,11 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK;
import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.WARN;

public class QualityGateEventsStepTest {
private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("uuid 1").setKey("key 1")
.addChildren(ReportComponent.builder(Component.Type.MODULE, 2).setVersion("V1.9").build())
private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid("uuid 1")
.setKey("key 1")
.setProjectVersion("V1.9")
.addChildren(ReportComponent.builder(Component.Type.MODULE, 2).build())
.build();
private static final String INVALID_ALERT_STATUS = "trololo";
private static final String ALERT_TEXT = "alert text";
@@ -89,7 +92,7 @@ public class QualityGateEventsStepTest {
@Before
public void setUp() {
when(metricRepository.getByKey(ALERT_STATUS_KEY)).thenReturn(alertStatusMetric);
analysisMetadataHolder.setProject(new Project(PROJECT_COMPONENT.getUuid(), PROJECT_COMPONENT.getKey(), PROJECT_COMPONENT.getName(), PROJECT_COMPONENT.getDescription(), emptyList()));
analysisMetadataHolder.setProject(new Project(PROJECT_COMPONENT.getUuid(), PROJECT_COMPONENT.getDbKey(), PROJECT_COMPONENT.getName(), PROJECT_COMPONENT.getDescription(), emptyList()));
analysisMetadataHolder.setBranch(mock(Branch.class));
treeRootHolder.setRoot(PROJECT_COMPONENT);
}
@@ -194,9 +197,9 @@ public class QualityGateEventsStepTest {
verify(notificationService).deliver(notificationArgumentCaptor.capture());
Notification notification = notificationArgumentCaptor.getValue();
assertThat(notification.getType()).isEqualTo("alerts");
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getPublicKey());
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey());
assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getReportAttributes().getVersion());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getVersion());
assertThat(notification.getFieldValue("branch")).isNull();
assertThat(notification.getFieldValue("alertLevel")).isEqualTo(rawAlterStatus.name());
assertThat(notification.getFieldValue("alertName")).isEqualTo(expectedLabel);
@@ -249,9 +252,9 @@ public class QualityGateEventsStepTest {
verify(notificationService).deliver(notificationArgumentCaptor.capture());
Notification notification = notificationArgumentCaptor.getValue();
assertThat(notification.getType()).isEqualTo("alerts");
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getPublicKey());
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey());
assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getReportAttributes().getVersion());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getVersion());
assertThat(notification.getFieldValue("branch")).isNull();
assertThat(notification.getFieldValue("alertLevel")).isEqualTo(newQualityGateStatus.getStatus().name());
assertThat(notification.getFieldValue("alertName")).isEqualTo(expectedLabel);
@@ -279,9 +282,9 @@ public class QualityGateEventsStepTest {
verify(notificationService).deliver(notificationArgumentCaptor.capture());
Notification notification = notificationArgumentCaptor.getValue();
assertThat(notification.getType()).isEqualTo("alerts");
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getPublicKey());
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey());
assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getReportAttributes().getVersion());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getVersion());
assertThat(notification.getFieldValue("branch")).isEqualTo(branchName);

reset(measureRepository, eventRepository, notificationService);
@@ -301,9 +304,9 @@ public class QualityGateEventsStepTest {
verify(notificationService).deliver(notificationArgumentCaptor.capture());
Notification notification = notificationArgumentCaptor.getValue();
assertThat(notification.getType()).isEqualTo("alerts");
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getPublicKey());
assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey());
assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getReportAttributes().getVersion());
assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getVersion());
assertThat(notification.getFieldValue("branch")).isEqualTo(null);

reset(measureRepository, eventRepository, notificationService);

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

@@ -107,8 +107,8 @@ public class ReportPersistAnalysisStepTest extends BaseStepTest {

Component file = ReportComponent.builder(Component.Type.FILE, 4).setUuid("DEFG").setKey("MODULE_KEY:src/main/java/dir/Foo.java").build();
Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 3).setUuid("CDEF").setKey("MODULE_KEY:src/main/java/dir").addChildren(file).build();
Component module = ReportComponent.builder(Component.Type.MODULE, 2).setUuid("BCDE").setKey("MODULE_KEY").setVersion("1.1").addChildren(directory).build();
Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).setVersion("1.0").addChildren(module).build();
Component module = ReportComponent.builder(Component.Type.MODULE, 2).setUuid("BCDE").setKey("MODULE_KEY").addChildren(directory).build();
Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).setProjectVersion("1.0").addChildren(module).build();
treeRootHolder.setRoot(project);

dbIdsRepository.setComponentId(project, projectDto.getId());

+ 8
- 8
server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java View File

@@ -27,7 +27,6 @@ import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -63,6 +62,7 @@ import static java.util.Arrays.stream;
import static java.util.Collections.shuffle;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.concat;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentCaptor.forClass;
@@ -96,7 +96,7 @@ public class SendIssueNotificationsStepTest extends BaseStepTest {

private static final Component FILE = builder(Type.FILE, 11).build();
private static final Component PROJECT = builder(Type.PROJECT, 1)
.setVersion(RandomStringUtils.randomAlphanumeric(10))
.setProjectVersion(randomAlphanumeric(10))
.addChildren(FILE).build();

@Rule
@@ -157,7 +157,7 @@ public class SendIssueNotificationsStepTest extends BaseStepTest {
underTest.execute(context);

verify(notificationService).deliver(newIssuesNotificationMock);
verify(newIssuesNotificationMock).setProject(PROJECT.getPublicKey(), PROJECT.getName(), null, null);
verify(newIssuesNotificationMock).setProject(PROJECT.getKey(), PROJECT.getName(), null, null);
verify(newIssuesNotificationMock).setAnalysisDate(new Date(ANALYSE_DATE));
verify(newIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), any());
verify(newIssuesNotificationMock).setDebt(ISSUE_DURATION);
@@ -283,7 +283,7 @@ public class SendIssueNotificationsStepTest extends BaseStepTest {
verify(notificationService).deliver(newIssuesNotificationMock);
verify(notificationService).deliver(myNewIssuesNotificationMock);
verify(myNewIssuesNotificationMock).setAssignee(any(UserDto.class));
verify(myNewIssuesNotificationMock).setProject(PROJECT.getPublicKey(), PROJECT.getName(), null, null);
verify(myNewIssuesNotificationMock).setProject(PROJECT.getKey(), PROJECT.getName(), null, null);
verify(myNewIssuesNotificationMock).setAnalysisDate(new Date(ANALYSE_DATE));
verify(myNewIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), any(NewIssuesStatistics.Stats.class));
verify(myNewIssuesNotificationMock).setDebt(ISSUE_DURATION);
@@ -417,8 +417,8 @@ public class SendIssueNotificationsStepTest extends BaseStepTest {
@Test
public void dont_send_issues_change_notification_for_hotspot() {
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto(newOrganizationDto()).setDbKey(PROJECT.getKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getKey()).setLongName(FILE.getName());
ComponentDto project = newPrivateProjectDto(newOrganizationDto()).setDbKey(PROJECT.getDbKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getDbKey()).setLongName(FILE.getName());
RuleDefinitionDto ruleDefinitionDto = newRule();
DefaultIssue issue = prepareIssue(ANALYSE_DATE, user, project, file, ruleDefinitionDto, RuleType.SECURITY_HOTSPOT);

@@ -436,8 +436,8 @@ public class SendIssueNotificationsStepTest extends BaseStepTest {

private void sendIssueChangeNotification(long issueCreatedAt) {
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto(newOrganizationDto()).setDbKey(PROJECT.getKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getKey()).setLongName(FILE.getName());
ComponentDto project = newPrivateProjectDto(newOrganizationDto()).setDbKey(PROJECT.getDbKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getDbKey()).setLongName(FILE.getName());
RuleDefinitionDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
DefaultIssue issue = prepareIssue(issueCreatedAt, user, project, file, ruleDefinitionDto, randomTypeExceptHotspot);

Loading…
Cancel
Save