@@ -21,12 +21,10 @@ package org.sonar.alm.client.github; | |||
import com.google.gson.annotations.SerializedName; | |||
import java.util.List; | |||
import java.util.Objects; | |||
import java.util.Optional; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.alm.client.github.config.GithubAppConfiguration; | |||
import org.sonar.alm.client.github.security.AccessToken; | |||
import org.sonar.alm.client.github.security.UserAccessToken; | |||
@@ -166,67 +164,6 @@ public interface GithubApplicationClient { | |||
} | |||
} | |||
@Immutable | |||
final class RepositoryDetails { | |||
private final Repository repository; | |||
private final String description; | |||
private final String mainBranchName; | |||
private final String url; | |||
public RepositoryDetails(Repository repository, String description, String mainBranchName, String url) { | |||
this.repository = repository; | |||
this.description = description; | |||
this.mainBranchName = mainBranchName; | |||
this.url = url; | |||
} | |||
public Repository getRepository() { | |||
return repository; | |||
} | |||
public String getDescription() { | |||
return description; | |||
} | |||
public String getMainBranchName() { | |||
return mainBranchName; | |||
} | |||
public String getUrl() { | |||
return url; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
RepositoryDetails that = (RepositoryDetails) o; | |||
return Objects.equals(repository, that.repository) && | |||
Objects.equals(description, that.description) && | |||
Objects.equals(mainBranchName, that.mainBranchName) && | |||
Objects.equals(url, that.url); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(repository, description, mainBranchName, url); | |||
} | |||
@Override | |||
public String toString() { | |||
return "RepositoryDetails{" + | |||
"repository=" + repository + | |||
", description='" + description + '\'' + | |||
", mainBranchName='" + mainBranchName + '\'' + | |||
", url='" + url + '\'' + | |||
'}'; | |||
} | |||
} | |||
class Organizations { | |||
private int total; | |||
private List<Organization> organizations; |
@@ -56,7 +56,7 @@ public class DefaultLdapGroupsProvider implements LdapGroupsProvider { | |||
*/ | |||
@Override | |||
public Collection<String> doGetGroups(Context context) { | |||
return getGroups(context.getServerKey(), context.getUsername()); | |||
return getGroups(context.serverKey(), context.username()); | |||
} | |||
private Collection<String> getGroups(String serverKey, String username) { |
@@ -55,7 +55,7 @@ public class DefaultLdapUsersProvider implements LdapUsersProvider { | |||
@Override | |||
public LdapUserDetails doGetUserDetails(Context context) { | |||
return getUserDetails(context.getServerKey(), context.getUsername()); | |||
return getUserDetails(context.serverKey(), context.username()); | |||
} | |||
/** |
@@ -26,27 +26,6 @@ public interface LdapGroupsProvider { | |||
Collection<String> doGetGroups(Context context); | |||
final class Context { | |||
private final String serverKey; | |||
private final String username; | |||
private final HttpServletRequest request; | |||
public Context(String serverKey, String username, HttpServletRequest request) { | |||
this.serverKey = serverKey; | |||
this.username = username; | |||
this.request = request; | |||
} | |||
public String getServerKey() { | |||
return serverKey; | |||
} | |||
public String getUsername() { | |||
return username; | |||
} | |||
public HttpServletRequest getRequest() { | |||
return request; | |||
} | |||
record Context(String serverKey, String username, HttpServletRequest request) { | |||
} | |||
} |
@@ -25,30 +25,7 @@ public interface LdapUsersProvider { | |||
LdapUserDetails doGetUserDetails(Context context); | |||
final class Context { | |||
private final String username; | |||
private final String serverKey; | |||
private final HttpServletRequest request; | |||
public Context(String serverKey, String username, HttpServletRequest request) { | |||
this.username = username; | |||
this.serverKey = serverKey; | |||
this.request = request; | |||
} | |||
public String getUsername() { | |||
return username; | |||
} | |||
public String getServerKey() { | |||
return serverKey; | |||
} | |||
public HttpServletRequest getRequest() { | |||
return request; | |||
} | |||
record Context(String serverKey, String username, HttpServletRequest request) { | |||
} | |||
} |
@@ -577,11 +577,11 @@ public class CeQueueImplTest { | |||
assertThat(task.getType()).isEqualTo(taskSubmit.getType()); | |||
if (taskSubmit.getSubmitterUuid() != null) { | |||
if (userDto == null) { | |||
assertThat(task.getSubmitter().getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().getLogin()).isNull(); | |||
assertThat(task.getSubmitter().uuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().login()).isNull(); | |||
} else { | |||
assertThat(task.getSubmitter().getUuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().getLogin()).isEqualTo(userDto.getLogin()); | |||
assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().login()).isEqualTo(userDto.getLogin()); | |||
} | |||
} | |||
} |
@@ -29,7 +29,7 @@ final class DequeBasedPath<T> implements PathAwareVisitor.Path<T>, Iterable<Path | |||
@Override | |||
public T current() { | |||
return deque.getFirst().getElement(); | |||
return deque.getFirst().element(); | |||
} | |||
@Override | |||
@@ -38,7 +38,7 @@ final class DequeBasedPath<T> implements PathAwareVisitor.Path<T>, Iterable<Path | |||
if (iterator.hasNext()) { | |||
iterator.next(); | |||
if (iterator.hasNext()) { | |||
return iterator.next().getElement(); | |||
return iterator.next().element(); | |||
} | |||
} | |||
throw new NoSuchElementException("Path is either empty or has only one element. There is no parent"); | |||
@@ -51,7 +51,7 @@ final class DequeBasedPath<T> implements PathAwareVisitor.Path<T>, Iterable<Path | |||
@Override | |||
public T root() { | |||
return deque.getLast().getElement(); | |||
return deque.getLast().element(); | |||
} | |||
@Override |
@@ -169,7 +169,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.component().getKey(), input.component().getType()); | |||
} | |||
} | |||
} |
@@ -116,11 +116,11 @@ public interface PathAwareVisitor<T> extends ComponentVisitor { | |||
/** | |||
* The Component on the path. | |||
*/ | |||
Component getComponent(); | |||
Component component(); | |||
/** | |||
* The stacked element for the Component of this PathElement. | |||
*/ | |||
T getElement(); | |||
T element(); | |||
} | |||
} |
@@ -19,25 +19,5 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.component; | |||
import javax.annotation.concurrent.Immutable; | |||
@Immutable | |||
final class PathElementImpl<T> implements PathAwareVisitor.PathElement<T> { | |||
private final Component component; | |||
private final T element; | |||
public PathElementImpl(Component component, T element) { | |||
this.component = component; | |||
this.element = element; | |||
} | |||
@Override | |||
public Component getComponent() { | |||
return component; | |||
} | |||
@Override | |||
public T getElement() { | |||
return element; | |||
} | |||
record PathElementImpl<T>(Component component, T element) implements PathAwareVisitor.PathElement<T> { | |||
} |
@@ -36,7 +36,6 @@ import java.util.Map; | |||
import java.util.Set; | |||
import java.util.stream.Collectors; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.apache.ibatis.session.ResultContext; | |||
import org.apache.ibatis.session.ResultHandler; | |||
import org.sonar.api.utils.log.Logger; | |||
@@ -178,8 +177,8 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
LOG.debug("{} files moves found", electedMatches.size()); | |||
for (Match validatedMatch : electedMatches) { | |||
movedFilesRepository.setOriginalFile( | |||
reportFilesByUuid.get(validatedMatch.getReportUuid()), | |||
toOriginalFile(dbFilesByUuid.get(validatedMatch.getDbUuid()))); | |||
reportFilesByUuid.get(validatedMatch.reportUuid()), | |||
toOriginalFile(dbFilesByUuid.get(validatedMatch.dbUuid()))); | |||
LOG.trace("File move found: {}", validatedMatch); | |||
} | |||
} | |||
@@ -192,7 +191,7 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
} else { | |||
Set<String> reallyAddedFileUuids = new HashSet<>(addedFileUuids); | |||
for (Match electedMatch : electedMatches) { | |||
reallyAddedFileUuids.remove(electedMatch.getReportUuid()); | |||
reallyAddedFileUuids.remove(electedMatch.reportUuid()); | |||
} | |||
reallyAddedFileUuids.stream() | |||
.map(reportFilesByUuid::get) | |||
@@ -209,7 +208,7 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
builder.add(new DbComponent(row.getKey(), row.getUuid(), row.getPath(), row.getLineCount())); | |||
}); | |||
return builder.build().stream() | |||
.collect(MoreCollectors.uniqueIndex(DbComponent::getUuid)); | |||
.collect(MoreCollectors.uniqueIndex(DbComponent::uuid)); | |||
} | |||
} | |||
@@ -245,7 +244,7 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
ScoreMatrix.ScoreFile[] removedFiles = removedFileUuids.stream() | |||
.map(key -> { | |||
DbComponent dbComponent = dtosByUuid.get(key); | |||
return new ScoreMatrix.ScoreFile(dbComponent.getUuid(), dbComponent.getLineCount()); | |||
return new ScoreMatrix.ScoreFile(dbComponent.uuid(), dbComponent.lineCount()); | |||
}) | |||
.toArray(ScoreMatrix.ScoreFile[]::new); | |||
@@ -353,13 +352,13 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
} else { | |||
matchesPerFileForScore.clear(); | |||
for (Match match : matchesToValidate) { | |||
matchesPerFileForScore.put(match.getDbUuid(), match); | |||
matchesPerFileForScore.put(match.getReportUuid(), match); | |||
matchesPerFileForScore.put(match.dbUuid(), match); | |||
matchesPerFileForScore.put(match.reportUuid(), match); | |||
} | |||
// validate non-ambiguous matches (i.e. the match is the only match of either the db file and the report file) | |||
for (Match match : matchesToValidate) { | |||
int dbFileMatchesCount = matchesPerFileForScore.get(match.getDbUuid()).size(); | |||
int reportFileMatchesCount = matchesPerFileForScore.get(match.getReportUuid()).size(); | |||
int dbFileMatchesCount = matchesPerFileForScore.get(match.dbUuid()).size(); | |||
int reportFileMatchesCount = matchesPerFileForScore.get(match.reportUuid()).size(); | |||
if (dbFileMatchesCount == 1 && reportFileMatchesCount == 1) { | |||
electedMatches.add(match); | |||
} | |||
@@ -368,38 +367,10 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
} | |||
private static MovedFilesRepository.OriginalFile toOriginalFile(DbComponent dbComponent) { | |||
return new MovedFilesRepository.OriginalFile(dbComponent.getUuid(), dbComponent.getKey()); | |||
return new MovedFilesRepository.OriginalFile(dbComponent.uuid(), dbComponent.key()); | |||
} | |||
@Immutable | |||
public static final class DbComponent { | |||
private final String key; | |||
private final String uuid; | |||
private final String path; | |||
private final int lineCount; | |||
public DbComponent(String key, String uuid, String path, int lineCount) { | |||
this.key = key; | |||
this.uuid = uuid; | |||
this.path = path; | |||
this.lineCount = lineCount; | |||
} | |||
public String getKey() { | |||
return key; | |||
} | |||
public String getUuid() { | |||
return uuid; | |||
} | |||
public String getPath() { | |||
return path; | |||
} | |||
public int getLineCount() { | |||
return lineCount; | |||
} | |||
public record DbComponent(String key, String uuid, String path, int lineCount) { | |||
} | |||
private static class ElectedMatches implements Iterable<Match> { | |||
@@ -413,8 +384,8 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
public void add(Match match) { | |||
matches.add(match); | |||
matchedFileUuids.add(match.getDbUuid()); | |||
matchedFileUuids.add(match.getReportUuid()); | |||
matchedFileUuids.add(match.dbUuid()); | |||
matchedFileUuids.add(match.reportUuid()); | |||
} | |||
public List<Match> filter(Collection<Match> matches) { | |||
@@ -422,7 +393,7 @@ public class FileMoveDetectionStep implements ComputationStep { | |||
} | |||
private boolean notAlreadyMatched(Match input) { | |||
return !(matchedFileUuids.contains(input.getDbUuid()) || matchedFileUuids.contains(input.getReportUuid())); | |||
return !(matchedFileUuids.contains(input.dbUuid()) || matchedFileUuids.contains(input.reportUuid())); | |||
} | |||
@Override |
@@ -19,45 +19,7 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.filemove; | |||
import java.util.Objects; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
@Immutable | |||
final class Match { | |||
private final String dbUuid; | |||
private final String reportUuid; | |||
Match(String dbUuid, String reportUuid) { | |||
this.dbUuid = dbUuid; | |||
this.reportUuid = reportUuid; | |||
} | |||
public String getDbUuid() { | |||
return dbUuid; | |||
} | |||
public String getReportUuid() { | |||
return reportUuid; | |||
} | |||
@Override | |||
public boolean equals(@Nullable Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
Match match = (Match) o; | |||
return dbUuid.equals(match.dbUuid) && reportUuid.equals(match.reportUuid); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(dbUuid, reportUuid); | |||
} | |||
record Match(String dbUuid, String reportUuid) { | |||
@Override | |||
public String toString() { | |||
return '{' + dbUuid + "=>" + reportUuid + '}'; |
@@ -42,23 +42,12 @@ public interface MovedFilesRepository { | |||
*/ | |||
Optional<OriginalFile> getOriginalPullRequestFile(Component file); | |||
final class OriginalFile { | |||
private final String uuid; | |||
private final String key; | |||
record OriginalFile(String uuid, String key) { | |||
public OriginalFile(String uuid, String key) { | |||
this.uuid = requireNonNull(uuid, "uuid can not be null"); | |||
this.key = requireNonNull(key, "key can not be null"); | |||
} | |||
public String getUuid() { | |||
return uuid; | |||
} | |||
public String getKey() { | |||
return key; | |||
} | |||
@Override | |||
public boolean equals(@Nullable Object o) { | |||
if (this == o) { | |||
@@ -79,9 +68,9 @@ public interface MovedFilesRepository { | |||
@Override | |||
public String toString() { | |||
return "OriginalFile{" + | |||
"uuid='" + uuid + '\'' + | |||
", key='" + key + '\'' + | |||
'}'; | |||
"uuid='" + uuid + '\'' + | |||
", key='" + key + '\'' + | |||
'}'; | |||
} | |||
} | |||
} |
@@ -161,7 +161,7 @@ public class PullRequestFileMoveDetectionStep implements ComputationStep { | |||
private static ResultHandler<FileMoveRowDto> accumulateFilesForFileMove(Map<String, DbComponent> accumulator) { | |||
return resultContext -> { | |||
DbComponent component = rowToDbComponent(resultContext.getResultObject()); | |||
accumulator.put(component.getUuid(), component); | |||
accumulator.put(component.uuid(), component); | |||
}; | |||
} | |||
@@ -177,7 +177,7 @@ public class PullRequestFileMoveDetectionStep implements ComputationStep { | |||
private static Map<String, DbComponent> toDbFilesByPathReferenceMap(Collection<DbComponent> dbFiles) { | |||
return dbFiles | |||
.stream() | |||
.collect(toMap(DbComponent::getPath, identity())); | |||
.collect(toMap(DbComponent::path, identity())); | |||
} | |||
private static Map<String, Component> getReportFilesByUuid(Component root) { | |||
@@ -195,6 +195,6 @@ public class PullRequestFileMoveDetectionStep implements ComputationStep { | |||
} | |||
private static OriginalFile toOriginalFile(DbComponent dbComponent) { | |||
return new OriginalFile(dbComponent.getUuid(), dbComponent.getKey()); | |||
return new OriginalFile(dbComponent.uuid(), dbComponent.key()); | |||
} | |||
} |
@@ -32,10 +32,10 @@ public final class LinesAndConditionsWithUncoveredCounter extends ElementsAndCov | |||
@Override | |||
protected void initializeForSupportedLeaf(CounterInitializationContext counterContext) { | |||
this.elements = getLongMeasureValue(counterContext, metricKeys.getLines()) | |||
+ getLongMeasureValue(counterContext, metricKeys.getConditions()); | |||
this.elements = getLongMeasureValue(counterContext, metricKeys.lines()) | |||
+ getLongMeasureValue(counterContext, metricKeys.conditions()); | |||
this.coveredElements = this.elements | |||
- getLongMeasureValue(counterContext, metricKeys.getUncoveredLines()) | |||
- getLongMeasureValue(counterContext, metricKeys.getUncoveredConditions()); | |||
- getLongMeasureValue(counterContext, metricKeys.uncoveredLines()) | |||
- getLongMeasureValue(counterContext, metricKeys.uncoveredConditions()); | |||
} | |||
} |
@@ -19,37 +19,13 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.formula.coverage; | |||
import javax.annotation.concurrent.Immutable; | |||
import static java.util.Objects.requireNonNull; | |||
@Immutable | |||
public final class LinesAndConditionsWithUncoveredMetricKeys { | |||
private final String lines; | |||
private final String conditions; | |||
private final String uncoveredLines; | |||
private final String uncoveredConditions; | |||
public record LinesAndConditionsWithUncoveredMetricKeys(String lines, String conditions, String uncoveredLines, String uncoveredConditions) { | |||
public LinesAndConditionsWithUncoveredMetricKeys(String lines, String conditions, String uncoveredLines, String uncoveredConditions) { | |||
this.lines = requireNonNull(lines); | |||
this.conditions = requireNonNull(conditions); | |||
this.uncoveredLines = requireNonNull(uncoveredLines); | |||
this.uncoveredConditions = requireNonNull(uncoveredConditions); | |||
} | |||
public String getLines() { | |||
return lines; | |||
} | |||
public String getConditions() { | |||
return conditions; | |||
} | |||
public String getUncoveredLines() { | |||
return uncoveredLines; | |||
} | |||
public String getUncoveredConditions() { | |||
return uncoveredConditions; | |||
} | |||
} |
@@ -32,7 +32,7 @@ public final class SingleWithUncoveredCounter extends ElementsAndCoveredElements | |||
@Override | |||
protected void initializeForSupportedLeaf(CounterInitializationContext counterContext) { | |||
this.elements = getLongMeasureValue(counterContext, metricKeys.getCovered()); | |||
this.coveredElements = this.elements - getLongMeasureValue(counterContext, metricKeys.getUncovered()); | |||
this.elements = getLongMeasureValue(counterContext, metricKeys.covered()); | |||
this.coveredElements = this.elements - getLongMeasureValue(counterContext, metricKeys.uncovered()); | |||
} | |||
} |
@@ -19,25 +19,11 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.formula.coverage; | |||
import javax.annotation.concurrent.Immutable; | |||
import static java.util.Objects.requireNonNull; | |||
@Immutable | |||
public final class SingleWithUncoveredMetricKeys { | |||
private final String covered; | |||
private final String uncovered; | |||
public record SingleWithUncoveredMetricKeys(String covered, String uncovered) { | |||
public SingleWithUncoveredMetricKeys(String covered, String uncovered) { | |||
this.covered = requireNonNull(covered); | |||
this.uncovered = requireNonNull(uncovered); | |||
} | |||
public String getCovered() { | |||
return covered; | |||
} | |||
public String getUncovered() { | |||
return uncovered; | |||
} | |||
} |
@@ -44,7 +44,7 @@ public abstract class BaseInputFactory { | |||
BaseLazyInput(DbClient dbClient, Component component, @Nullable MovedFilesRepository.OriginalFile originalFile) { | |||
this.dbClient = dbClient; | |||
this.component = component; | |||
this.effectiveUuid = originalFile == null ? component.getUuid() : originalFile.getUuid(); | |||
this.effectiveUuid = originalFile == null ? component.getUuid() : originalFile.uuid(); | |||
} | |||
@Override |
@@ -51,9 +51,10 @@ public class MovedIssueVisitor extends IssueVisitor { | |||
"Issue %s for component %s has a different component key but no original file exist in MovedFilesRepository", | |||
issue, component); | |||
OriginalFile originalFile = originalFileOptional.get(); | |||
checkState(originalFile.getUuid().equals(issue.componentUuid()), | |||
String fileUuid = originalFile.uuid(); | |||
checkState(fileUuid.equals(issue.componentUuid()), | |||
"Issue %s doesn't belong to file %s registered as original file of current file %s", | |||
issue, originalFile.getUuid(), component); | |||
issue, fileUuid, component); | |||
// changes the issue's component uuid, and set issue as changed, to enforce it is persisted to DB | |||
issueUpdater.setIssueComponent(issue, component.getUuid(), component.getKey(), new Date(analysisMetadataHolder.getAnalysisDate())); |
@@ -37,7 +37,7 @@ public class RemoveProcessedComponentsVisitor extends IssueVisitor { | |||
componentsWithUnprocessedIssues.remove(component.getUuid()); | |||
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component); | |||
if (originalFile.isPresent()) { | |||
componentsWithUnprocessedIssues.remove(originalFile.get().getUuid()); | |||
componentsWithUnprocessedIssues.remove(originalFile.get().uuid()); | |||
} | |||
} | |||
} |
@@ -71,7 +71,7 @@ public class TrackerTargetBranchInputFactory { | |||
private Optional<String> getOriginalComponentKey(Component component) { | |||
return movedFilesRepository | |||
.getOriginalPullRequestFile(component) | |||
.map(OriginalFile::getKey); | |||
.map(OriginalFile::key); | |||
} | |||
private class TargetLazyInput extends LazyInput<DefaultIssue> { |
@@ -19,41 +19,19 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.notification; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import static java.util.Objects.requireNonNull; | |||
public class ReportAnalysisFailureNotificationBuilder { | |||
private final Project project; | |||
private final Task task; | |||
private final String errorMessage; | |||
public record ReportAnalysisFailureNotificationBuilder(Project project, Task task, String errorMessage) { | |||
public ReportAnalysisFailureNotificationBuilder(Project project, Task task, @Nullable String errorMessage) { | |||
this.project = requireNonNull(project, "project can't be null"); | |||
this.task = requireNonNull(task, "task can't be null"); | |||
this.errorMessage = errorMessage; | |||
} | |||
public Project getProject() { | |||
return project; | |||
} | |||
public Task getTask() { | |||
return task; | |||
} | |||
@CheckForNull | |||
public String getErrorMessage() { | |||
return errorMessage; | |||
} | |||
public static final class Project { | |||
private final String uuid; | |||
private final String key; | |||
private final String name; | |||
private final String branchName; | |||
public record Project(String uuid, String key, String name, String branchName) { | |||
public Project(String uuid, String key, String name, @Nullable String branchName) { | |||
this.uuid = requireNonNull(uuid, "uuid can't be null"); | |||
this.key = requireNonNull(key, "key can't be null"); | |||
@@ -61,45 +39,13 @@ public class ReportAnalysisFailureNotificationBuilder { | |||
this.branchName = branchName; | |||
} | |||
public String getUuid() { | |||
return uuid; | |||
} | |||
public String getKey() { | |||
return key; | |||
} | |||
public String getName() { | |||
return name; | |||
} | |||
@CheckForNull | |||
public String getBranchName() { | |||
return branchName; | |||
} | |||
} | |||
public static final class Task { | |||
private final String uuid; | |||
private final long createdAt; | |||
private final long failedAt; | |||
public record Task(String uuid, long createdAt, long failedAt) { | |||
public Task(String uuid, long createdAt, long failedAt) { | |||
this.uuid = requireNonNull(uuid, "uuid can't be null"); | |||
this.createdAt = createdAt; | |||
this.failedAt = failedAt; | |||
} | |||
public String getUuid() { | |||
return uuid; | |||
} | |||
public long getCreatedAt() { | |||
return createdAt; | |||
} | |||
public long getFailedAt() { | |||
return failedAt; | |||
} | |||
} | |||
} |
@@ -50,8 +50,8 @@ public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemp | |||
} | |||
ReportAnalysisFailureNotificationBuilder taskFailureNotification = serializer.fromNotification((ReportAnalysisFailureNotification) notification); | |||
String projectUuid = taskFailureNotification.getProject().getUuid(); | |||
String projectFullName = computeProjectFullName(taskFailureNotification.getProject()); | |||
String projectUuid = taskFailureNotification.project().uuid(); | |||
String projectFullName = computeProjectFullName(taskFailureNotification.project()); | |||
return new EmailMessage() | |||
.setMessageId(notification.getType() + "/" + projectUuid) | |||
@@ -60,11 +60,11 @@ public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemp | |||
} | |||
private static String computeProjectFullName(ReportAnalysisFailureNotificationBuilder.Project project) { | |||
String branchName = project.getBranchName(); | |||
String branchName = project.branchName(); | |||
if (branchName != null) { | |||
return String.format("%s (%s)", project.getName(), branchName); | |||
return String.format("%s (%s)", project.name(), branchName); | |||
} | |||
return project.getName(); | |||
return project.name(); | |||
} | |||
private static String subject(String projectFullName) { | |||
@@ -72,23 +72,23 @@ public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemp | |||
} | |||
private String message(String projectFullName, ReportAnalysisFailureNotificationBuilder taskFailureNotification) { | |||
ReportAnalysisFailureNotificationBuilder.Project project = taskFailureNotification.getProject(); | |||
ReportAnalysisFailureNotificationBuilder.Task task = taskFailureNotification.getTask(); | |||
ReportAnalysisFailureNotificationBuilder.Project project = taskFailureNotification.project(); | |||
ReportAnalysisFailureNotificationBuilder.Task task = taskFailureNotification.task(); | |||
StringBuilder res = new StringBuilder(); | |||
res.append("Project:").append(TAB).append(projectFullName).append(LINE_RETURN); | |||
res.append("Background task:").append(TAB).append(task.getUuid()).append(LINE_RETURN); | |||
res.append("Submission time:").append(TAB).append(formatDateTime(task.getCreatedAt())).append(LINE_RETURN); | |||
res.append("Failure time:").append(TAB).append(formatDateTime(task.getFailedAt())).append(LINE_RETURN); | |||
res.append("Background task:").append(TAB).append(task.uuid()).append(LINE_RETURN); | |||
res.append("Submission time:").append(TAB).append(formatDateTime(task.createdAt())).append(LINE_RETURN); | |||
res.append("Failure time:").append(TAB).append(formatDateTime(task.failedAt())).append(LINE_RETURN); | |||
String errorMessage = taskFailureNotification.getErrorMessage(); | |||
String errorMessage = taskFailureNotification.errorMessage(); | |||
if (errorMessage != null) { | |||
res.append(LINE_RETURN); | |||
res.append("Error message:").append(TAB).append(errorMessage).append(LINE_RETURN); | |||
} | |||
res.append(LINE_RETURN); | |||
res.append("More details at: ").append(String.format("%s/project/background_tasks?id=%s", settings.getServerBaseURL(), encode(project.getKey()))); | |||
res.append("More details at: ").append(String.format("%s/project/background_tasks?id=%s", settings.getServerBaseURL(), encode(project.key()))); | |||
return res.toString(); | |||
} |
@@ -83,6 +83,6 @@ public class ReportAnalysisFailureNotificationHandler extends EmailNotificationH | |||
return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS) | |||
.stream() | |||
.flatMap(emailRecipient -> notifications.stream() | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.getEmail(), notification))); | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification))); | |||
} | |||
} |
@@ -35,14 +35,14 @@ public class ReportAnalysisFailureNotificationSerializerImpl implements ReportAn | |||
public ReportAnalysisFailureNotification toNotification(ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder) { | |||
ReportAnalysisFailureNotification notification = new ReportAnalysisFailureNotification(); | |||
notification | |||
.setFieldValue(FIELD_PROJECT_UUID, reportAnalysisFailureNotificationBuilder.getProject().getUuid()) | |||
.setFieldValue(FIELD_PROJECT_KEY, reportAnalysisFailureNotificationBuilder.getProject().getKey()) | |||
.setFieldValue(FIELD_PROJECT_NAME, reportAnalysisFailureNotificationBuilder.getProject().getName()) | |||
.setFieldValue(FIELD_PROJECT_BRANCH, reportAnalysisFailureNotificationBuilder.getProject().getBranchName()) | |||
.setFieldValue(FIELD_TASK_UUID, reportAnalysisFailureNotificationBuilder.getTask().getUuid()) | |||
.setFieldValue(FIELD_TASK_CREATED_AT, valueOf(reportAnalysisFailureNotificationBuilder.getTask().getCreatedAt())) | |||
.setFieldValue(FIELD_TASK_FAILED_AT, valueOf(reportAnalysisFailureNotificationBuilder.getTask().getFailedAt())) | |||
.setFieldValue(FIELD_ERROR_MESSAGE, reportAnalysisFailureNotificationBuilder.getErrorMessage()); | |||
.setFieldValue(FIELD_PROJECT_UUID, reportAnalysisFailureNotificationBuilder.project().uuid()) | |||
.setFieldValue(FIELD_PROJECT_KEY, reportAnalysisFailureNotificationBuilder.project().key()) | |||
.setFieldValue(FIELD_PROJECT_NAME, reportAnalysisFailureNotificationBuilder.project().name()) | |||
.setFieldValue(FIELD_PROJECT_BRANCH, reportAnalysisFailureNotificationBuilder.project().branchName()) | |||
.setFieldValue(FIELD_TASK_UUID, reportAnalysisFailureNotificationBuilder.task().uuid()) | |||
.setFieldValue(FIELD_TASK_CREATED_AT, valueOf(reportAnalysisFailureNotificationBuilder.task().createdAt())) | |||
.setFieldValue(FIELD_TASK_FAILED_AT, valueOf(reportAnalysisFailureNotificationBuilder.task().failedAt())) | |||
.setFieldValue(FIELD_ERROR_MESSAGE, reportAnalysisFailureNotificationBuilder.errorMessage()); | |||
return notification; | |||
} | |||
@@ -22,36 +22,21 @@ package org.sonar.ce.task.projectanalysis.qualitygate; | |||
import com.google.common.base.MoreObjects; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.ce.task.projectanalysis.measure.Measure; | |||
import static java.util.Objects.requireNonNull; | |||
@Immutable | |||
public final class EvaluationResult { | |||
private final Measure.Level level; | |||
@CheckForNull | |||
private final Comparable<?> value; | |||
public record EvaluationResult(Measure.Level level, @CheckForNull Comparable<?> value) { | |||
public EvaluationResult(Measure.Level level, @Nullable Comparable<?> value) { | |||
this.level = requireNonNull(level); | |||
this.value = value; | |||
} | |||
public Measure.Level getLevel() { | |||
return level; | |||
} | |||
@CheckForNull | |||
public Comparable<?> getValue() { | |||
return value; | |||
} | |||
@Override | |||
public String toString() { | |||
return MoreObjects.toStringHelper(this) | |||
.add("level", level) | |||
.add("value", value) | |||
.toString(); | |||
.add("level", level) | |||
.add("value", value) | |||
.toString(); | |||
} | |||
} |
@@ -47,7 +47,7 @@ public final class EvaluationResultTextConverterImpl implements EvaluationResult | |||
@CheckForNull | |||
public String asText(Condition condition, EvaluationResult evaluationResult) { | |||
requireNonNull(condition); | |||
if (evaluationResult.getLevel() == Measure.Level.OK) { | |||
if (evaluationResult.level() == Measure.Level.OK) { | |||
return null; | |||
} | |||
return getAlertLabel(condition); |
@@ -77,7 +77,7 @@ public class ScmInfoDbLoader { | |||
if (!analysisMetadataHolder.isFirstAnalysis() && !analysisMetadataHolder.isPullRequest() && !isReferenceBranch()) { | |||
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(file); | |||
if (originalFile.isPresent()) { | |||
return originalFile.map(MovedFilesRepository.OriginalFile::getUuid); | |||
return originalFile.map(MovedFilesRepository.OriginalFile::uuid); | |||
} | |||
return Optional.of(file.getUuid()); | |||
} |
@@ -53,7 +53,7 @@ public class FileSourceDataWarnings { | |||
requireNonNull(file, "file can't be null"); | |||
requireNonNull(readError, "readError can't be null"); | |||
fileErrorsPerData.compute(readError.getData(), (data, existingList) -> { | |||
fileErrorsPerData.compute(readError.data(), (data, existingList) -> { | |||
Set<Component> res = existingList == null ? new HashSet<>() : existingList; | |||
res.add(file); | |||
return res; |
@@ -74,7 +74,7 @@ public class SourceLinesDiffImpl implements SourceLinesDiff { | |||
uuid = newCodeReferenceBranchComponentUuids.getComponentUuid(component.getKey()); | |||
} else { | |||
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component); | |||
uuid = originalFile.map(MovedFilesRepository.OriginalFile::getUuid).orElse(component.getUuid()); | |||
uuid = originalFile.map(MovedFilesRepository.OriginalFile::uuid).orElse(component.getUuid()); | |||
} | |||
if (uuid == null) { |
@@ -19,9 +19,7 @@ | |||
*/ | |||
package org.sonar.ce.task.projectanalysis.source.linereader; | |||
import java.util.Objects; | |||
import java.util.Optional; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.db.protobuf.DbFileSources; | |||
import static com.google.common.base.Preconditions.checkArgument; | |||
@@ -36,24 +34,10 @@ public interface LineReader { | |||
COVERAGE, DUPLICATION, HIGHLIGHTING, SCM, SYMBOLS | |||
} | |||
@Immutable | |||
final class ReadError { | |||
private final Data data; | |||
private final int line; | |||
public ReadError(Data data, int line) { | |||
record ReadError(Data data, int line) { | |||
public ReadError { | |||
requireNonNull(data); | |||
checkArgument(line >= 0); | |||
this.data = data; | |||
this.line = line; | |||
} | |||
public Data getData() { | |||
return data; | |||
} | |||
public int getLine() { | |||
return line; | |||
} | |||
@Override | |||
@@ -69,11 +53,6 @@ public interface LineReader { | |||
data == readError.data; | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(data, line); | |||
} | |||
@Override | |||
public String toString() { | |||
return "ReadError{" + |
@@ -383,10 +383,10 @@ public class PersistComponentsStep implements ComputationStep { | |||
componentDto.setBranchUuid(path.root().getDto().uuid()); | |||
ComponentDto parentModule = StreamSupport.stream(path.getCurrentPath().spliterator(), false) | |||
.filter(p -> p.getComponent().getType() == Component.Type.PROJECT) | |||
.filter(p -> p.component().getType() == Component.Type.PROJECT) | |||
.findFirst() | |||
.get() | |||
.getElement().getDto(); | |||
.element().getDto(); | |||
componentDto.setUuidPath(formatUuidPathFromParent(path.parent().getDto())); | |||
componentDto.setRootUuid(parentModule.uuid()); | |||
componentDto.setModuleUuid(parentModule.uuid()); |
@@ -184,7 +184,7 @@ public class QualityGateMeasuresStep implements ComputationStep { | |||
builder.addLabel(text); | |||
Measure updatedMeasure = Measure.updatedMeasureBuilder(measure.get()) | |||
.setQualityGateStatus(new QualityGateStatus(finalMetricEvaluationResult.evaluationResult.getLevel(), text)) | |||
.setQualityGateStatus(new QualityGateStatus(finalMetricEvaluationResult.evaluationResult.level(), text)) | |||
.create(); | |||
measureRepository.update(project, metric, updatedMeasure); | |||
@@ -198,7 +198,7 @@ public class QualityGateMeasuresStep implements ComputationStep { | |||
MetricEvaluationResult metricEvaluationResult = null; | |||
for (Condition newCondition : conditions) { | |||
EvaluationResult newEvaluationResult = conditionEvaluator.evaluate(newCondition, measure); | |||
if (metricEvaluationResult == null || newEvaluationResult.getLevel().ordinal() > metricEvaluationResult.evaluationResult.getLevel().ordinal()) { | |||
if (metricEvaluationResult == null || newEvaluationResult.level().ordinal() > metricEvaluationResult.evaluationResult.level().ordinal()) { | |||
metricEvaluationResult = new MetricEvaluationResult(newEvaluationResult, newCondition); | |||
} | |||
} | |||
@@ -244,12 +244,12 @@ public class QualityGateMeasuresStep implements ComputationStep { | |||
} | |||
public void addEvaluatedCondition(MetricEvaluationResult metricEvaluationResult) { | |||
Measure.Level level = metricEvaluationResult.evaluationResult.getLevel(); | |||
Measure.Level level = metricEvaluationResult.evaluationResult.level(); | |||
if (Measure.Level.ERROR == level) { | |||
globalLevel = Measure.Level.ERROR; | |||
} | |||
evaluatedConditions.add( | |||
new EvaluatedCondition(metricEvaluationResult.condition, level, metricEvaluationResult.evaluationResult.getValue())); | |||
new EvaluatedCondition(metricEvaluationResult.condition, level, metricEvaluationResult.evaluationResult.value())); | |||
} | |||
public List<EvaluatedCondition> getEvaluatedConditions() { |
@@ -46,7 +46,7 @@ public class SmallChangesetQualityGateSpecialCase { | |||
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) { | |||
return metricEvaluationResult != null | |||
&& metricEvaluationResult.evaluationResult.getLevel() != Measure.Level.OK | |||
&& metricEvaluationResult.evaluationResult.level() != Measure.Level.OK | |||
&& METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric().getKey()) | |||
&& config.getConfiguration().getBoolean(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES).orElse(true) | |||
&& isSmallChangeset(project); | |||
@@ -54,7 +54,7 @@ public class SmallChangesetQualityGateSpecialCase { | |||
MetricEvaluationResult apply(MetricEvaluationResult metricEvaluationResult) { | |||
return new MetricEvaluationResult( | |||
new EvaluationResult(Measure.Level.OK, metricEvaluationResult.evaluationResult.getValue()), metricEvaluationResult.condition); | |||
new EvaluationResult(Measure.Level.OK, metricEvaluationResult.evaluationResult.value()), metricEvaluationResult.condition); | |||
} | |||
private boolean isSmallChangeset(Component project) { |
@@ -158,7 +158,7 @@ public class ExportIssuesStep implements ComputationStep { | |||
String ruleUuid = rs.getString(2); | |||
String ruleKey = rs.getString(3); | |||
String repositoryKey = rs.getString(4); | |||
builder.setRuleRef(ruleRegistrar.register(ruleUuid, repositoryKey, ruleKey).getRef()); | |||
builder.setRuleRef(ruleRegistrar.register(ruleUuid, repositoryKey, ruleKey).ref()); | |||
} | |||
private static void setLocations(ProjectDump.Issue.Builder builder, ResultSet rs, String issueUuid) throws SQLException { |
@@ -61,9 +61,9 @@ public class ExportRuleStep implements ComputationStep { | |||
private static ProjectDump.Rule toRuleMessage(ProjectDump.Rule.Builder ruleBuilder, Rule rule) { | |||
ruleBuilder.clear(); | |||
return ruleBuilder | |||
.setRef(rule.getRef()) | |||
.setKey(rule.getKey()) | |||
.setRepository(rule.getRepository()) | |||
.setRef(rule.ref()) | |||
.setKey(rule.key()) | |||
.setRepository(rule.repository()) | |||
.build(); | |||
} | |||
} |
@@ -21,34 +21,16 @@ package org.sonar.ce.task.projectexport.rule; | |||
import java.util.Objects; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
import static java.util.Objects.requireNonNull; | |||
@Immutable | |||
public final class Rule { | |||
private final String ref; | |||
private final String repository; | |||
private final String key; | |||
public record Rule(String ref, String repository, String key) { | |||
public Rule(String ref, String repository, String key) { | |||
this.ref = ref; | |||
this.repository = requireNonNull(repository, "repository can not be null"); | |||
this.key = requireNonNull(key, "key can not be null"); | |||
} | |||
public String getRef() { | |||
return ref; | |||
} | |||
public String getRepository() { | |||
return repository; | |||
} | |||
public String getKey() { | |||
return key; | |||
} | |||
@Override | |||
public boolean equals(@Nullable Object o) { | |||
if (this == o) { |
@@ -37,10 +37,10 @@ public class RuleRepositoryImpl implements RuleRepository { | |||
Rule rule = rulesByUuid.get(ref); | |||
if (rule != null) { | |||
if (!ruleKey.repository().equals(rule.getRepository()) || !ruleKey.rule().equals(rule.getKey())) { | |||
if (!ruleKey.repository().equals(rule.repository()) || !ruleKey.rule().equals(rule.key())) { | |||
throw new IllegalArgumentException(format( | |||
"Specified RuleKey '%s' is not equal to the one already registered in repository for ref %s: '%s'", | |||
ruleKey, ref, RuleKey.of(rule.getRepository(), rule.getKey()))); | |||
ruleKey, ref, RuleKey.of(rule.repository(), rule.key()))); | |||
} | |||
return rule; | |||
} |
@@ -85,7 +85,7 @@ class CallRecorderPathAwareVisitor extends PathAwareVisitorAdapter<Integer> { | |||
} | |||
private static List<Integer> toValueList(Path<Integer> path) { | |||
return StreamSupport.stream(path.getCurrentPath().spliterator(), false).map(PathElement::getElement).collect(Collectors.toList()); | |||
return StreamSupport.stream(path.getCurrentPath().spliterator(), false).map(PathElement::element).collect(Collectors.toList()); | |||
} | |||
private static Integer getParent(Path<Integer> path) { |
@@ -340,8 +340,8 @@ public class FileMoveDetectionStepTest { | |||
assertThat(movedFilesRepository.getComponentsWithOriginal()).containsExactly(file2); | |||
MovedFilesRepository.OriginalFile originalFile = movedFilesRepository.getOriginalFile(file2).get(); | |||
assertThat(originalFile.getKey()).isEqualTo(dtos[0].getKey()); | |||
assertThat(originalFile.getUuid()).isEqualTo(dtos[0].uuid()); | |||
assertThat(originalFile.key()).isEqualTo(dtos[0].getKey()); | |||
assertThat(originalFile.uuid()).isEqualTo(dtos[0].uuid()); | |||
assertThat(addedFileRepository.getComponents()).isEmpty(); | |||
verifyStatistics(context, 1, 1, 1, 1); | |||
} | |||
@@ -505,11 +505,11 @@ public class FileMoveDetectionStepTest { | |||
assertThat(movedFilesRepository.getComponentsWithOriginal()).containsOnly(file3, file6); | |||
MovedFilesRepository.OriginalFile originalFile2 = movedFilesRepository.getOriginalFile(file3).get(); | |||
assertThat(originalFile2.getKey()).isEqualTo(dtos[0].getKey()); | |||
assertThat(originalFile2.getUuid()).isEqualTo(dtos[0].uuid()); | |||
assertThat(originalFile2.key()).isEqualTo(dtos[0].getKey()); | |||
assertThat(originalFile2.uuid()).isEqualTo(dtos[0].uuid()); | |||
MovedFilesRepository.OriginalFile originalFile5 = movedFilesRepository.getOriginalFile(file6).get(); | |||
assertThat(originalFile5.getKey()).isEqualTo(dtos[3].getKey()); | |||
assertThat(originalFile5.getUuid()).isEqualTo(dtos[3].uuid()); | |||
assertThat(originalFile5.key()).isEqualTo(dtos[3].getKey()); | |||
assertThat(originalFile5.uuid()).isEqualTo(dtos[3].uuid()); | |||
assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isGreaterThan(MIN_REQUIRED_SCORE); | |||
assertThat(addedFileRepository.getComponents()).isEmpty(); | |||
verifyStatistics(context, 3, 4, 2, 2); | |||
@@ -581,11 +581,11 @@ public class FileMoveDetectionStepTest { | |||
migrationRb1238, | |||
addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex); | |||
assertThat(movedFilesRepository.getOriginalFile(makeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex).get().getUuid()) | |||
assertThat(movedFilesRepository.getOriginalFile(makeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex).get().uuid()) | |||
.isEqualTo("uuid_" + "MakeComponentUuidNotNullOnDuplicationsIndex.java".hashCode()); | |||
assertThat(movedFilesRepository.getOriginalFile(migrationRb1238).get().getUuid()) | |||
assertThat(movedFilesRepository.getOriginalFile(migrationRb1238).get().uuid()) | |||
.isEqualTo("uuid_" + "1242_make_analysis_uuid_not_null_on_duplications_index.rb".hashCode()); | |||
assertThat(movedFilesRepository.getOriginalFile(addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex).get().getUuid()) | |||
assertThat(movedFilesRepository.getOriginalFile(addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex).get().uuid()) | |||
.isEqualTo("uuid_" + "AddComponentUuidColumnToDuplicationsIndex.java".hashCode()); | |||
verifyStatistics(context, comps.values().size(), 12, 6, 3); | |||
} |
@@ -42,12 +42,12 @@ public class MatchTest { | |||
@Test | |||
public void getDbKey_returns_first_constructor_argument() { | |||
assertThat(underTest.getDbUuid()).isEqualTo(SOME_KEY); | |||
assertThat(underTest.dbUuid()).isEqualTo(SOME_KEY); | |||
} | |||
@Test | |||
public void getDbKey_returns_second_constructor_argument() { | |||
assertThat(underTest.getReportUuid()).isEqualTo(SOME_REPORT_KEY); | |||
assertThat(underTest.reportUuid()).isEqualTo(SOME_REPORT_KEY); | |||
} | |||
@Test |
@@ -245,8 +245,8 @@ public class PullRequestFileMoveDetectionStepTest { | |||
assertThat(movedFilesRepository.getOriginalPullRequestFile(fileInReport)).isPresent(); | |||
OriginalFile detectedOriginalFile = movedFilesRepository.getOriginalPullRequestFile(fileInReport).get(); | |||
assertThat(detectedOriginalFile.getKey()).isEqualTo(originalFileInDatabase.getKey()); | |||
assertThat(detectedOriginalFile.getUuid()).isEqualTo(originalFileInDatabase.getUuid()); | |||
assertThat(detectedOriginalFile.key()).isEqualTo(originalFileInDatabase.getKey()); | |||
assertThat(detectedOriginalFile.uuid()).isEqualTo(originalFileInDatabase.getUuid()); | |||
} | |||
private Map<String, Component> initializeTargetBranchDatabaseComponents(Set<FileReference> references) { |
@@ -103,7 +103,7 @@ public class MovedIssueVisitorTest { | |||
@Test | |||
public void onIssue_update_component_and_module_fields_to_component_and_flag_issue_has_changed() { | |||
MovedFilesRepository.OriginalFile originalFile = new MovedFilesRepository.OriginalFile("original uuid", "original key"); | |||
DefaultIssue issue = mockIssue(originalFile.getUuid()); | |||
DefaultIssue issue = mockIssue(originalFile.uuid()); | |||
when(movedFilesRepository.getOriginalFile(FILE)) | |||
.thenReturn(Optional.of(originalFile)); | |||
@@ -0,0 +1,68 @@ | |||
/* | |||
* SonarQube | |||
* Copyright (C) 2009-2023 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.notification; | |||
import org.junit.Test; | |||
import org.sonar.api.config.EmailSettings; | |||
import org.sonar.server.qualitygate.notification.QGChangeNotification; | |||
import static org.assertj.core.api.Assertions.assertThat; | |||
import static org.mockito.Mockito.mock; | |||
import static org.mockito.Mockito.when; | |||
public class ReportAnalysisFailureNotificationEmailTemplateTest { | |||
ReportAnalysisFailureNotificationSerializer serializer = new ReportAnalysisFailureNotificationSerializerImpl(); | |||
EmailSettings settings = mock(EmailSettings.class); | |||
ReportAnalysisFailureNotificationEmailTemplate underTest = new ReportAnalysisFailureNotificationEmailTemplate(serializer, settings); | |||
@Test | |||
public void should_not_format_other_than_analysis_failure() { | |||
assertThat(underTest.format(new QGChangeNotification())).isNull(); | |||
} | |||
@Test | |||
public void check_formatting() { | |||
ReportAnalysisFailureNotification notification = mock(ReportAnalysisFailureNotification.class); | |||
when(notification.getFieldValue("project.uuid")).thenReturn("uuid"); | |||
when(notification.getFieldValue("project.name")).thenReturn("name"); | |||
when(notification.getFieldValue("project.key")).thenReturn("key"); | |||
when(notification.getFieldValue("project.branch")).thenReturn("branch"); | |||
when(notification.getFieldValue("task.uuid")).thenReturn("task_uuid"); | |||
when(notification.getFieldValue("task.createdAt")).thenReturn("1673449576159"); | |||
when(notification.getFieldValue("task.failedAt")).thenReturn("1673449576159"); | |||
when(notification.getFieldValue("error.message")).thenReturn("error"); | |||
when(settings.getServerBaseURL()).thenReturn("sonarsource.com"); | |||
var result = underTest.format(notification); | |||
assertThat(result.getSubject()).isEqualTo("name: Background task in failure"); | |||
assertThat(result.getMessage()) | |||
.contains(""" | |||
Project: name | |||
Background task: task_uuid""") | |||
.contains(""" | |||
Error message: error | |||
More details at: sonarsource.com/project/background_tasks?id=key"""); | |||
} | |||
} |
@@ -161,7 +161,7 @@ public class ReportAnalysisFailureNotificationHandlerTest { | |||
.map(login -> new EmailRecipient(login, emailOf(login))) | |||
.collect(toSet()); | |||
Set<EmailDeliveryRequest> expectedRequests = emailRecipients.stream() | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif))) | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))) | |||
.collect(toSet()); | |||
when(emailNotificationChannel.isActivated()).thenReturn(true); | |||
when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS)) | |||
@@ -202,9 +202,9 @@ public class ReportAnalysisFailureNotificationHandlerTest { | |||
.thenReturn(emailRecipients2); | |||
Set<EmailDeliveryRequest> expectedRequests = Stream.concat( | |||
emailRecipients1.stream() | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif))), | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))), | |||
emailRecipients2.stream() | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif)))) | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif)))) | |||
.collect(toSet()); | |||
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet())); |
@@ -37,8 +37,8 @@ class EvaluationResultAssert extends AbstractAssert<EvaluationResultAssert, Eval | |||
isNotNull(); | |||
// check condition | |||
if (actual.getLevel() != expected) { | |||
failWithMessage("Expected Level to be <%s> but was <%s>", expected, actual.getLevel()); | |||
if (actual.level() != expected) { | |||
failWithMessage("Expected Level to be <%s> but was <%s>", expected, actual.level()); | |||
} | |||
return this; | |||
@@ -47,8 +47,8 @@ class EvaluationResultAssert extends AbstractAssert<EvaluationResultAssert, Eval | |||
public EvaluationResultAssert hasValue(Comparable<?> expected) { | |||
isNotNull(); | |||
if (!Objects.equals(actual.getValue(), expected)) { | |||
failWithMessage("Expected Value to be <%s> but was <%s>", expected, actual.getValue()); | |||
if (!Objects.equals(actual.value(), expected)) { | |||
failWithMessage("Expected Value to be <%s> but was <%s>", expected, actual.value()); | |||
} | |||
return this; |
@@ -38,8 +38,8 @@ public class EvaluationResultTest { | |||
Measure.Level level = Measure.Level.OK; | |||
EvaluationResult evaluationResult = new EvaluationResult(level, value); | |||
assertThat(evaluationResult.getLevel()).isEqualTo(level); | |||
assertThat(evaluationResult.getValue()).isEqualTo(value); | |||
assertThat(evaluationResult.level()).isEqualTo(level); | |||
assertThat(evaluationResult.value()).isEqualTo(value); | |||
} | |||
@Test |
@@ -102,7 +102,7 @@ public class FileSourceDataComputerTest { | |||
ArgumentCaptor<LineReader.ReadError> readErrorCaptor = ArgumentCaptor.forClass(LineReader.ReadError.class); | |||
verify(fileSourceDataWarnings, times(lineCount)).addWarning(same(FILE), readErrorCaptor.capture()); | |||
assertThat(readErrorCaptor.getAllValues()) | |||
.extracting(LineReader.ReadError::getLine) | |||
.extracting(LineReader.ReadError::line) | |||
.containsExactly(IntStream.range(randomStartPoint, randomStartPoint + lineCount).boxed().toArray(Integer[]::new)); | |||
} | |||
@@ -266,15 +266,15 @@ public class NewCoverageMeasuresStepTest { | |||
private void verify_aggregates_variations(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { | |||
treeRootHolder.setRoot(MULTIPLE_FILES_TREE); | |||
measureRepository | |||
.addRawMeasure(FILE_1_REF, metricKeys.getLines(), createMeasure(3000)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getConditions(), createMeasure(300)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getUncoveredLines(), createMeasure(30)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getUncoveredConditions(), createMeasure(9)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getLines(), createMeasure(2000)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getConditions(), createMeasure(400)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getUncoveredLines(), createMeasure(200)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getUncoveredConditions(), createMeasure(16)); | |||
.addRawMeasure(FILE_1_REF, metricKeys.lines(), createMeasure(3000)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.conditions(), createMeasure(300)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.uncoveredLines(), createMeasure(30)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.uncoveredConditions(), createMeasure(9)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.lines(), createMeasure(2000)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.conditions(), createMeasure(400)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.uncoveredLines(), createMeasure(200)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.uncoveredConditions(), createMeasure(16)); | |||
underTest.execute(new TestComputationStepContext()); | |||
@@ -108,7 +108,7 @@ public class QualityGateMeasuresStepTest { | |||
public String answer(InvocationOnMock invocation) { | |||
Condition condition = (Condition) invocation.getArguments()[0]; | |||
EvaluationResult evaluationResult = (EvaluationResult) invocation.getArguments()[1]; | |||
return dumbResultTextAnswer(condition, evaluationResult.getLevel(), evaluationResult.getValue()); | |||
return dumbResultTextAnswer(condition, evaluationResult.level(), evaluationResult.value()); | |||
} | |||
}); | |||
} |
@@ -136,15 +136,15 @@ public class ReportCoverageMeasuresStepTest { | |||
private void verify_coverage_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { | |||
measureRepository | |||
.addRawMeasure(FILE_1_REF, metricKeys.getLines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getConditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getLines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getConditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(16)); | |||
.addRawMeasure(FILE_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(FILE_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(FILE_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)); | |||
underTest.execute(new TestComputationStepContext()); | |||
@@ -145,8 +145,8 @@ public class SmallChangesetQualityGateSpecialCaseTest { | |||
QualityGateMeasuresStep.MetricEvaluationResult modified = underTest.apply(original); | |||
assertThat(modified.evaluationResult.getLevel()).isSameAs(OK); | |||
assertThat(modified.evaluationResult.getValue()).isSameAs(value); | |||
assertThat(modified.evaluationResult.level()).isSameAs(OK); | |||
assertThat(modified.evaluationResult.value()).isSameAs(value); | |||
assertThat(modified.condition).isSameAs(condition); | |||
} | |||
@@ -91,37 +91,37 @@ public class ViewsCoverageMeasuresStepTest { | |||
private void verify_lines_and_conditions_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys) { | |||
measureRepository | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getLines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getConditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getLines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getConditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(16)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getLines(), newMeasureBuilder().create(1000)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getConditions(), newMeasureBuilder().create(500)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(19)); | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.lines(), newMeasureBuilder().create(1000)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.conditions(), newMeasureBuilder().create(500)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(19)); | |||
underTest.execute(new TestComputationStepContext()); | |||
MeasureRepoEntry[] subViewRepoEntries = { | |||
entryOf(metricKeys.getLines(), newMeasureBuilder().create(5000)), | |||
entryOf(metricKeys.getConditions(), newMeasureBuilder().create(700)), | |||
entryOf(metricKeys.getUncoveredLines(), newMeasureBuilder().create(230)), | |||
entryOf(metricKeys.getUncoveredConditions(), newMeasureBuilder().create(25)) | |||
entryOf(metricKeys.lines(), newMeasureBuilder().create(5000)), | |||
entryOf(metricKeys.conditions(), newMeasureBuilder().create(700)), | |||
entryOf(metricKeys.uncoveredLines(), newMeasureBuilder().create(230)), | |||
entryOf(metricKeys.uncoveredConditions(), newMeasureBuilder().create(25)) | |||
}; | |||
assertThat(toEntries(measureRepository.getAddedRawMeasures(SUB_SUBVIEW_REF))).contains(subViewRepoEntries); | |||
assertThat(toEntries(measureRepository.getAddedRawMeasures(SUBVIEW_REF))).contains(subViewRepoEntries); | |||
assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains( | |||
entryOf(metricKeys.getLines(), newMeasureBuilder().create(6000)), | |||
entryOf(metricKeys.getConditions(), newMeasureBuilder().create(1200)), | |||
entryOf(metricKeys.getUncoveredLines(), newMeasureBuilder().create(530)), | |||
entryOf(metricKeys.getUncoveredConditions(), newMeasureBuilder().create(44))); | |||
entryOf(metricKeys.lines(), newMeasureBuilder().create(6000)), | |||
entryOf(metricKeys.conditions(), newMeasureBuilder().create(1200)), | |||
entryOf(metricKeys.uncoveredLines(), newMeasureBuilder().create(530)), | |||
entryOf(metricKeys.uncoveredConditions(), newMeasureBuilder().create(44))); | |||
} | |||
@Test | |||
@@ -138,20 +138,20 @@ public class ViewsCoverageMeasuresStepTest { | |||
private void verify_coverage_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { | |||
measureRepository | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getLines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getConditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getLines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getConditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(16)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getLines(), newMeasureBuilder().create(1000)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getConditions(), newMeasureBuilder().create(500)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getUncoveredLines(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.getUncoveredConditions(), newMeasureBuilder().create(19)); | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) | |||
.addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) | |||
.addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.lines(), newMeasureBuilder().create(1000)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.conditions(), newMeasureBuilder().create(500)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(300)) | |||
.addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(19)); | |||
underTest.execute(new TestComputationStepContext()); | |||
@@ -292,7 +292,7 @@ public class ExportIssuesStepTest { | |||
ProjectDump.Issue issue = getWrittenIssue(); | |||
assertThat(issue.getRuleRef()) | |||
.isEqualTo(ruleRepository.register(issueDto.getRuleUuid(), readyRuleDto.getKey()).getRef()); | |||
.isEqualTo(ruleRepository.register(issueDto.getRuleUuid(), readyRuleDto.getKey()).ref()); | |||
} | |||
@Test |
@@ -51,9 +51,9 @@ public class RuleRepositoryImplTest { | |||
underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); | |||
for (int i = 0; i < someRandomInt(); i++) { | |||
Rule otherRule = underTest.register(Integer.toString(i), RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); | |||
assertThat(otherRule.getRef()).isEqualTo(Integer.toString(i)); | |||
assertThat(otherRule.getRepository()).isEqualTo(SOME_REPOSITORY); | |||
assertThat(otherRule.getKey()).isEqualTo(SOME_RULE_KEY); | |||
assertThat(otherRule.ref()).isEqualTo(Integer.toString(i)); | |||
assertThat(otherRule.repository()).isEqualTo(SOME_REPOSITORY); | |||
assertThat(otherRule.key()).isEqualTo(SOME_RULE_KEY); | |||
} | |||
} | |||
@@ -79,7 +79,7 @@ public class RuleRepositoryImplTest { | |||
public void register_returns_the_same_object_for_every_call_with_equals_RuleKey_objects() { | |||
Rule rule = underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); | |||
for (int i = 0; i < someRandomInt(); i++) { | |||
assertThat(underTest.register(Uuids.createFast(), RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)).getRef()).isNotEqualTo(rule.getRef()); | |||
assertThat(underTest.register(Uuids.createFast(), RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)).ref()).isNotEqualTo(rule.ref()); | |||
} | |||
} | |||
@@ -89,9 +89,9 @@ public class RuleRepositoryImplTest { | |||
String repository = SOME_REPOSITORY + i; | |||
String ruleKey = String.valueOf(i); | |||
Rule rule = underTest.register(Integer.toString(i), RuleKey.of(repository, ruleKey)); | |||
assertThat(rule.getRef()).isEqualTo(Integer.toString(i)); | |||
assertThat(rule.getRepository()).isEqualTo(repository); | |||
assertThat(rule.getKey()).isEqualTo(ruleKey); | |||
assertThat(rule.ref()).isEqualTo(Integer.toString(i)); | |||
assertThat(rule.repository()).isEqualTo(repository); | |||
assertThat(rule.key()).isEqualTo(ruleKey); | |||
} | |||
} | |||
@@ -119,8 +119,8 @@ public class RuleRepositoryImplTest { | |||
Collection<Rule> all = underTest.getAll(); | |||
assertThat(all).extracting(Rule::getRepository).containsOnly(repositories); | |||
assertThat(all).extracting(Rule::getKey).containsOnly(keys); | |||
assertThat(all).extracting(Rule::repository).containsOnly(repositories); | |||
assertThat(all).extracting(Rule::key).containsOnly(keys); | |||
assertThatThrownBy(() -> all.add(SOME_RULE)) | |||
.isInstanceOf(UnsupportedOperationException.class); |
@@ -59,25 +59,12 @@ public class CeTask { | |||
} | |||
} | |||
@Immutable | |||
public static final class User { | |||
private final String uuid; | |||
private final String login; | |||
public record User(String uuid, String login) { | |||
public User(String uuid, @Nullable String login) { | |||
this.uuid = requireNonNull(uuid); | |||
this.login = emptyToNull(login); | |||
} | |||
public String getUuid() { | |||
return uuid; | |||
} | |||
@CheckForNull | |||
public String getLogin() { | |||
return login; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { |
@@ -110,7 +110,7 @@ public class CeTaskTest { | |||
.setSubmitter(new CeTask.User("USER_ID", "")) | |||
.build(); | |||
assertThat(ceTask.getSubmitter().getLogin()).isNull(); | |||
assertThat(ceTask.getSubmitter().login()).isNull(); | |||
} | |||
@Test | |||
@@ -140,8 +140,8 @@ public class CeTaskTest { | |||
public void verify_submitter_getters() { | |||
CeTask.User user = new CeTask.User("UUID", "LOGIN"); | |||
assertThat(user.getUuid()).isEqualTo("UUID"); | |||
assertThat(user.getLogin()).isEqualTo("LOGIN"); | |||
assertThat(user.uuid()).isEqualTo("UUID"); | |||
assertThat(user.login()).isEqualTo("LOGIN"); | |||
} | |||
@Test |
@@ -287,11 +287,11 @@ public class CeWorkerImpl implements CeWorker { | |||
if (submitter == null) { | |||
return null; | |||
} | |||
String submitterLogin = submitter.getLogin(); | |||
String submitterLogin = submitter.login(); | |||
if (submitterLogin != null) { | |||
return submitterLogin; | |||
} else { | |||
return submitter.getUuid(); | |||
return submitter.uuid(); | |||
} | |||
} | |||
@@ -221,15 +221,15 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { | |||
ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); | |||
ReportAnalysisFailureNotificationBuilder.Project notificationProject = reportAnalysisFailureNotificationBuilder.getProject(); | |||
assertThat(notificationProject.getName()).isEqualTo(project.name()); | |||
assertThat(notificationProject.getKey()).isEqualTo(project.getKey()); | |||
assertThat(notificationProject.getUuid()).isEqualTo(project.uuid()); | |||
assertThat(notificationProject.getBranchName()).isNull(); | |||
ReportAnalysisFailureNotificationBuilder.Task notificationTask = reportAnalysisFailureNotificationBuilder.getTask(); | |||
assertThat(notificationTask.getUuid()).isEqualTo(taskUuid); | |||
assertThat(notificationTask.getCreatedAt()).isEqualTo(createdAt); | |||
assertThat(notificationTask.getFailedAt()).isEqualTo(executedAt); | |||
ReportAnalysisFailureNotificationBuilder.Project notificationProject = reportAnalysisFailureNotificationBuilder.project(); | |||
assertThat(notificationProject.name()).isEqualTo(project.name()); | |||
assertThat(notificationProject.key()).isEqualTo(project.getKey()); | |||
assertThat(notificationProject.uuid()).isEqualTo(project.uuid()); | |||
assertThat(notificationProject.branchName()).isNull(); | |||
ReportAnalysisFailureNotificationBuilder.Task notificationTask = reportAnalysisFailureNotificationBuilder.task(); | |||
assertThat(notificationTask.uuid()).isEqualTo(taskUuid); | |||
assertThat(notificationTask.createdAt()).isEqualTo(createdAt); | |||
assertThat(notificationTask.failedAt()).isEqualTo(executedAt); | |||
} | |||
@Test | |||
@@ -243,7 +243,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { | |||
ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); | |||
ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); | |||
assertThat(reportAnalysisFailureNotificationBuilder.getErrorMessage()).isEqualTo(message); | |||
assertThat(reportAnalysisFailureNotificationBuilder.errorMessage()).isEqualTo(message); | |||
} | |||
@Test | |||
@@ -258,7 +258,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { | |||
ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); | |||
ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); | |||
assertThat(reportAnalysisFailureNotificationBuilder.getErrorMessage()).isNull(); | |||
assertThat(reportAnalysisFailureNotificationBuilder.errorMessage()).isNull(); | |||
} | |||
@Test | |||
@@ -296,7 +296,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { | |||
verify(notificationService).deliver(same(notificationMock)); | |||
ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); | |||
assertThat(notificationCaptor.getValue().getTask().getFailedAt()).isEqualTo(now); | |||
assertThat(notificationCaptor.getValue().task().failedAt()).isEqualTo(now); | |||
} | |||
private ReportAnalysisFailureNotification mockSerializer() { |
@@ -656,11 +656,11 @@ public class InternalCeQueueImplTest { | |||
} | |||
if (taskSubmit.getSubmitterUuid() != null) { | |||
if (userDto == null) { | |||
assertThat(task.getSubmitter().getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().getLogin()).isNull(); | |||
assertThat(task.getSubmitter().uuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().login()).isNull(); | |||
} else { | |||
assertThat(task.getSubmitter().getUuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().getUuid()).isEqualTo(userDto.getLogin()); | |||
assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); | |||
assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getLogin()); | |||
} | |||
} | |||
} |
@@ -367,8 +367,8 @@ public class CeWorkerImplTest { | |||
verifyWorkerUuid(); | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=SUCCESS | time=", submitter.getLogin())); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=SUCCESS | time=", submitter.login())); | |||
assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); | |||
assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty(); | |||
} | |||
@@ -387,8 +387,8 @@ public class CeWorkerImplTest { | |||
verifyWorkerUuid(); | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.getLogin())); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); | |||
logs = logTester.logs(LoggerLevel.ERROR); | |||
assertThat(logs).hasSize(1); | |||
assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid()); | |||
@@ -464,8 +464,8 @@ public class CeWorkerImplTest { | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.getLogin())); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); | |||
logs = logTester.logs(LoggerLevel.ERROR); | |||
assertThat(logs).hasSize(1); | |||
assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid()); | |||
@@ -482,8 +482,8 @@ public class CeWorkerImplTest { | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(1)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.getLogin())); | |||
assertThat(logs.get(1)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); | |||
assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty(); | |||
} | |||
@@ -512,8 +512,8 @@ public class CeWorkerImplTest { | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.getLogin())); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); | |||
List<LogAndArguments> logAndArguments = logTester.getLogs(LoggerLevel.ERROR); | |||
assertThat(logAndArguments).hasSize(2); | |||
@@ -541,8 +541,8 @@ public class CeWorkerImplTest { | |||
List<String> logs = logTester.logs(LoggerLevel.INFO); | |||
assertThat(logs).hasSize(2); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.getLogin()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.getLogin())); | |||
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); | |||
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); | |||
List<LogAndArguments> logAndArguments = logTester.getLogs(LoggerLevel.ERROR); | |||
assertThat(logAndArguments).hasSize(1); | |||
assertThat(logAndArguments.get(0).getFormattedMsg()).isEqualTo("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db"); |
@@ -21,20 +21,9 @@ package org.sonar.db.event; | |||
import static java.util.Objects.requireNonNull; | |||
public final class EventPurgeData { | |||
private final String componentUuid; | |||
private final String analysisUuid; | |||
public record EventPurgeData(String componentUuid, String analysisUuid) { | |||
public EventPurgeData(String componentUuid, String analysisUuid) { | |||
this.componentUuid = requireNonNull(componentUuid); | |||
this.analysisUuid = requireNonNull(analysisUuid); | |||
} | |||
public String getComponentUuid() { | |||
return componentUuid; | |||
} | |||
public String getAnalysisUuid() { | |||
return analysisUuid; | |||
} | |||
} |
@@ -276,7 +276,7 @@ public class EventComponentChangeDaoTest { | |||
Arrays.stream(event1Dtos).forEach(dto -> underTest.insert(dbSession, dto, doesNotMatter)); | |||
Arrays.stream(event2Dtos).forEach(dto -> underTest.insert(dbSession, dto, doesNotMatter)); | |||
assertThat(underTest.selectByAnalysisUuids(dbSession, singletonList(doesNotMatter.getAnalysisUuid()))) | |||
assertThat(underTest.selectByAnalysisUuids(dbSession, singletonList(doesNotMatter.analysisUuid()))) | |||
.extracting( | |||
EventComponentChangeDto::getUuid, | |||
EventComponentChangeDto::getEventUuid, |
@@ -203,22 +203,7 @@ public class PopulateInitialSchema extends DataChange { | |||
return uuid; | |||
} | |||
private static final class Groups { | |||
private final String adminGroupUuid; | |||
private final String userGroupUuid; | |||
private Groups(String adminGroupUuid, String userGroupUuid) { | |||
this.adminGroupUuid = adminGroupUuid; | |||
this.userGroupUuid = userGroupUuid; | |||
} | |||
public String getAdminGroupUuid() { | |||
return adminGroupUuid; | |||
} | |||
public String getUserGroupUuid() { | |||
return userGroupUuid; | |||
} | |||
private record Groups(String adminGroupUuid, String userGroupUuid) { | |||
} | |||
private void insertGroupRoles(Context context, Groups groups) throws SQLException { | |||
@@ -228,14 +213,14 @@ public class PopulateInitialSchema extends DataChange { | |||
for (String adminRole : ADMIN_ROLES) { | |||
upsert | |||
.setString(1, uuidFactory.create()) | |||
.setString(2, groups.getAdminGroupUuid()) | |||
.setString(2, groups.adminGroupUuid()) | |||
.setString(3, adminRole) | |||
.addBatch(); | |||
} | |||
for (String anyoneRole : Arrays.asList("scan", "provisioning")) { | |||
upsert | |||
.setString(1, uuidFactory.create()) | |||
.setString(2, groups.getUserGroupUuid()) | |||
.setString(2, groups.userGroupUuid()) | |||
.setString(3, anyoneRole) | |||
.addBatch(); | |||
} | |||
@@ -250,11 +235,11 @@ public class PopulateInitialSchema extends DataChange { | |||
Upsert upsert = context.prepareUpsert(createInsertStatement("groups_users", "user_uuid", "group_uuid")); | |||
upsert | |||
.setString(1, adminUserUuid) | |||
.setString(2, groups.getUserGroupUuid()) | |||
.setString(2, groups.userGroupUuid()) | |||
.addBatch(); | |||
upsert | |||
.setString(1, adminUserUuid) | |||
.setString(2, groups.getAdminGroupUuid()) | |||
.setString(2, groups.adminGroupUuid()) | |||
.addBatch(); | |||
upsert | |||
.execute() |
@@ -92,14 +92,14 @@ public class JvmOptions<T extends JvmOptions> { | |||
private void checkMandatoryOptionOverwrite(String propertyName, List<String> jvmOptionsFromProperty) { | |||
List<Match> matches = jvmOptionsFromProperty.stream() | |||
.map(jvmOption -> new Match(jvmOption, mandatoryOptionFor(jvmOption))) | |||
.filter(match -> match.getMandatoryOption() != null) | |||
.filter(match -> match.mandatoryOption() != null) | |||
.toList(); | |||
if (!matches.isEmpty()) { | |||
throw new MessageException(format( | |||
"a JVM option can't overwrite mandatory JVM options. The following JVM options defined by property '%s' are invalid: %s", | |||
propertyName, | |||
matches.stream() | |||
.map(m -> m.getOption() + " overwrites " + m.mandatoryOption.getKey() + m.mandatoryOption.getValue()) | |||
.map(m -> m.option() + " overwrites " + m.mandatoryOption.getKey() + m.mandatoryOption.getValue()) | |||
.collect(joining(", ")))); | |||
} | |||
} | |||
@@ -158,24 +158,11 @@ public class JvmOptions<T extends JvmOptions> { | |||
return options.toString(); | |||
} | |||
private static final class Match { | |||
private final String option; | |||
private final Map.Entry<String, String> mandatoryOption; | |||
private record Match(String option, Map.Entry<String, String> mandatoryOption) { | |||
private Match(String option, @Nullable Map.Entry<String, String> mandatoryOption) { | |||
this.option = option; | |||
this.mandatoryOption = mandatoryOption; | |||
} | |||
String getOption() { | |||
return option; | |||
} | |||
@CheckForNull | |||
Map.Entry<String, String> getMandatoryOption() { | |||
return mandatoryOption; | |||
} | |||
} | |||
} |
@@ -108,7 +108,7 @@ public class ChangesOnMyIssueNotificationHandler extends EmailNotificationHandle | |||
return subscribedAssignees.stream() | |||
.flatMap(recipient -> notificationsWithPeerChangedIssues.stream() | |||
// do not notify users of the changes they made themselves | |||
.filter(notification -> !notification.getChange().isAuthorLogin(recipient.getLogin())) | |||
.filter(notification -> !notification.getChange().isAuthorLogin(recipient.login())) | |||
.map(notification -> toEmailDeliveryRequest(notification, recipient, projectKeys))) | |||
.filter(Objects::nonNull) | |||
.collect(toSet(notificationsWithPeerChangedIssues.size())); | |||
@@ -140,7 +140,7 @@ public class ChangesOnMyIssueNotificationHandler extends EmailNotificationHandle | |||
Set<String> subscribedProjectKeys = (Set<String>) entry.getValue(); | |||
return notificationsWithPeerChangedIssues.stream() | |||
// do not notify users of the changes they made themselves | |||
.filter(notification -> !notification.getChange().isAuthorLogin(recipient.getLogin())) | |||
.filter(notification -> !notification.getChange().isAuthorLogin(recipient.login())) | |||
.map(notification -> toEmailDeliveryRequest(notification, recipient, subscribedProjectKeys)) | |||
.filter(Objects::nonNull); | |||
}) | |||
@@ -156,14 +156,14 @@ public class ChangesOnMyIssueNotificationHandler extends EmailNotificationHandle | |||
@CheckForNull | |||
private static EmailDeliveryRequest toEmailDeliveryRequest(NotificationWithProjectKeys notification, EmailRecipient recipient, Set<String> subscribedProjectKeys) { | |||
Set<ChangedIssue> recipientIssuesByProject = notification.getIssues().stream() | |||
.filter(issue -> issue.getAssignee().filter(assignee -> recipient.getLogin().equals(assignee.getLogin())).isPresent()) | |||
.filter(issue -> issue.getAssignee().filter(assignee -> recipient.login().equals(assignee.getLogin())).isPresent()) | |||
.filter(issue -> subscribedProjectKeys.contains(issue.getProject().getKey())) | |||
.collect(toSet(notification.getIssues().size())); | |||
if (recipientIssuesByProject.isEmpty()) { | |||
return null; | |||
} | |||
return new EmailDeliveryRequest( | |||
recipient.getEmail(), | |||
recipient.email(), | |||
new ChangesOnMyIssuesNotification(notification.getChange(), recipientIssuesByProject)); | |||
} | |||
@@ -136,7 +136,7 @@ public class FPOrWontFixNotificationHandler extends EmailNotificationHandler<Iss | |||
private static Stream<EmailDeliveryRequest> toRequests(NotificationWithProjectKeys notification, Set<String> projectKeys, Collection<EmailRecipient> recipients) { | |||
return recipients.stream() | |||
// do not notify author of the change | |||
.filter(recipient -> !notification.getChange().isAuthorLogin(recipient.getLogin())) | |||
.filter(recipient -> !notification.getChange().isAuthorLogin(recipient.login())) | |||
.flatMap(recipient -> { | |||
SetMultimap<String, ChangedIssue> issuesByNewResolution = notification.getIssues().stream() | |||
// ignore issues not changed to a FP or Won't Fix resolution | |||
@@ -155,7 +155,7 @@ public class FPOrWontFixNotificationHandler extends EmailNotificationHandler<Iss | |||
.map(wontFixIssues -> new FPOrWontFixNotification(notification.getChange(), wontFixIssues, WONT_FIX)) | |||
.orElse(null)) | |||
.filter(Objects::nonNull) | |||
.map(fpOrWontFixNotification -> new EmailDeliveryRequest(recipient.getEmail(), fpOrWontFixNotification)); | |||
.map(fpOrWontFixNotification -> new EmailDeliveryRequest(recipient.email(), fpOrWontFixNotification)); | |||
}); | |||
} | |||
@@ -91,7 +91,7 @@ public class MyNewIssuesNotificationHandler extends EmailNotificationHandler<MyN | |||
Map<String, NotificationManager.EmailRecipient> recipientsByLogin = notificationManager | |||
.findSubscribedEmailRecipients(KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER) | |||
.stream() | |||
.collect(MoreCollectors.uniqueIndex(NotificationManager.EmailRecipient::getLogin)); | |||
.collect(MoreCollectors.uniqueIndex(NotificationManager.EmailRecipient::login)); | |||
return notifications.stream() | |||
.map(notification -> toEmailDeliveryRequest(recipientsByLogin, notification)) | |||
.filter(Objects::nonNull); | |||
@@ -104,7 +104,7 @@ public class MyNewIssuesNotificationHandler extends EmailNotificationHandler<MyN | |||
NotificationManager.EmailRecipient emailRecipient = recipientsByLogin.get(assignee); | |||
if (emailRecipient != null) { | |||
return new EmailDeliveryRequest(emailRecipient.getEmail(), notification); | |||
return new EmailDeliveryRequest(emailRecipient.email(), notification); | |||
} | |||
return null; | |||
} |
@@ -29,7 +29,6 @@ import java.util.Optional; | |||
import java.util.function.ToIntFunction; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.api.notifications.Notification; | |||
import org.sonar.api.rule.RuleKey; | |||
import org.sonar.api.rules.RuleType; | |||
@@ -86,42 +85,12 @@ public class NewIssuesNotification extends Notification { | |||
Optional<String> getUserNameByUuid(String uuid); | |||
} | |||
@Immutable | |||
public static final class RuleDefinition { | |||
private final String name; | |||
private final String language; | |||
public record RuleDefinition(String name, String language) { | |||
public RuleDefinition(String name, @Nullable String language) { | |||
this.name = requireNonNull(name, "name can't be null"); | |||
this.language = language; | |||
} | |||
public String getName() { | |||
return name; | |||
} | |||
@CheckForNull | |||
public String getLanguage() { | |||
return language; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
RuleDefinition that = (RuleDefinition) o; | |||
return name.equals(that.name) && Objects.equals(language, that.language); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(name, language); | |||
} | |||
@Override | |||
public String toString() { | |||
return "RuleDefinition{" + name + " (" + language + ')' + '}'; | |||
@@ -177,7 +146,7 @@ public class NewIssuesNotification extends Notification { | |||
String ruleKey = ruleStats.getKey(); | |||
RuleDefinition rule = detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.parse(ruleKey)) | |||
.orElseThrow(() -> new IllegalStateException(String.format("Rule with key '%s' does not exist", ruleKey))); | |||
String name = rule.getName() + " (" + rule.getLanguage() + ")"; | |||
String name = rule.name() + " (" + rule.language() + ")"; | |||
setFieldValue(metric + DOT + i + LABEL, name); | |||
setFieldValue(metric + DOT + i + COUNT, String.valueOf(ruleStats.getValue().getOnCurrentAnalysis())); | |||
i++; |
@@ -82,7 +82,7 @@ public class NewIssuesNotificationHandler extends EmailNotificationHandler<NewIs | |||
return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, ALL_MUST_HAVE_ROLE_USER) | |||
.stream() | |||
.flatMap(emailRecipient -> notifications.stream() | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.getEmail(), notification))); | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification))); | |||
} | |||
} |
@@ -134,8 +134,8 @@ public class DefaultNotificationManager implements NotificationManager { | |||
try (DbSession dbSession = dbClient.openSession(false)) { | |||
Set<String> authorizedLogins = keepAuthorizedLogins(dbSession, projectKey, subscriberAndChannels, subscriberPermissionsOnProject); | |||
subscriberAndChannels.stream() | |||
.filter(subscriberAndChannel -> authorizedLogins.contains(subscriberAndChannel.getSubscriber().getLogin())) | |||
.forEach(subscriberAndChannel -> builder.put(subscriberAndChannel.getSubscriber().getLogin(), subscriberAndChannel.getChannel())); | |||
.filter(subscriberAndChannel -> authorizedLogins.contains(subscriberAndChannel.subscriber().getLogin())) | |||
.forEach(subscriberAndChannel -> builder.put(subscriberAndChannel.subscriber().getLogin(), subscriberAndChannel.channel())); | |||
} | |||
return builder.build(); | |||
} | |||
@@ -167,8 +167,8 @@ public class DefaultNotificationManager implements NotificationManager { | |||
private Set<String> keepAuthorizedLogins(DbSession dbSession, String projectKey, Set<SubscriberAndChannel> subscriberAndChannels, | |||
@Nullable Boolean global, String permission) { | |||
Set<String> logins = subscriberAndChannels.stream() | |||
.filter(s -> global == null || s.getSubscriber().isGlobal() == global) | |||
.map(s -> s.getSubscriber().getLogin()) | |||
.filter(s -> global == null || s.subscriber().isGlobal() == global) | |||
.map(s -> s.subscriber().getLogin()) | |||
.collect(Collectors.toSet()); | |||
if (logins.isEmpty()) { | |||
return Collections.emptySet(); | |||
@@ -244,22 +244,7 @@ public class DefaultNotificationManager implements NotificationManager { | |||
.filter(s -> authorizedLogins.contains(s.getLogin())); | |||
} | |||
private static final class SubscriberAndChannel { | |||
private final Subscriber subscriber; | |||
private final NotificationChannel channel; | |||
private SubscriberAndChannel(Subscriber subscriber, NotificationChannel channel) { | |||
this.subscriber = subscriber; | |||
this.channel = channel; | |||
} | |||
Subscriber getSubscriber() { | |||
return subscriber; | |||
} | |||
NotificationChannel getChannel() { | |||
return channel; | |||
} | |||
private record SubscriberAndChannel(Subscriber subscriber, NotificationChannel channel) { | |||
@Override | |||
public boolean equals(Object o) { | |||
@@ -274,10 +259,6 @@ public class DefaultNotificationManager implements NotificationManager { | |||
Objects.equals(channel, that.channel); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(subscriber, channel); | |||
} | |||
} | |||
@VisibleForTesting |
@@ -22,7 +22,6 @@ package org.sonar.server.notification; | |||
import com.google.common.collect.Multimap; | |||
import java.util.Objects; | |||
import java.util.Set; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.api.notifications.Notification; | |||
import org.sonar.api.notifications.NotificationChannel; | |||
import org.sonar.api.web.UserRole; | |||
@@ -57,29 +56,17 @@ public interface NotificationManager { | |||
* @param dispatcher the dispatcher for which this list of users is requested | |||
* @param projectKey key of the project | |||
* @param subscriberPermissionsOnProject the required permission for global and project subscribers | |||
* | |||
* @return the list of user login along with the subscribed channels | |||
*/ | |||
Multimap<String, NotificationChannel> findSubscribedRecipientsForDispatcher(NotificationDispatcher dispatcher, String projectKey, | |||
SubscriberPermissionsOnProject subscriberPermissionsOnProject); | |||
@Immutable | |||
final class EmailRecipient { | |||
private final String login; | |||
private final String email; | |||
record EmailRecipient(String login, String email) { | |||
public EmailRecipient(String login, String email) { | |||
this.login = requireNonNull(login, "login can't be null"); | |||
this.email = requireNonNull(email, "email can't be null"); | |||
} | |||
public String getLogin() { | |||
return login; | |||
} | |||
public String getEmail() { | |||
return email; | |||
} | |||
@Override | |||
public String toString() { | |||
return "EmailRecipient{" + "'" + login + '\'' + ":'" + email + '\'' + '}'; | |||
@@ -97,10 +84,6 @@ public interface NotificationManager { | |||
return login.equals(that.login) && email.equals(that.email); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(login, email); | |||
} | |||
} | |||
/** |
@@ -24,7 +24,6 @@ import java.net.URL; | |||
import java.util.Objects; | |||
import java.util.Set; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.apache.commons.lang.StringUtils; | |||
import org.apache.commons.mail.Email; | |||
import org.apache.commons.mail.EmailException; | |||
@@ -128,24 +127,12 @@ public class EmailNotificationChannel extends NotificationChannel { | |||
return false; | |||
} | |||
@Immutable | |||
public static final class EmailDeliveryRequest { | |||
private final String recipientEmail; | |||
private final Notification notification; | |||
public record EmailDeliveryRequest(String recipientEmail, Notification notification) { | |||
public EmailDeliveryRequest(String recipientEmail, Notification notification) { | |||
this.recipientEmail = requireNonNull(recipientEmail, "recipientEmail can't be null"); | |||
this.notification = requireNonNull(notification, "notification can't be null"); | |||
} | |||
public String getRecipientEmail() { | |||
return recipientEmail; | |||
} | |||
public Notification getNotification() { | |||
return notification; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
@@ -159,11 +146,6 @@ public class EmailNotificationChannel extends NotificationChannel { | |||
Objects.equals(notification, that.notification); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(recipientEmail, notification); | |||
} | |||
@Override | |||
public String toString() { | |||
return "EmailDeliveryRequest{" + "'" + recipientEmail + '\'' + " : " + notification + '}'; | |||
@@ -177,11 +159,11 @@ public class EmailNotificationChannel extends NotificationChannel { | |||
} | |||
return (int) deliveries.stream() | |||
.filter(t -> !t.getRecipientEmail().isBlank()) | |||
.filter(t -> !t.recipientEmail().isBlank()) | |||
.map(t -> { | |||
EmailMessage emailMessage = format(t.getNotification()); | |||
EmailMessage emailMessage = format(t.notification()); | |||
if (emailMessage != null) { | |||
emailMessage.setTo(t.getRecipientEmail()); | |||
emailMessage.setTo(t.recipientEmail()); | |||
return deliver(emailMessage); | |||
} | |||
return false; |
@@ -82,6 +82,6 @@ public class QGChangeNotificationHandler extends EmailNotificationHandler<QGChan | |||
return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, ALL_MUST_HAVE_ROLE_USER) | |||
.stream() | |||
.flatMap(emailRecipient -> notifications.stream() | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.getEmail(), notification))); | |||
.map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification))); | |||
} | |||
} |
@@ -25,7 +25,6 @@ import java.util.Map; | |||
import java.util.Objects; | |||
import java.util.Optional; | |||
import java.util.Set; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import org.sonar.core.platform.EditionProvider; | |||
import org.sonar.core.platform.EditionProvider.Edition; | |||
@@ -251,62 +250,13 @@ public class TelemetryData { | |||
} | |||
static class Database { | |||
private final String name; | |||
private final String version; | |||
Database(String name, String version) { | |||
this.name = name; | |||
this.version = version; | |||
} | |||
public String getName() { | |||
return name; | |||
} | |||
public String getVersion() { | |||
return version; | |||
} | |||
record Database(String name, String version) { | |||
} | |||
static class Project { | |||
private final String projectUuid; | |||
private final String language; | |||
private final Long loc; | |||
private final Long lastAnalysis; | |||
public Project(String projectUuid, Long lastAnalysis, String language, Long loc) { | |||
this.projectUuid = projectUuid; | |||
this.lastAnalysis = lastAnalysis; | |||
this.language = language; | |||
this.loc = loc; | |||
} | |||
public String getProjectUuid() { | |||
return projectUuid; | |||
} | |||
public String getLanguage() { | |||
return language; | |||
} | |||
public Long getLoc() { | |||
return loc; | |||
} | |||
public Long getLastAnalysis() { | |||
return lastAnalysis; | |||
} | |||
record Project(String projectUuid, Long lastAnalysis, String language, Long loc) { | |||
} | |||
static class ProjectStatistics { | |||
private final String projectUuid; | |||
private final Long branchCount; | |||
private final Long pullRequestCount; | |||
private final String scm; | |||
private final String ci; | |||
private final String devopsPlatform; | |||
record ProjectStatistics(String projectUuid, Long branchCount, Long pullRequestCount, String scm, String ci, String devopsPlatform) { | |||
ProjectStatistics(String projectUuid, Long branchCount, Long pullRequestCount, | |||
@Nullable String scm, @Nullable String ci, @Nullable String devopsPlatform) { | |||
this.projectUuid = projectUuid; | |||
@@ -316,33 +266,5 @@ public class TelemetryData { | |||
this.ci = ci; | |||
this.devopsPlatform = devopsPlatform; | |||
} | |||
public String getProjectUuid() { | |||
return projectUuid; | |||
} | |||
public Long getBranchCount() { | |||
return branchCount; | |||
} | |||
public Long getPullRequestCount() { | |||
return pullRequestCount; | |||
} | |||
@CheckForNull | |||
public String getScm() { | |||
return scm; | |||
} | |||
@CheckForNull | |||
public String getCi() { | |||
return ci; | |||
} | |||
@CheckForNull | |||
public String getDevopsPlatform() { | |||
return devopsPlatform; | |||
} | |||
} | |||
} |
@@ -57,8 +57,8 @@ public class TelemetryDataJsonWriter { | |||
statistics.getEdition().ifPresent(e -> json.prop("edition", e.name().toLowerCase(Locale.ENGLISH))); | |||
json.name("database"); | |||
json.beginObject(); | |||
json.prop("name", statistics.getDatabase().getName()); | |||
json.prop("version", statistics.getDatabase().getVersion()); | |||
json.prop("name", statistics.getDatabase().name()); | |||
json.prop("version", statistics.getDatabase().version()); | |||
json.endObject(); | |||
json.name("plugins"); | |||
json.beginArray(); | |||
@@ -128,12 +128,12 @@ public class TelemetryDataJsonWriter { | |||
json.beginArray(); | |||
statistics.getProjects().forEach(project -> { | |||
json.beginObject(); | |||
json.prop("projectUuid", project.getProjectUuid()); | |||
if (project.getLastAnalysis() != null) { | |||
json.prop("lastAnalysis", toUtc(project.getLastAnalysis())); | |||
json.prop("projectUuid", project.projectUuid()); | |||
if (project.lastAnalysis() != null) { | |||
json.prop("lastAnalysis", toUtc(project.lastAnalysis())); | |||
} | |||
json.prop(LANGUAGE_PROPERTY, project.getLanguage()); | |||
json.prop("loc", project.getLoc()); | |||
json.prop(LANGUAGE_PROPERTY, project.language()); | |||
json.prop("loc", project.loc()); | |||
json.endObject(); | |||
}); | |||
json.endArray(); | |||
@@ -146,12 +146,12 @@ public class TelemetryDataJsonWriter { | |||
json.beginArray(); | |||
statistics.getProjectStatistics().forEach(project -> { | |||
json.beginObject(); | |||
json.prop("projectUuid", project.getProjectUuid()); | |||
json.prop("branchCount", project.getBranchCount()); | |||
json.prop("pullRequestCount", project.getPullRequestCount()); | |||
json.prop("scm", project.getScm()); | |||
json.prop("ci", project.getCi()); | |||
json.prop("devopsPlatform", project.getDevopsPlatform()); | |||
json.prop("projectUuid", project.projectUuid()); | |||
json.prop("branchCount", project.branchCount()); | |||
json.prop("pullRequestCount", project.pullRequestCount()); | |||
json.prop("scm", project.scm()); | |||
json.prop("ci", project.ci()); | |||
json.prop("devopsPlatform", project.devopsPlatform()); | |||
json.endObject(); | |||
}); | |||
json.endArray(); |
@@ -19,48 +19,18 @@ | |||
*/ | |||
package org.sonar.server.webhook; | |||
import java.util.Objects; | |||
import static java.util.Objects.requireNonNull; | |||
public final class CeTask { | |||
private final String id; | |||
private final Status status; | |||
public record CeTask(String id, Status status) { | |||
public CeTask(String id, Status status) { | |||
this.id = requireNonNull(id, "id can't be null"); | |||
this.status = requireNonNull(status, "status can't be null"); | |||
} | |||
public String getId() { | |||
return id; | |||
} | |||
public Status getStatus() { | |||
return status; | |||
} | |||
public enum Status { | |||
SUCCESS, FAILED | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
CeTask task = (CeTask) o; | |||
return Objects.equals(id, task.id) && | |||
status == task.status; | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(id, status); | |||
} | |||
@Override | |||
public String toString() { |
@@ -19,9 +19,7 @@ | |||
*/ | |||
package org.sonar.server.webhook; | |||
import java.util.Objects; | |||
import java.util.function.Supplier; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.Nullable; | |||
import org.sonar.api.ce.posttask.PostProjectAnalysisTask; | |||
import org.sonar.api.config.Configuration; | |||
@@ -51,50 +49,13 @@ public interface WebHooks { | |||
*/ | |||
void sendProjectAnalysisUpdate(Analysis analysis, Supplier<WebhookPayload> payloadSupplier, PostProjectAnalysisTask.LogStatistics taskLogStatistics); | |||
final class Analysis { | |||
private final String projectUuid; | |||
private final String ceTaskUuid; | |||
private final String analysisUuid; | |||
record Analysis(String projectUuid, String analysisUuid, String ceTaskUuid) { | |||
public Analysis(String projectUuid, @Nullable String analysisUuid, @Nullable String ceTaskUuid) { | |||
this.projectUuid = requireNonNull(projectUuid, "projectUuid can't be null"); | |||
this.analysisUuid = analysisUuid; | |||
this.ceTaskUuid = ceTaskUuid; | |||
} | |||
public String getProjectUuid() { | |||
return projectUuid; | |||
} | |||
@CheckForNull | |||
public String getCeTaskUuid() { | |||
return ceTaskUuid; | |||
} | |||
@CheckForNull | |||
public String getAnalysisUuid() { | |||
return analysisUuid; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
Analysis analysis = (Analysis) o; | |||
return Objects.equals(projectUuid, analysis.projectUuid) && | |||
Objects.equals(ceTaskUuid, analysis.ceTaskUuid) && | |||
Objects.equals(analysisUuid, analysis.analysisUuid); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(projectUuid, ceTaskUuid, analysisUuid); | |||
} | |||
@Override | |||
public String toString() { | |||
return "Analysis{" + |
@@ -103,8 +103,8 @@ public class WebHooksImpl implements WebHooks { | |||
private void sendProjectAnalysisUpdateImpl(Analysis analysis, Supplier<WebhookPayload> payloadSupplier, | |||
@Nullable PostProjectAnalysisTask.LogStatistics taskLogStatistics) { | |||
List<Webhook> webhooks = readWebHooksFrom(analysis.getProjectUuid(), taskLogStatistics) | |||
.map(dto -> new Webhook(dto.getUuid(), analysis.getProjectUuid(), analysis.getCeTaskUuid(), analysis.getAnalysisUuid(), | |||
List<Webhook> webhooks = readWebHooksFrom(analysis.projectUuid(), taskLogStatistics) | |||
.map(dto -> new Webhook(dto.getUuid(), analysis.projectUuid(), analysis.ceTaskUuid(), analysis.analysisUuid(), | |||
dto.getName(), dto.getUrl(), dto.getSecret())) | |||
.collect(MoreCollectors.toList()); | |||
if (webhooks.isEmpty()) { | |||
@@ -117,7 +117,7 @@ public class WebHooksImpl implements WebHooks { | |||
log(delivery); | |||
deliveryStorage.persist(delivery); | |||
})); | |||
asyncExecution.addToQueue(() -> deliveryStorage.purge(analysis.getProjectUuid())); | |||
asyncExecution.addToQueue(() -> deliveryStorage.purge(analysis.projectUuid())); | |||
} | |||
private static void log(WebhookDelivery delivery) { |
@@ -103,8 +103,8 @@ public class WebhookPayloadFactoryImpl implements WebhookPayloadFactory { | |||
} | |||
private static void writeTask(JsonWriter writer, Optional<CeTask> ceTask) { | |||
ceTask.ifPresent(ceTask1 -> writer.prop("taskId", ceTask1.getId())); | |||
writer.prop(PROPERTY_STATUS, ceTask.map(CeTask::getStatus).orElse(CeTask.Status.SUCCESS).toString()); | |||
ceTask.ifPresent(ceTask1 -> writer.prop("taskId", ceTask1.id())); | |||
writer.prop(PROPERTY_STATUS, ceTask.map(CeTask::status).orElse(CeTask.Status.SUCCESS).toString()); | |||
} | |||
private void writeBranch(JsonWriter writer, Project project, Branch branch) { |
@@ -283,15 +283,15 @@ public class ChangesOnMyIssueNotificationHandlerTest { | |||
Set<EmailDeliveryRequest> emailDeliveryRequests = emailDeliveryRequestSetCaptor.getValue(); | |||
assertThat(emailDeliveryRequests).hasSize(4); | |||
ListMultimap<String, EmailDeliveryRequest> emailDeliveryRequestByEmail = emailDeliveryRequests.stream() | |||
.collect(index(EmailDeliveryRequest::getRecipientEmail)); | |||
.collect(index(EmailDeliveryRequest::recipientEmail)); | |||
List<EmailDeliveryRequest> assignee1Requests = emailDeliveryRequestByEmail.get(emailOf(assignee1.getLogin())); | |||
assertThat(assignee1Requests) | |||
.hasSize(2) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChange) | |||
.containsOnly(userOrAnalysisChange); | |||
assertThat(assignee1Requests) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChangedIssues) | |||
.containsOnly( | |||
assignee1Issues.stream().limit(5).collect(unorderedIndex(t -> project, t -> t)), | |||
@@ -300,11 +300,11 @@ public class ChangesOnMyIssueNotificationHandlerTest { | |||
List<EmailDeliveryRequest> assignee2Requests = emailDeliveryRequestByEmail.get(emailOf(assignee2.getLogin())); | |||
assertThat(assignee2Requests) | |||
.hasSize(2) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChange) | |||
.containsOnly(userOrAnalysisChange); | |||
assertThat(assignee2Requests) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChangedIssues) | |||
.containsOnly( | |||
assignee2Issues.stream().limit(6).collect(unorderedIndex(t -> project, t -> t)), | |||
@@ -376,15 +376,15 @@ public class ChangesOnMyIssueNotificationHandlerTest { | |||
Set<EmailDeliveryRequest> emailDeliveryRequests = emailDeliveryRequestSetCaptor.getValue(); | |||
assertThat(emailDeliveryRequests).hasSize(3); | |||
ListMultimap<String, EmailDeliveryRequest> emailDeliveryRequestByEmail = emailDeliveryRequests.stream() | |||
.collect(index(EmailDeliveryRequest::getRecipientEmail)); | |||
.collect(index(EmailDeliveryRequest::recipientEmail)); | |||
List<EmailDeliveryRequest> assignee1Requests = emailDeliveryRequestByEmail.get(emailOf(assignee1.getLogin())); | |||
assertThat(assignee1Requests) | |||
.hasSize(2) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChange) | |||
.containsOnly(userOrAnalysisChange, assignee2Change1); | |||
assertThat(assignee1Requests) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChangedIssues) | |||
.containsOnly( | |||
assignee1Issues.stream().skip(4).limit(2).collect(unorderedIndex(t -> project1, t -> t)), | |||
@@ -393,11 +393,11 @@ public class ChangesOnMyIssueNotificationHandlerTest { | |||
List<EmailDeliveryRequest> assignee2Requests = emailDeliveryRequestByEmail.get(emailOf(assignee2.getLogin())); | |||
assertThat(assignee2Requests) | |||
.hasSize(1) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChange) | |||
.containsOnly(userOrAnalysisChange); | |||
assertThat(assignee2Requests) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.getNotification()) | |||
.extracting(t -> (ChangesOnMyIssuesNotification) t.notification()) | |||
.extracting(ChangesOnMyIssuesNotification::getChangedIssues) | |||
.containsOnly(assignee2Issues.stream().skip(7).collect(unorderedIndex(t -> project2, t -> t))); | |||
} |
@@ -337,7 +337,7 @@ public class FPOrWontFixNotificationHandlerTest { | |||
verify(emailNotificationChannel).deliverAll(captor.capture()); | |||
verifyNoMoreInteractions(emailNotificationChannel); | |||
ListMultimap<String, EmailDeliveryRequest> requestsByRecipientEmail = captor.getValue().stream() | |||
.collect(index(EmailDeliveryRequest::getRecipientEmail)); | |||
.collect(index(EmailDeliveryRequest::recipientEmail)); | |||
assertThat(requestsByRecipientEmail.get(emailOf(subscriber1.getLogin()))) | |||
.containsOnly( | |||
Stream.of( | |||
@@ -418,7 +418,7 @@ public class FPOrWontFixNotificationHandlerTest { | |||
verify(emailNotificationChannel).deliverAll(captor.capture()); | |||
verifyNoMoreInteractions(emailNotificationChannel); | |||
ListMultimap<String, EmailDeliveryRequest> requestsByRecipientEmail = captor.getValue().stream() | |||
.collect(index(EmailDeliveryRequest::getRecipientEmail)); | |||
.collect(index(EmailDeliveryRequest::recipientEmail)); | |||
assertThat(requestsByRecipientEmail.get(emailOf(subscriber1.getLogin()))) | |||
.containsOnly( | |||
new EmailDeliveryRequest(emailOf(subscriber1.getLogin()), new FPOrWontFixNotification( |
@@ -159,7 +159,7 @@ public class NewIssuesNotificationHandlerTest { | |||
.map(login -> new EmailRecipient(login, emailOf(login))) | |||
.collect(toSet()); | |||
Set<EmailDeliveryRequest> expectedRequests = emailRecipients.stream() | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif))) | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))) | |||
.collect(toSet()); | |||
when(emailNotificationChannel.isActivated()).thenReturn(true); | |||
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER)) | |||
@@ -200,9 +200,9 @@ public class NewIssuesNotificationHandlerTest { | |||
.thenReturn(emailRecipients2); | |||
Set<EmailDeliveryRequest> expectedRequests = Stream.concat( | |||
emailRecipients1.stream() | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif))), | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))), | |||
emailRecipients2.stream() | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.getEmail(), notif)))) | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif)))) | |||
.collect(toSet()); | |||
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet())); |
@@ -157,7 +157,7 @@ public class QGChangeNotificationHandlerTest { | |||
.map(login -> new NotificationManager.EmailRecipient(login, emailOf(login))) | |||
.collect(toSet()); | |||
Set<EmailNotificationChannel.EmailDeliveryRequest> expectedRequests = emailRecipients.stream() | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.getEmail(), notif))) | |||
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif))) | |||
.collect(toSet()); | |||
when(emailNotificationChannel.isActivated()).thenReturn(true); | |||
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER)) | |||
@@ -198,9 +198,9 @@ public class QGChangeNotificationHandlerTest { | |||
.thenReturn(emailRecipients2); | |||
Set<EmailNotificationChannel.EmailDeliveryRequest> expectedRequests = Stream.concat( | |||
emailRecipients1.stream() | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.getEmail(), notif))), | |||
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif))), | |||
emailRecipients2.stream() | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.getEmail(), notif)))) | |||
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif)))) | |||
.collect(toSet()); | |||
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet())); |
@@ -44,7 +44,7 @@ public class CeTaskTest { | |||
@Test | |||
public void verify_getters() { | |||
assertThat(underTest.getId()).isEqualTo("A"); | |||
assertThat(underTest.getStatus()).isEqualTo(CeTask.Status.SUCCESS); | |||
assertThat(underTest.id()).isEqualTo("A"); | |||
assertThat(underTest.status()).isEqualTo(CeTask.Status.SUCCESS); | |||
} | |||
} |
@@ -19,45 +19,14 @@ | |||
*/ | |||
package org.sonar.server.project; | |||
import java.util.Objects; | |||
import static com.google.common.base.Preconditions.checkNotNull; | |||
public final class RekeyedProject { | |||
private final Project project; | |||
private final String previousKey; | |||
public record RekeyedProject(Project project, String previousKey) { | |||
public RekeyedProject(Project project, String previousKey) { | |||
this.project = checkNotNull(project, "project can't be null"); | |||
this.previousKey = checkNotNull(previousKey, "previousKey can't be null"); | |||
} | |||
public Project getProject() { | |||
return project; | |||
} | |||
public String getPreviousKey() { | |||
return previousKey; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
RekeyedProject that = (RekeyedProject) o; | |||
return Objects.equals(project, that.project) && | |||
Objects.equals(previousKey, that.previousKey); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(project, previousKey); | |||
} | |||
@Override | |||
public String toString() { | |||
return "RekeyedProject{" + |
@@ -49,8 +49,8 @@ public class RekeyedProjectTest { | |||
String previousKey = randomAlphanumeric(6); | |||
RekeyedProject underTest = new RekeyedProject(project, previousKey); | |||
assertThat(underTest.getProject()).isSameAs(project); | |||
assertThat(underTest.getPreviousKey()).isEqualTo(previousKey); | |||
assertThat(underTest.project()).isSameAs(project); | |||
assertThat(underTest.previousKey()).isEqualTo(previousKey); | |||
} | |||
@Test |
@@ -25,7 +25,6 @@ import java.util.List; | |||
import java.util.Objects; | |||
import java.util.Optional; | |||
import javax.annotation.CheckForNull; | |||
import javax.annotation.concurrent.Immutable; | |||
import org.sonar.db.component.ComponentDto; | |||
import org.sonar.db.permission.GlobalPermission; | |||
import org.sonar.db.project.ProjectDto; | |||
@@ -96,23 +95,12 @@ public interface UserSession { | |||
*/ | |||
Optional<IdentityProvider> getIdentityProvider(); | |||
@Immutable final class ExternalIdentity { | |||
private final String id; | |||
private final String login; | |||
record ExternalIdentity(String id, String login) { | |||
public ExternalIdentity(String id, String login) { | |||
this.id = requireNonNull(id, "id can't be null"); | |||
this.login = requireNonNull(login, "login can't be null"); | |||
} | |||
public String getId() { | |||
return id; | |||
} | |||
public String getLogin() { | |||
return login; | |||
} | |||
@Override | |||
public String toString() { | |||
return "ExternalIdentity{" + | |||
@@ -121,22 +109,6 @@ public interface UserSession { | |||
'}'; | |||
} | |||
@Override | |||
public boolean equals(Object o) { | |||
if (this == o) { | |||
return true; | |||
} | |||
if (o == null || getClass() != o.getClass()) { | |||
return false; | |||
} | |||
ExternalIdentity that = (ExternalIdentity) o; | |||
return Objects.equals(id, that.id) && Objects.equals(login, that.login); | |||
} | |||
@Override | |||
public int hashCode() { | |||
return Objects.hash(id, login); | |||
} | |||
} | |||
/** | |||
@@ -156,7 +128,6 @@ public interface UserSession { | |||
/** | |||
* Returns {@code true} if the permission is granted, otherwise {@code false}. | |||
* | |||
*/ | |||
boolean hasPermission(GlobalPermission permission); | |||
@@ -172,7 +143,7 @@ public interface UserSession { | |||
* | |||
* If the component does not exist, then returns {@code false}. | |||
* | |||
* @param component non-null component. | |||
* @param component non-null component. | |||
* @param permission project permission as defined by {@link org.sonar.server.permission.PermissionService} | |||
*/ | |||
boolean hasComponentPermission(String permission, ComponentDto component); |
@@ -169,7 +169,7 @@ public class TelemetryDataLoaderImplTest { | |||
tuple(activeUsers.get(2).getUuid(), lastConnectionDate, activeUsers.get(2).getLastSonarlintConnectionDate(), true), | |||
tuple(inactiveUser.getUuid(), null, inactiveUser.getLastSonarlintConnectionDate(), false)); | |||
assertThat(data.getProjects()) | |||
.extracting(TelemetryData.Project::getProjectUuid, TelemetryData.Project::getLanguage, TelemetryData.Project::getLoc, TelemetryData.Project::getLastAnalysis) | |||
.extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc, TelemetryData.Project::lastAnalysis) | |||
.containsExactlyInAnyOrder( | |||
tuple(project1.uuid(), "java", 70L, analysisDate), | |||
tuple(project1.uuid(), "js", 30L, analysisDate), | |||
@@ -177,8 +177,8 @@ public class TelemetryDataLoaderImplTest { | |||
tuple(project2.uuid(), "java", 180L, analysisDate), | |||
tuple(project2.uuid(), "js", 20L, analysisDate)); | |||
assertThat(data.getProjectStatistics()) | |||
.extracting(TelemetryData.ProjectStatistics::getBranchCount, TelemetryData.ProjectStatistics::getPullRequestCount, | |||
TelemetryData.ProjectStatistics::getScm, TelemetryData.ProjectStatistics::getCi, TelemetryData.ProjectStatistics::getDevopsPlatform) | |||
.extracting(TelemetryData.ProjectStatistics::branchCount, TelemetryData.ProjectStatistics::pullRequestCount, | |||
TelemetryData.ProjectStatistics::scm, TelemetryData.ProjectStatistics::ci, TelemetryData.ProjectStatistics::devopsPlatform) | |||
.containsExactlyInAnyOrder( | |||
tuple(1L, 0L, "scm-1", "ci-1", "azure_devops_cloud"), | |||
tuple(1L, 0L, "scm-2", "ci-2", "github_cloud")); | |||
@@ -198,8 +198,8 @@ public class TelemetryDataLoaderImplTest { | |||
private void assertDatabaseMetadata(TelemetryData.Database database) { | |||
try (DbSession dbSession = db.getDbClient().openSession(false)) { | |||
DatabaseMetaData metadata = dbSession.getConnection().getMetaData(); | |||
assertThat(database.getName()).isEqualTo("H2"); | |||
assertThat(database.getVersion()).isEqualTo(metadata.getDatabaseProductVersion()); | |||
assertThat(database.name()).isEqualTo("H2"); | |||
assertThat(database.version()).isEqualTo(metadata.getDatabaseProductVersion()); | |||
} catch (SQLException e) { | |||
throw new RuntimeException(e); | |||
} | |||
@@ -233,14 +233,14 @@ public class TelemetryDataLoaderImplTest { | |||
TelemetryData data = communityUnderTest.load(); | |||
assertThat(data.getProjects()).extracting(TelemetryData.Project::getProjectUuid, TelemetryData.Project::getLanguage, TelemetryData.Project::getLoc) | |||
assertThat(data.getProjects()).extracting(TelemetryData.Project::projectUuid, TelemetryData.Project::language, TelemetryData.Project::loc) | |||
.containsExactlyInAnyOrder( | |||
tuple(project.uuid(), "java", 100L), | |||
tuple(project.uuid(), "js", 50L), | |||
tuple(project.uuid(), "kotlin", 30L)); | |||
assertThat(data.getProjectStatistics()) | |||
.extracting(TelemetryData.ProjectStatistics::getBranchCount, TelemetryData.ProjectStatistics::getPullRequestCount, | |||
TelemetryData.ProjectStatistics::getScm, TelemetryData.ProjectStatistics::getCi) | |||
.extracting(TelemetryData.ProjectStatistics::branchCount, TelemetryData.ProjectStatistics::pullRequestCount, | |||
TelemetryData.ProjectStatistics::scm, TelemetryData.ProjectStatistics::ci) | |||
.containsExactlyInAnyOrder( | |||
tuple(2L, 0L, "undetected", "undetected")); | |||
} | |||
@@ -378,7 +378,7 @@ public class TelemetryDataLoaderImplTest { | |||
db.components().insertPublicProject(); | |||
TelemetryData data = communityUnderTest.load(); | |||
assertThat(data.getProjectStatistics()) | |||
.extracting(TelemetryData.ProjectStatistics::getDevopsPlatform, TelemetryData.ProjectStatistics::getScm, TelemetryData.ProjectStatistics::getCi) | |||
.extracting(TelemetryData.ProjectStatistics::devopsPlatform, TelemetryData.ProjectStatistics::scm, TelemetryData.ProjectStatistics::ci) | |||
.containsExactlyInAnyOrder(tuple("undetected", "undetected", "undetected")); | |||
} | |||
@@ -78,22 +78,7 @@ public class RecoveryIndexer implements Startable { | |||
this.loopLimit = getSetting(PROPERTY_LOOP_LIMIT, DEFAULT_LOOP_LIMIT); | |||
} | |||
private static final class Indexer { | |||
private final IndexType indexType; | |||
private final ResilientIndexer delegate; | |||
private Indexer(IndexType indexType, ResilientIndexer delegate) { | |||
this.indexType = indexType; | |||
this.delegate = delegate; | |||
} | |||
public IndexType getIndexType() { | |||
return indexType; | |||
} | |||
public ResilientIndexer getDelegate() { | |||
return delegate; | |||
} | |||
private record Indexer(IndexType indexType, ResilientIndexer delegate) { | |||
} | |||
@Override |
@@ -23,20 +23,9 @@ import org.sonar.db.qualityprofile.QProfileDto; | |||
import static java.util.Objects.requireNonNull; | |||
public final class QProfileRestoreSummary { | |||
private final QProfileDto profile; | |||
private final BulkChangeResult ruleChanges; | |||
public record QProfileRestoreSummary(QProfileDto profile, BulkChangeResult ruleChanges) { | |||
public QProfileRestoreSummary(QProfileDto profile, BulkChangeResult ruleChanges) { | |||
this.profile = requireNonNull(profile); | |||
this.ruleChanges = requireNonNull(ruleChanges); | |||
} | |||
public QProfileDto getProfile() { | |||
return profile; | |||
} | |||
public BulkChangeResult getRuleChanges() { | |||
return ruleChanges; | |||
} | |||
} |
@@ -29,27 +29,6 @@ public interface DescendantProfilesSupplier { | |||
Result get(Collection<QProfileDto> profiles, Collection<String> ruleUuids); | |||
final class Result { | |||
private final Collection<QProfileDto> profiles; | |||
private final Collection<ActiveRuleDto> activeRules; | |||
private final Collection<ActiveRuleParamDto> activeRuleParams; | |||
public Result(Collection<QProfileDto> profiles, Collection<ActiveRuleDto> activeRules, Collection<ActiveRuleParamDto> activeRuleParams) { | |||
this.profiles = profiles; | |||
this.activeRules = activeRules; | |||
this.activeRuleParams = activeRuleParams; | |||
} | |||
public Collection<QProfileDto> getProfiles() { | |||
return profiles; | |||
} | |||
public Collection<ActiveRuleDto> getActiveRules() { | |||
return activeRules; | |||
} | |||
public Collection<ActiveRuleParamDto> getActiveRuleParams() { | |||
return activeRuleParams; | |||
} | |||
record Result(Collection<QProfileDto> profiles, Collection<ActiveRuleDto> activeRules, Collection<ActiveRuleParamDto> activeRuleParams) { | |||
} | |||
} |
@@ -197,8 +197,8 @@ public class RuleActivationContext { | |||
.filter(p -> p.getRulesProfileUuid().equals(baseRulesProfile.getUuid())) | |||
.collect(toArrayList(profilesByUuid.size())); | |||
DescendantProfilesSupplier.Result result = descendantProfilesSupplier.get(baseProfiles, rulesByUuid.keySet()); | |||
register(result.getProfiles()); | |||
register(result.getActiveRules(), result.getActiveRuleParams()); | |||
register(result.profiles()); | |||
register(result.activeRules(), result.activeRuleParams()); | |||
descendantsLoaded = true; | |||
} | |||
@@ -92,7 +92,7 @@ public class RestoreAction implements QProfileWsAction { | |||
} | |||
private void writeResponse(JsonWriter json, QProfileRestoreSummary summary) { | |||
QProfileDto profile = summary.getProfile(); | |||
QProfileDto profile = summary.profile(); | |||
String languageKey = profile.getLanguage(); | |||
Language language = languages.get(languageKey); | |||
@@ -108,7 +108,7 @@ public class RestoreAction implements QProfileWsAction { | |||
} | |||
jsonProfile.endObject(); | |||
BulkChangeResult ruleChanges = summary.getRuleChanges(); | |||
BulkChangeResult ruleChanges = summary.ruleChanges(); | |||
json.prop("ruleSuccesses", ruleChanges.countSucceeded()); | |||
json.prop("ruleFailures", ruleChanges.countFailed()); | |||
json.endObject().close(); |
@@ -208,10 +208,10 @@ public class QProfileBackuperImplTest { | |||
QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, (String) null); | |||
assertThat(summary.getProfile().getName()).isEqualTo("foo"); | |||
assertThat(summary.getProfile().getLanguage()).isEqualTo("js"); | |||
assertThat(summary.profile().getName()).isEqualTo("foo"); | |||
assertThat(summary.profile().getLanguage()).isEqualTo("js"); | |||
assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee()); | |||
assertThat(reset.calledProfile.getKee()).isEqualTo(summary.profile().getKee()); | |||
assertThat(reset.calledActivations).isEmpty(); | |||
} | |||
@@ -287,10 +287,10 @@ public class QProfileBackuperImplTest { | |||
QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, "bar"); | |||
assertThat(summary.getProfile().getName()).isEqualTo("bar"); | |||
assertThat(summary.getProfile().getLanguage()).isEqualTo("js"); | |||
assertThat(summary.profile().getName()).isEqualTo("bar"); | |||
assertThat(summary.profile().getLanguage()).isEqualTo("js"); | |||
assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee()); | |||
assertThat(reset.calledProfile.getKee()).isEqualTo(summary.profile().getKee()); | |||
assertThat(reset.calledActivations).isEmpty(); | |||
} | |||
@@ -82,7 +82,7 @@ public class RestoreActionTest { | |||
TestResponse response = restore("<backup/>"); | |||
assertThat(backuper.restoredBackup).isEqualTo("<backup/>"); | |||
assertThat(backuper.restoredSummary.getProfile().getName()).isEqualTo("the-name-in-backup"); | |||
assertThat(backuper.restoredSummary.profile().getName()).isEqualTo("the-name-in-backup"); | |||
JsonAssert.assertJson(response.getInput()).isSimilarTo("{" + | |||
" \"profile\": {" + | |||
" \"name\": \"the-name-in-backup\"," + |