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()));
}
}
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())
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;
* 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.
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}.
*/
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;
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;
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);
}
@Override
- public String getKey() {
- return key;
+ public String getDbKey() {
+ return dbKey;
}
@Override
- public String getPublicKey() {
- return publicKey;
+ public String getKey() {
+ return key;
}
@Override
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;
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";
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;
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;
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;
}
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;
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 +
'}';
}
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();
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()))
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()))
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())
private static Component buildChangedProject(Component component) {
return changedComponentBuilder(component)
+ .setProjectAttributes(new ProjectAttributes(component.getProjectAttributes().getVersion()))
.addChildren(buildChangedComponentChildren(component))
.build();
}
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()));
}
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());
}
}
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;
}
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;
}
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));
}
}
@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());
}
}
}
--- /dev/null
+/*
+ * 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 + '\'' +
+ '}';
+ }
+}
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;
}
public static class Builder {
private final int ref;
@CheckForNull
- private String version;
- @CheckForNull
private String path;
@CheckForNull
private String scmPath;
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;
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.
*/
public String toString() {
return "ReportAttributes{" +
"ref=" + ref +
- ", version='" + version + '\'' +
", path='" + path + '\'' +
", scmPath='" + scmPath + '\'' +
'}';
VisitException.rethrowOrWrap(
e,
"Visit of Component {key=%s,type=%s} failed",
- component.getKey(), component.getType());
+ component.getDbKey(), component.getType());
}
}
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:
return "";
}
if (duplicate instanceof InProjectDuplicate) {
- return ((InProjectDuplicate) duplicate).getFile().getKey();
+ return ((InProjectDuplicate) duplicate).getFile().getDbKey();
}
if (duplicate instanceof CrossProjectDuplicate) {
return ((CrossProjectDuplicate) duplicate).getFileKey();
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;
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();
}
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) {
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;
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);
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++;
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();
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;
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);
}
}
return Optional.absent();
}
- return Optional.fromNullable(originalFiles.get(file.getKey()));
+ return Optional.fromNullable(originalFiles.get(file.getDbKey()));
}
}
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);
}
}
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;
// 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);
}
}
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();
}
public Input<DefaultIssue> create(Component component) {
- String mergeBranchComponentUuid = mergeBranchComponentUuids.getUuid(component.getKey());
+ String mergeBranchComponentUuid = mergeBranchComponentUuids.getUuid(component.getDbKey());
return new MergeLazyInput(component.getType(), mergeBranchComponentUuid);
}
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;
}
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;
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);
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);
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);
// 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();
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);
}
}
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));
}
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;
@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);
}
}
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);
}
}
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);
}
}
}
private void computeDuplications(Component component, Iterable<Duplication> duplications) {
- String duplicationXml = createXmlDuplications(component.getKey(), duplications);
+ String duplicationXml = createXmlDuplications(component.getDbKey(), duplications);
measureRepository.add(
component,
duplicationDataMetric,
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();
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;
}
}
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);
}
@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);
@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);
}
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)
}
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()) {
* 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()));
}
}
private ComponentDto createBase(Component component) {
- String componentKey = component.getKey();
+ String componentKey = component.getDbKey();
String componentUuid = component.getUuid();
ComponentDto componentDto = new ComponentDto();
}
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) {
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);
}
}
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 -> {
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;
}
}
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;
}
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())
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++;
}
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()));
.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()));
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();
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);
@Override
public void visitProject(Component rawProject) {
this.rawProject = rawProject;
- String rawProjectKey = rawProject.getKey();
+ String rawProjectKey = rawProject.getDbKey();
Optional<ComponentDto> baseProject = loadBaseComponent(rawProjectKey);
validateAnalysisDate(baseProject);
@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);
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);
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);
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());
}
});
}
}
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));
}
}
private static CallRecord viewsCallRecord(Component component, String method) {
- return CallRecord.viewsCallRecord(method, component.getKey());
+ return CallRecord.viewsCallRecord(method, component.getDbKey());
}
}
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 {
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");
}
builder(Component.Type.DIRECTORY)
.setName("DIR")
- .setKey(KEY)
+ .setDbKey(KEY)
.setUuid(UUID)
.setReportAttributes(ReportAttributes.newBuilder(1).build())
.build();
public void set_uuid_throws_NPE_if_component_arg_is_Null() {
expectedException.expect(NullPointerException.class);
- builder(FILE).setKey(null);
+ builder(FILE).setDbKey(null);
}
@Test
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
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())
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);
}
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;
}
}
.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);
}
.setType(PROJECT)
.build(), baseAnalysis);
- assertThat(root.getReportAttributes().getVersion()).isEqualTo("6.5");
+ assertThat(root.getProjectAttributes().getVersion()).isEqualTo("6.5");
}
@Test
.setVersion("")
.build(), baseAnalysis);
- assertThat(root.getReportAttributes().getVersion()).isEqualTo("6.5");
+ assertThat(root.getProjectAttributes().getVersion()).isEqualTo("6.5");
}
@Test
.setType(PROJECT)
.build());
- assertThat(root.getReportAttributes().getVersion()).isEqualTo("not provided");
+ assertThat(root.getProjectAttributes().getVersion()).isEqualTo("not provided");
}
@Test
.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();
}
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
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()
@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();
}
});
}
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;
.setPublicKey("PUBLIC_PROJECT_KEY")
.setUuid("PROJECT_UUID")
.setName("Project Name")
- .setVersion("1.0-SNAPSHOT")
+ .setProjectVersion("1.0-SNAPSHOT")
.build();
private final Type type;
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;
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;
}
@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()));
}
}
@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()));
}
return children;
}
+ @Override
+ public ProjectAttributes getProjectAttributes() {
+ checkState(this.type == Type.PROJECT);
+ return this.projectAttributes;
+ }
+
@Override
public ReportAttributes getReportAttributes() {
return this.reportAttributes;
private String key;
private String publicKey;
private String name;
- private String version;
+ private String projectVersion;
private String description;
private String path;
private FileAttributes fileAttributes;
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) {
return this;
}
- public Builder setVersion(@Nullable String s) {
- this.version = s;
+ public Builder setProjectVersion(String s) {
+ checkProjectVersion(s);
+ this.projectVersion = s;
return this;
}
}
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");
+ }
}
}
}
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
}
@Override
- public String getKey() {
+ public String getDbKey() {
return key;
}
* 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
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");
}
private static CallRecord viewsCallRecord(String methodName, Component component) {
- return CallRecord.viewsCallRecord(methodName, component.getKey());
+ return CallRecord.viewsCallRecord(methodName, component.getDbKey());
}
}
}
private static CallRecord viewsCallRecord(String methodName, Component component) {
- return CallRecord.viewsCallRecord(methodName, component.getKey());
+ return CallRecord.viewsCallRecord(methodName, component.getDbKey());
}
}
super(maxDepth, order, new SimpleStackElementFactory<Integer>() {
@Override
public Integer createForAny(Component component) {
- return Integer.valueOf(component.getKey());
+ return Integer.valueOf(component.getDbKey());
}
});
}
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();
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();
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();
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();
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();
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();
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();
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();
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);
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();
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();
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);
}
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);
}
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);
}
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>> {
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();
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 {
}
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());
}
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));
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")
}
@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
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);
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());
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();
Component project = builder(PROJECT, 1)
.setUuid(projectDto.uuid())
- .setVersion("1.5-SNAPSHOT")
+ .setProjectVersion("1.5-SNAPSHOT")
.addChildren(
builder(MODULE, 2)
.setUuid("BCDE")
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);
}
.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");
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";
@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);
}
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);
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);
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);
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);
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());
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;
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;
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
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);
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);
@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);
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);