import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.server.rule.index.RuleIndexer;
*/
public RuleDto persistAndIndex(DbSession dbSession, NewAdHocRule adHoc) {
RuleDao dao = dbClient.ruleDao();
- Optional<RuleDto> existingRuleDtoOpt = dao.selectByKey(dbSession, adHoc.getKey());
RuleMetadataDto metadata;
long now = system2.now();
- if (!existingRuleDtoOpt.isPresent()) {
- RuleDefinitionDto dto = new RuleDefinitionDto()
- .setUuid(uuidFactory.create())
- .setRuleKey(adHoc.getKey())
- .setIsExternal(true)
- .setIsAdHoc(true)
- .setName(adHoc.getEngineId() + ":" + adHoc.getRuleId())
- .setScope(ALL)
- .setStatus(READY)
- .setCreatedAt(now)
- .setUpdatedAt(now);
- dao.insert(dbSession, dto);
- metadata = new RuleMetadataDto().setRuleUuid(dto.getUuid());
- } else {
- // No need to update the rule, only org specific metadata
- RuleDto ruleDto = existingRuleDtoOpt.get();
- Preconditions.checkState(ruleDto.isExternal() && ruleDto.isAdHoc());
- metadata = ruleDto.getMetadata();
- }
+ RuleDto ruleDtoToUpdate = findOrCreateRuleDto(dbSession, adHoc, dao, now);
+
+ metadata = ruleDtoToUpdate.getMetadata();
if (adHoc.hasDetails()) {
boolean changed = false;
if (!Objects.equals(metadata.getAdHocName(), adHoc.getName())) {
}
if (changed) {
metadata.setUpdatedAt(now);
- metadata.setCreatedAt(now);
- dao.insertOrUpdate(dbSession, metadata);
+ metadata.setCreatedAt(ruleDtoToUpdate.getCreatedAt());
+ dao.update(dbSession, ruleDtoToUpdate);
}
}
return ruleDto;
}
+ private RuleDto findOrCreateRuleDto(DbSession dbSession, NewAdHocRule adHoc, RuleDao dao, long now) {
+ Optional<RuleDto> existingRuleDtoOpt = dbClient.ruleDao().selectByKey(dbSession, adHoc.getKey());
+ if (existingRuleDtoOpt.isEmpty()) {
+ RuleDto ruleDto = new RuleDto()
+ .setUuid(uuidFactory.create())
+ .setRuleKey(adHoc.getKey())
+ .setIsExternal(true)
+ .setIsAdHoc(true)
+ .setName(adHoc.getEngineId() + ":" + adHoc.getRuleId())
+ .setScope(ALL)
+ .setStatus(READY)
+ .setCreatedAt(now)
+ .setUpdatedAt(now);
+ dao.insert(dbSession, ruleDto);
+ return ruleDto;
+ } else {
+ RuleDto ruleDto = existingRuleDtoOpt.get();
+ Preconditions.checkState(ruleDto.isExternal() && ruleDto.isAdHoc());
+ return ruleDto;
+ }
+ }
+
}
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.project.Project;
import static org.assertj.core.api.Assertions.assertThat;
fileWithNoIssuesOnBranch1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1, null));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
fileWithOneOpenIssueOnBranch1Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr1, null));
db.issues().insert(rule, branch1pr1, fileWithOneOpenIssueOnBranch1Pr1);
b -> b.setBranchType(BranchType.PULL_REQUEST),
b -> b.setMergeBranchUuid(project.uuid()));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto fileWithResolvedIssueOnPullrequest = db.components().insertComponent(ComponentTesting.newFileDto(pullRequest, null));
db.issues().insert(rule, pullRequest, fileWithResolvedIssueOnPullrequest, i -> i.setStatus("RESOLVED"));
b -> b.setBranchType(BranchType.BRANCH),
b -> b.setMergeBranchUuid(project.uuid()));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto fileWithResolvedIssueOnDerivedBranch = db.components().insertComponent(ComponentTesting.newFileDto(derivedBranch, null));
db.issues().insert(rule, derivedBranch, fileWithResolvedIssueOnDerivedBranch, i -> i.setStatus("RESOLVED"));
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.scanner.protocol.Constants;
assertThat(ruleUpdated.getMetadata().getAdHocDescription()).isEqualTo("A description updated");
assertThat(ruleUpdated.getMetadata().getAdHocSeverity()).isEqualTo(Severity.CRITICAL);
assertThat(ruleUpdated.getMetadata().getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
- assertThat(ruleUpdated.getDefinition().getCreatedAt()).isEqualTo(creationDate);
+ assertThat(ruleUpdated.getCreatedAt()).isEqualTo(creationDate);
assertThat(ruleUpdated.getMetadata().getCreatedAt()).isEqualTo(creationDate);
assertThat(ruleUpdated.getMetadata().getUpdatedAt()).isGreaterThan(creationDate);
}
@Test
public void does_not_update_rule_when_no_change() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setRepositoryKey("external_eslint").setIsExternal(true).setIsAdHoc(true));
+ RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_eslint").setIsExternal(true).setIsAdHoc(true));
RuleMetadataDto ruleMetadata = db.rules().insertOrUpdateMetadata(rule);
RuleDto ruleUpdated = underTest.persistAndIndex(dbSession, new NewAdHocRule(ScannerReport.AdHocRule.newBuilder()
assertThat(ruleUpdated.getRuleDescriptionSectionDtos()).usingRecursiveFieldByFieldElementComparator().isEqualTo(rule.getRuleDescriptionSectionDtos());
assertThat(ruleUpdated.getSeverity()).isEqualTo(rule.getSeverity());
assertThat(ruleUpdated.getType()).isEqualTo(rule.getType());
- assertThat(ruleUpdated.getDefinition().getCreatedAt()).isEqualTo(rule.getCreatedAt());
- assertThat(ruleUpdated.getDefinition().getUpdatedAt()).isEqualTo(rule.getUpdatedAt());
+ assertThat(ruleUpdated.getCreatedAt()).isEqualTo(rule.getCreatedAt());
+ assertThat(ruleUpdated.getUpdatedAt()).isEqualTo(ruleMetadata.getUpdatedAt());
assertThat(ruleUpdated.getMetadata().getAdHocName()).isEqualTo(ruleMetadata.getAdHocName());
assertThat(ruleUpdated.getMetadata().getAdHocDescription()).isEqualTo(ruleMetadata.getAdHocDescription());
assertThat(ruleUpdated.getMetadata().getAdHocSeverity()).isEqualTo(ruleMetadata.getAdHocSeverity());
assertThat(ruleUpdated.getMetadata().getAdHocType()).isEqualTo(ruleMetadata.getAdHocType());
assertThat(ruleUpdated.getMetadata().getCreatedAt()).isEqualTo(rule.getCreatedAt());
- assertThat(ruleUpdated.getMetadata().getUpdatedAt()).isEqualTo(rule.getUpdatedAt());
+ assertThat(ruleUpdated.getMetadata().getUpdatedAt()).isEqualTo(ruleMetadata.getUpdatedAt());
}
}
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
public void loadClosedIssues_returns_single_DefaultIssue_by_issue_based_on_first_row() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
+ RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
Date issueDate = addDays(NOW, -10);
IssueDto issue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL));
db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(issueDate, 10));
public void loadClosedIssues_returns_single_DefaultIssue_with_null_line_if_first_row_has_no_line_diff() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
+ RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
Date issueDate = addDays(NOW, -10);
IssueDto issue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL));
db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(issueDate, 10));
public void loadClosedIssues_returns_only_closed_issues_with_close_date() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
+ RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
Date issueDate = addDays(NOW, -10);
IssueDto closedIssue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL));
db.issues().insertFieldDiffs(closedIssue, newToClosedDiffsWithLine(issueDate, 10));
private void loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(ComponentIssuesLoader underTest) {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
+ RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL));
Date[] issueDates = new Date[] {
addDays(NOW, -10),
addDays(NOW, -31),
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.IssueFieldsSetter;
import static org.assertj.core.api.Assertions.assertThat;
private DbClient dbClient = dbTester.getDbClient();
private ProjectTrackerBaseLazyInput underTest;
- private RuleDefinitionDto rule;
+ private RuleDto rule;
private ComponentDto rootProjectDto;
private ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(),
System2.INSTANCE, mock(IssueChangesToDeleteRepository.class));
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
public DbTester db = DbTester.create();
private PullRequestSourceBranchMerger underTest;
- private RuleDefinitionDto rule;
+ private RuleDto rule;
private DefaultIssue rawIssue;
private Input<DefaultIssue> rawIssuesInput;
import org.sonar.db.DbTester;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.rule.index.RuleIndexer;
assertThat(underTest.getByKey(ruleKey).getType()).isNull();
RuleDao ruleDao = dbClient.ruleDao();
- Optional<RuleDefinitionDto> ruleDefinitionDto = ruleDao.selectDefinitionByKey(dbClient.openSession(false), ruleKey);
+ Optional<RuleDto> ruleDefinitionDto = ruleDao.selectByKey(dbClient.openSession(false), ruleKey);
assertThat(ruleDefinitionDto).isNotPresent();
}
underTest.saveOrUpdateAddHocRules(db.getSession());
db.commit();
- Optional<RuleDefinitionDto> ruleDefinitionDto = db.getDbClient().ruleDao().selectDefinitionByKey(db.getSession(), ruleKey);
+ Optional<RuleDto> ruleDefinitionDto = db.getDbClient().ruleDao().selectByKey(db.getSession(), ruleKey);
assertThat(ruleDefinitionDto).isPresent();
Rule rule = underTest.getByKey(ruleKey);
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.project.Project;
private ComponentDto branch1Dto;
private ComponentDto branch2Dto;
private ComponentDto branch3Dto;
- private RuleDefinitionDto rule;
+ private RuleDto rule;
@Before
public void setUp() {
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.es.EsTester;
import org.sonar.server.rule.index.RuleIndexDefinition;
underTest.execute(new TestComputationStepContext());
RuleDao ruleDao = dbClient.ruleDao();
- Optional<RuleDefinitionDto> ruleDefinitionDtoOptional = ruleDao.selectDefinitionByKey(dbClient.openSession(false), ruleKey);
+ Optional<RuleDto> ruleDefinitionDtoOptional = ruleDao.selectByKey(dbClient.openSession(false), ruleKey);
assertThat(ruleDefinitionDtoOptional).isPresent();
- RuleDefinitionDto reloaded = ruleDefinitionDtoOptional.get();
+ RuleDto reloaded = ruleDefinitionDtoOptional.get();
assertThat(reloaded.getRuleKey()).isEqualTo("no-cond-assign");
assertThat(reloaded.getRepositoryKey()).isEqualTo("external_eslint");
assertThat(reloaded.isExternal()).isTrue();
underTest.execute(new TestComputationStepContext());
RuleDao ruleDao = dbClient.ruleDao();
- assertThat(ruleDao.selectAllDefinitions(dbClient.openSession(false))).hasSize(1);
+ assertThat(ruleDao.selectAll(dbClient.openSession(false))).hasSize(1);
assertThat(es.countDocuments(RuleIndexDefinition.TYPE_RULE)).isZero();
}
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueMapper;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.issue.IssueStorage;
@Test
public void insert_copied_issue() {
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
public void insert_copied_issue_with_minimal_info() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
@Test
public void insert_merged_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
@Test
public void update_conflicting_issue() {
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
@Test
public void insert_new_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
public void close_issue() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
@Test
public void handle_no_longer_new_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
@Test
public void handle_existing_new_code_issue_migration() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
@Test
public void handle_existing_without_need_for_new_code_issue_migration() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
public void add_comment() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
public void add_change() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.DistributedMetricStatsInt;
import org.sonar.server.issue.notification.IssuesChangesNotification;
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto().setDbKey(PROJECT.getDbKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getDbKey()).setLongName(FILE.getName());
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
prepareIssue(ANALYSE_DATE, user, project, file, ruleDefinitionDto, RuleType.SECURITY_HOTSPOT);
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
.addChildren(
builder(Type.FILE, 11).setKey(file.getDbKey()).setPublicKey(file.getKey()).setName(file.longName()).build())
.build());
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
DefaultIssue issue = prepareIssue(issueCreatedAt, user, project, file, ruleDefinitionDto, randomTypeExceptHotspot);
IssuesChangesNotification issuesChangesNotification = mock(IssuesChangesNotification.class);
verifyNoMoreInteractions(notificationService);
}
- private DefaultIssue prepareIssue(long issueCreatedAt, UserDto user, ComponentDto project, ComponentDto file, RuleDefinitionDto ruleDefinitionDto, RuleType type) {
+ private DefaultIssue prepareIssue(long issueCreatedAt, UserDto user, ComponentDto project, ComponentDto file, RuleDto ruleDefinitionDto, RuleType type) {
DefaultIssue issue = newIssue(ruleDefinitionDto, project, file).setType(type).toDefaultIssue()
.setNew(false).setChanged(true).setSendNotifications(true).setCreationDate(new Date(issueCreatedAt)).setAssigneeUuid(user.getUuid());
protoIssueCache.newAppender().append(issue).close();
treeRootHolder.setRoot(builder(Type.PROJECT, 2).setKey(branch.getDbKey()).setPublicKey(branch.getKey()).setName(branch.longName()).setUuid(branch.uuid()).addChildren(
builder(Type.FILE, 11).setKey(file.getDbKey()).setPublicKey(file.getKey()).setName(file.longName()).build()).build());
analysisMetadataHolder.setProject(Project.from(project));
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
DefaultIssue issue = newIssue(ruleDefinitionDto, branch, file).setType(randomTypeExceptHotspot).toDefaultIssue()
.setNew(false)
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto().setDbKey(PROJECT.getDbKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setDbKey(FILE.getDbKey()).setLongName(FILE.getName());
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
List<DefaultIssue> issues = IntStream.range(0, 2001 + new Random().nextInt(10))
.mapToObj(i -> newIssue(ruleDefinitionDto, project, file).setKee("uuid_" + i).setType(randomTypeExceptHotspot).toDefaultIssue()
private RuleDto insertRule(String ruleKey1) {
RuleDto dto = new RuleDto().setRepositoryKey(SOME_REPO).setScope(Scope.MAIN).setRuleKey(ruleKey1).setStatus(RuleStatus.READY);
- dbTester.rules().insert(dto.getDefinition());
+ dbTester.rules().insert(dto);
dbSession.commit();
return dto;
}
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
private RuleDto insertRule(RuleKey ruleKey, boolean isExternal, boolean isAdHoc) {
dbTester.rules().insert(
- new RuleDefinitionDto()
+ new RuleDto()
.setRuleKey(ruleKey)
.setIsExternal(isExternal)
.setIsAdHoc(isAdHoc)
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.api.utils.DateUtils.dateToLong;
}
public Set<String> getSecurityStandards() {
- return RuleDefinitionDto.deserializeSecurityStandardsString(securityStandards);
+ return RuleDto.deserializeSecurityStandardsString(securityStandards);
}
/**
return ruleKey;
}
- public IssueDto setRule(RuleDefinitionDto rule) {
+ public IssueDto setRule(RuleDto rule) {
Preconditions.checkNotNull(rule.getUuid(), "Rule must be persisted.");
this.ruleUuid = rule.getUuid();
this.ruleKey = rule.getRuleKey();
/**
* Should only be used to persist in E/S
* <p/>
- * Please use {@link #setRule(RuleDefinitionDto)} instead
+ * Please use {@link #setRule(RuleDto)} instead
*/
public IssueDto setLanguage(String language) {
this.language = language;
/**
* Should only be used to persist in E/S
* <p/>
- * Please use {@link #setRule(RuleDefinitionDto)} instead
+ * Please use {@link #setRule(RuleDto)} instead
*/
public IssueDto setRuleKey(String repo, String rule) {
this.ruleRepo = repo;
import org.sonar.core.util.Uuids;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkArgument;
// only statics
}
- public static IssueDto newIssue(RuleDefinitionDto rule, ComponentDto project, ComponentDto file) {
+ public static IssueDto newIssue(RuleDto rule, ComponentDto project, ComponentDto file) {
checkArgument(project.qualifier().equals(Qualifiers.PROJECT), "Second parameter should be a project");
return newIssue(rule, project.uuid(), project.getDbKey(), file);
}
- public static IssueDto newIssue(RuleDefinitionDto rule, ProjectDto project, ComponentDto file) {
+ public static IssueDto newIssue(RuleDto rule, ProjectDto project, ComponentDto file) {
return newIssue(rule, project.getUuid(), project.getKey(), file);
}
- public static IssueDto newIssue(RuleDefinitionDto rule, String projectUuid, String projectKey, ComponentDto file) {
+ public static IssueDto newIssue(RuleDto rule, String projectUuid, String projectKey, ComponentDto file) {
checkArgument(file.projectUuid().equals(projectUuid), "The file doesn't belong to the project");
return new IssueDto()
public static IssueDto newDto(RuleDto rule, ComponentDto file, ComponentDto project) {
return new IssueDto()
.setKee(Uuids.createFast())
- .setRule(rule.getDefinition())
+ .setRule(rule)
.setType(RuleType.CODE_SMELL)
.setComponent(file)
.setProject(project)
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.ActiveRule;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.SeverityUtil;
import static java.util.Objects.requireNonNull;
return this;
}
- public static ActiveRuleDto createFor(QProfileDto profile, RuleDefinitionDto ruleDto) {
+ public static ActiveRuleDto createFor(QProfileDto profile, RuleDto ruleDto) {
requireNonNull(profile.getRulesProfileUuid(), "Profile is not persisted");
requireNonNull(ruleDto.getUuid(), "Rule is not persisted");
ActiveRuleDto dto = new ActiveRuleDto();
*/
package org.sonar.db.rule;
+import com.google.common.annotations.VisibleForTesting;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
return Optional.ofNullable(mapper(session).selectByKey(key));
}
- public Optional<RuleDefinitionDto> selectDefinitionByKey(DbSession session, RuleKey key) {
- return Optional.ofNullable(mapper(session).selectDefinitionByKey(key));
- }
-
public Optional<RuleMetadataDto> selectMetadataByKey(DbSession session, RuleKey key) {
return Optional.ofNullable(mapper(session).selectMetadataByKey(key));
}
- public List<RuleMetadataDto> selectMetadataByKeys(DbSession session, Collection<RuleKey> keys) {
- if (keys.isEmpty()) {
- return emptyList();
- }
- return executeLargeInputs(keys, mapper(session)::selectMetadataByKeys);
- }
-
public RuleDto selectOrFailByKey(DbSession session, RuleKey key) {
return Optional.ofNullable(mapper(session).selectByKey(key))
.orElseThrow(() -> new RowNotFoundException(String.format("Rule with key '%s' does not exist", key)));
}
- public RuleDefinitionDto selectOrFailDefinitionByKey(DbSession session, RuleKey key) {
- return Optional.ofNullable(mapper(session).selectDefinitionByKey(key))
- .orElseThrow(() -> new RowNotFoundException(String.format("Rule with key '%s' does not exist", key)));
- }
-
public Optional<RuleDto> selectByUuid(String uuid, DbSession session) {
return Optional.ofNullable(mapper(session).selectByUuid(uuid));
}
- public Optional<RuleDefinitionDto> selectDefinitionByUuid(String uuid, DbSession session) {
- return Optional.ofNullable(mapper(session).selectDefinitionByUuid(uuid));
- }
-
- public List<RuleDto> selectByUuids(DbSession session, List<String> uuids) {
+ public List<RuleDto> selectByUuids(DbSession session, Collection<String> uuids) {
if (uuids.isEmpty()) {
return emptyList();
}
return executeLargeInputs(uuids, chunk -> mapper(session).selectByUuids(chunk));
}
- public List<RuleDefinitionDto> selectDefinitionByUuids(DbSession session, Collection<String> uuids) {
- if (uuids.isEmpty()) {
- return emptyList();
- }
- return executeLargeInputs(uuids, mapper(session)::selectDefinitionByUuids);
- }
-
public List<RuleDto> selectByKeys(DbSession session, Collection<RuleKey> keys) {
if (keys.isEmpty()) {
return emptyList();
return executeLargeInputs(keys, chunk -> mapper(session).selectByKeys(chunk));
}
- public List<RuleDefinitionDto> selectDefinitionByKeys(DbSession session, Collection<RuleKey> keys) {
- if (keys.isEmpty()) {
- return emptyList();
- }
- return executeLargeInputs(keys, mapper(session)::selectDefinitionByKeys);
- }
-
- public List<RuleDefinitionDto> selectEnabled(DbSession session) {
+ public List<RuleDto> selectEnabled(DbSession session) {
return mapper(session).selectEnabled();
}
return mapper(session).selectAll();
}
- public List<RuleDefinitionDto> selectAllDefinitions(DbSession session) {
- return mapper(session).selectAllDefinitions();
- }
-
public List<RuleDto> selectByTypeAndLanguages(DbSession session, List<Integer> types, List<String> languages) {
return executeLargeInputs(languages, chunk -> mapper(session).selectByTypeAndLanguages(types, chunk));
}
return mapper(session).selectByQuery(ruleQuery);
}
- public void insert(DbSession session, RuleDefinitionDto ruleDefinitionDto) {
- checkNotNull(ruleDefinitionDto.getUuid(), "RuleDefinitionDto has no 'uuid'.");
+ public void insert(DbSession session, RuleDto ruleDto) {
+ checkNotNull(ruleDto.getUuid(), "RuleDto has no 'uuid'.");
RuleMapper mapper = mapper(session);
- mapper.insertDefinition(ruleDefinitionDto);
- insertRuleDescriptionSectionDtos(ruleDefinitionDto, mapper);
- }
-
- public void insert(DbSession session, RuleMetadataDto dto) {
- checkNotNull(dto.getRuleUuid(), "RuleMetadataDto has no 'ruleUuid'.");
- mapper(session).insertMetadata(dto);
+ mapper.insertRule(ruleDto);
+ insertOrUpdateRuleMetadata(session, ruleDto.getMetadata());
+ updateRuleDescriptionSectionDtos(ruleDto, mapper);
}
- public void update(DbSession session, RuleDefinitionDto ruleDefinitionDto) {
+ public void update(DbSession session, RuleDto ruleDto) {
RuleMapper mapper = mapper(session);
- mapper.updateDefinition(ruleDefinitionDto);
- updateRuleDescriptionDtos(ruleDefinitionDto, mapper);
+ mapper.updateRule(ruleDto);
+ insertOrUpdateRuleMetadata(session, ruleDto.getMetadata());
+ updateRuleDescriptionSectionDtos(ruleDto, mapper);
}
- private void updateRuleDescriptionDtos(RuleDefinitionDto ruleDefinitionDto, RuleMapper mapper) {
- mapper.deleteRuleDescriptionSection(ruleDefinitionDto.getUuid());
- insertRuleDescriptionSectionDtos(ruleDefinitionDto, mapper);
+ private static void updateRuleDescriptionSectionDtos(RuleDto ruleDto, RuleMapper mapper) {
+ mapper.deleteRuleDescriptionSection(ruleDto.getUuid());
+ insertRuleDescriptionSectionDtos(ruleDto, mapper);
}
- private static void insertRuleDescriptionSectionDtos(RuleDefinitionDto ruleDefinitionDto, RuleMapper mapper) {
- ruleDefinitionDto.getRuleDescriptionSectionDtos()
- .forEach(section -> mapper.insertRuleDescriptionSection(ruleDefinitionDto.getUuid(), section));
+ private static void insertRuleDescriptionSectionDtos(RuleDto ruleDto, RuleMapper mapper) {
+ ruleDto.getRuleDescriptionSectionDtos()
+ .forEach(section -> mapper.insertRuleDescriptionSection(ruleDto.getUuid(), section));
}
- public void insertOrUpdate(DbSession session, RuleMetadataDto dto) {
- if (mapper(session).countMetadata(dto) > 0) {
- mapper(session).updateMetadata(dto);
+ @VisibleForTesting
+ void insertOrUpdateRuleMetadata(DbSession session, RuleMetadataDto ruleMetadataDto) {
+ if (ruleMetadataDto.isUndefined()) {
+ mapper(session).deleteMetadata(ruleMetadataDto.getRuleUuid());
+ } else if (mapper(session).countMetadata(ruleMetadataDto) > 0) {
+ mapper(session).updateMetadata(ruleMetadataDto);
} else {
- mapper(session).insertMetadata(dto);
+ mapper(session).insertMetadata(ruleMetadataDto);
}
}
return executeLargeInputs(ruleUuids, mapper(dbSession)::selectParamsByRuleUuids);
}
- public void insertRuleParam(DbSession session, RuleDefinitionDto rule, RuleParamDto param) {
+ public void insertRuleParam(DbSession session, RuleDto rule, RuleParamDto param) {
checkNotNull(rule.getUuid(), "Rule uuid must be set");
param.setRuleUuid(rule.getUuid());
mapper(session).insertParameter(param);
}
- public RuleParamDto updateRuleParam(DbSession session, RuleDefinitionDto rule, RuleParamDto param) {
+ public RuleParamDto updateRuleParam(DbSession session, RuleDto rule, RuleParamDto param) {
checkNotNull(rule.getUuid(), "Rule uuid must be set");
checkNotNull(param.getUuid(), "Rule parameter is not yet persisted must be set");
param.setRuleUuid(rule.getUuid());
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 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.db.rule;
-
-import com.google.common.base.Splitter;
-import com.google.common.collect.ImmutableSet;
-import java.util.HashSet;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rule.RuleStatus;
-import org.sonar.api.rules.RuleType;
-import org.sonar.db.rule.RuleDto.Scope;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
-
-public class RuleDefinitionDto {
-
- private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
-
- private String uuid;
- private String repositoryKey;
- private String ruleKey;
-
- private Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = new HashSet<>();
-
- /**
- * Description format can be null on external rule, otherwise it should never be null
- */
- private RuleDto.Format descriptionFormat;
- private RuleStatus status;
- private String name;
- private String configKey;
-
- /**
- * Severity can be null on external rule, otherwise it should never be null
- */
- private Integer severity;
-
- private boolean isTemplate;
-
- /**
- * This flag specify that this is an external rule, meaning that generated issues from this rule will be provided by the analyzer without being activated on a quality profile.
- */
- private boolean isExternal;
-
- /**
- * When an external rule is defined as ad hoc, it means that it's not defined using {@link org.sonar.api.server.rule.RulesDefinition.Context#createExternalRepository(String, String)}.
- * As the opposite, an external rule not being defined as ad hoc is declared by using {@link org.sonar.api.server.rule.RulesDefinition.Context#createExternalRepository(String, String)}.
- * This flag is only used for external rules (it can only be set to true for when {@link #isExternal()} is true)
- */
- private boolean isAdHoc;
-
- private String language;
- private String templateUuid;
- private String defRemediationFunction;
- private String defRemediationGapMultiplier;
- private String defRemediationBaseEffort;
- private String gapDescription;
- private String systemTags;
- private String securityStandards;
- private int type;
- private Scope scope;
-
- private RuleKey key;
-
- private String pluginKey;
-
- private long createdAt;
- private long updatedAt;
-
- public RuleDefinitionDto() {
- // nothing to do here
- }
-
- public static Set<String> deserializeTagsString(@Nullable String tags) {
- return deserializeStringSet(tags);
- }
-
- public static Set<String> deserializeSecurityStandardsString(@Nullable String securityStandards) {
- return deserializeStringSet(securityStandards);
- }
-
- private static Set<String> deserializeStringSet(@Nullable String str) {
- if (str == null || str.isEmpty()) {
- return ImmutableSet.of();
- }
-
- return ImmutableSet.copyOf(SPLITTER.split(str));
- }
-
- private static String serializeStringSet(@Nullable Set<String> strings) {
- return strings == null || strings.isEmpty() ? null : StringUtils.join(strings, ',');
- }
-
- public RuleKey getKey() {
- if (key == null) {
- key = RuleKey.of(getRepositoryKey(), getRuleKey());
- }
- return key;
- }
-
- RuleDefinitionDto setKey(RuleKey key) {
- this.key = key;
- setRepositoryKey(key.repository());
- setRuleKey(key.rule());
- return this;
- }
-
- public String getUuid() {
- return uuid;
- }
-
- public RuleDefinitionDto setUuid(String uuid) {
- this.uuid = uuid;
- return this;
- }
-
- public String getRepositoryKey() {
- return repositoryKey;
- }
-
- public RuleDefinitionDto setRepositoryKey(String s) {
- checkArgument(s.length() <= 255, "Rule repository is too long: %s", s);
- this.repositoryKey = s;
- return this;
- }
-
- public String getRuleKey() {
- return ruleKey;
- }
-
- public RuleDefinitionDto setRuleKey(String s) {
- checkArgument(s.length() <= 200, "Rule key is too long: %s", s);
- this.ruleKey = s;
- return this;
- }
-
- public RuleDefinitionDto setRuleKey(RuleKey ruleKey) {
- this.repositoryKey = ruleKey.repository();
- this.ruleKey = ruleKey.rule();
- this.key = ruleKey;
- return this;
- }
-
- @CheckForNull
- public RuleDescriptionSectionDto getRuleDescriptionSectionDto(String ruleDescriptionSectionKey) {
- return findExistingSectionWithSameKey(ruleDescriptionSectionKey).orElse(null);
- }
-
- @CheckForNull
- public RuleDescriptionSectionDto getDefaultRuleDescriptionSectionDto() {
- return findExistingSectionWithSameKey(DEFAULT_KEY).orElse(null);
- }
-
- public RuleDefinitionDto addRuleDescriptionSectionDto(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- checkArgument(sectionWithSameKeyShouldNotExist(ruleDescriptionSectionDto),
- "A section with key %s already exists", ruleDescriptionSectionDto.getKey());
- ruleDescriptionSectionDtos.add(ruleDescriptionSectionDto);
- return this;
- }
-
- private boolean sectionWithSameKeyShouldNotExist(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- return findExistingSectionWithSameKey(ruleDescriptionSectionDto.getKey()).isEmpty();
- }
-
- public RuleDefinitionDto addOrReplaceRuleDescriptionSectionDto(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- Optional<RuleDescriptionSectionDto> existingSectionWithSameKey = findExistingSectionWithSameKey(ruleDescriptionSectionDto.getKey());
- existingSectionWithSameKey.ifPresent(ruleDescriptionSectionDtos::remove);
- ruleDescriptionSectionDtos.add(ruleDescriptionSectionDto);
- return this;
- }
-
- private Optional<RuleDescriptionSectionDto> findExistingSectionWithSameKey(String ruleDescriptionSectionKey) {
- return ruleDescriptionSectionDtos.stream().filter(section -> section.getKey().equals(ruleDescriptionSectionKey)).findAny();
- }
-
- @CheckForNull
- public RuleDto.Format getDescriptionFormat() {
- return descriptionFormat;
- }
-
- public RuleDefinitionDto setDescriptionFormat(@Nullable RuleDto.Format descriptionFormat) {
- this.descriptionFormat = descriptionFormat;
- return this;
- }
-
- public RuleStatus getStatus() {
- return status;
- }
-
- public RuleDefinitionDto setStatus(@Nullable RuleStatus s) {
- this.status = s;
- return this;
- }
-
- public String getName() {
- return name;
- }
-
- public RuleDefinitionDto setName(@Nullable String s) {
- checkArgument(s == null || s.length() <= 255, "Rule name is too long: %s", s);
- this.name = s;
- return this;
- }
-
- public String getConfigKey() {
- return configKey;
- }
-
- public RuleDefinitionDto setConfigKey(@Nullable String configKey) {
- this.configKey = configKey;
- return this;
- }
-
- @CheckForNull
- public Integer getSeverity() {
- return severity;
- }
-
- @CheckForNull
- public String getSeverityString() {
- return severity != null ? SeverityUtil.getSeverityFromOrdinal(severity) : null;
- }
-
- public RuleDefinitionDto setSeverity(@Nullable String severity) {
- return this.setSeverity(severity != null ? SeverityUtil.getOrdinalFromSeverity(severity) : null);
- }
-
- public RuleDefinitionDto setSeverity(@Nullable Integer severity) {
- this.severity = severity;
- return this;
- }
-
- public boolean isTemplate() {
- return isTemplate;
- }
-
- public RuleDefinitionDto setIsTemplate(boolean isTemplate) {
- this.isTemplate = isTemplate;
- return this;
- }
-
- public boolean isExternal() {
- return isExternal;
- }
-
- public RuleDefinitionDto setIsExternal(boolean isExternal) {
- this.isExternal = isExternal;
- return this;
- }
-
- public boolean isAdHoc() {
- return isAdHoc;
- }
-
- public RuleDefinitionDto setIsAdHoc(boolean isAdHoc) {
- this.isAdHoc = isAdHoc;
- return this;
- }
-
- @CheckForNull
- public String getLanguage() {
- return language;
- }
-
- public RuleDefinitionDto setLanguage(String language) {
- this.language = language;
- return this;
- }
-
- @CheckForNull
- public String getTemplateUuid() {
- return templateUuid;
- }
-
- public boolean isCustomRule() {
- return getTemplateUuid() != null;
- }
-
- public RuleDefinitionDto setTemplateUuid(@Nullable String templateUuid) {
- this.templateUuid = templateUuid;
- return this;
- }
-
- @CheckForNull
- public String getDefRemediationFunction() {
- return defRemediationFunction;
- }
-
- public RuleDefinitionDto setDefRemediationFunction(@Nullable String defaultRemediationFunction) {
- this.defRemediationFunction = defaultRemediationFunction;
- return this;
- }
-
- @CheckForNull
- public String getDefRemediationGapMultiplier() {
- return defRemediationGapMultiplier;
- }
-
- public RuleDefinitionDto setDefRemediationGapMultiplier(@Nullable String defaultRemediationGapMultiplier) {
- this.defRemediationGapMultiplier = defaultRemediationGapMultiplier;
- return this;
- }
-
- @CheckForNull
- public String getDefRemediationBaseEffort() {
- return defRemediationBaseEffort;
- }
-
- public RuleDefinitionDto setDefRemediationBaseEffort(@Nullable String defaultRemediationBaseEffort) {
- this.defRemediationBaseEffort = defaultRemediationBaseEffort;
- return this;
- }
-
- @CheckForNull
- public String getGapDescription() {
- return gapDescription;
- }
-
- public RuleDefinitionDto setGapDescription(@Nullable String s) {
- this.gapDescription = s;
- return this;
- }
-
- public Set<String> getSystemTags() {
- return deserializeTagsString(systemTags);
- }
-
- private String getSystemTagsField() {
- return systemTags;
- }
-
- void setSystemTagsField(String s) {
- systemTags = s;
- }
-
- public RuleDefinitionDto setSystemTags(Set<String> tags) {
- this.systemTags = serializeStringSet(tags);
- return this;
- }
-
- public Set<String> getSecurityStandards() {
- return deserializeSecurityStandardsString(securityStandards);
- }
-
- private String getSecurityStandardsField() {
- return securityStandards;
- }
-
- void setSecurityStandardsField(String s) {
- securityStandards = s;
- }
-
- public RuleDefinitionDto setSecurityStandards(Set<String> standards) {
- this.securityStandards = serializeStringSet(standards);
- return this;
- }
-
- public int getType() {
- return type;
- }
-
- public RuleDefinitionDto setType(int type) {
- this.type = type;
- return this;
- }
-
- public RuleDefinitionDto setType(RuleType type) {
- this.type = type.getDbConstant();
- return this;
- }
-
- public long getCreatedAt() {
- return createdAt;
- }
-
- public RuleDefinitionDto setCreatedAt(long createdAt) {
- this.createdAt = createdAt;
- return this;
- }
-
- public long getUpdatedAt() {
- return updatedAt;
- }
-
- public RuleDefinitionDto setUpdatedAt(long updatedAt) {
- this.updatedAt = updatedAt;
- return this;
- }
-
- public Scope getScope() {
- return this.scope;
- }
-
- public RuleDefinitionDto setScope(Scope scope) {
- this.scope = scope;
- return this;
- }
-
- @CheckForNull
- public String getPluginKey() {
- return pluginKey;
- }
-
- public RuleDefinitionDto setPluginKey(@Nullable String pluginKey) {
- this.pluginKey = pluginKey;
- return this;
- }
-
- public Set<RuleDescriptionSectionDto> getRuleDescriptionSectionDtos() {
- return ruleDescriptionSectionDtos;
- }
-
- void setRuleDescriptionSectionDtos(Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos) {
- this.ruleDescriptionSectionDtos = ruleDescriptionSectionDtos;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof RuleDefinitionDto)) {
- return false;
- }
- if (this == obj) {
- return true;
- }
- RuleDefinitionDto other = (RuleDefinitionDto) obj;
- return Objects.equals(this.uuid, other.uuid);
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 37)
- .append(this.uuid)
- .toHashCode();
- }
-
- @Override
- public String toString() {
- return "RuleDefinitionDto{" +
- "uuid=" + uuid +
- ", repositoryKey='" + repositoryKey + '\'' +
- ", ruleKey='" + ruleKey + '\'' +
- ", ruleDescriptionSections='" + ruleDescriptionSectionDtos + '\'' +
- ", descriptionFormat=" + descriptionFormat +
- ", status=" + status +
- ", name='" + name + '\'' +
- ", configKey='" + configKey + '\'' +
- ", severity=" + severity +
- ", isTemplate=" + isTemplate +
- ", language='" + language + '\'' +
- ", templateUuid=" + templateUuid +
- ", defRemediationFunction='" + defRemediationFunction + '\'' +
- ", defRemediationGapMultiplier='" + defRemediationGapMultiplier + '\'' +
- ", defRemediationBaseEffort='" + defRemediationBaseEffort + '\'' +
- ", gapDescription='" + gapDescription + '\'' +
- ", systemTags='" + systemTags + '\'' +
- ", type=" + type +
- ", key=" + key +
- ", createdAt=" + createdAt +
- ", updatedAt=" + updatedAt +
- ", scope=" + scope +
- '}';
- }
-
-}
*/
package org.sonar.db.rule;
-import java.util.Objects;
import java.util.StringJoiner;
import static org.sonar.api.utils.Preconditions.checkArgument;
.toString();
}
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- RuleDescriptionSectionDto that = (RuleDescriptionSectionDto) o;
- return Objects.equals(uuid, that.uuid) && Objects.equals(key, that.key) && Objects.equals(content, that.content);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(uuid, key, content);
- }
-
public static final class RuleDescriptionSectionDtoBuilder {
private String uuid;
private String key = null;
*/
package org.sonar.db.rule;
-import java.util.Collection;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableSet;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Collections.emptySet;
+import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
+
public class RuleDto {
public enum Format {
MAIN, TEST, ALL
}
- private final RuleDefinitionDto definition;
+ private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
+
+ private String uuid;
+ private String repositoryKey;
+ private String ruleKey;
+
+ private Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = new HashSet<>();
+
+ /**
+ * Description format can be null on external rule, otherwise it should never be null
+ */
+ private RuleDto.Format descriptionFormat;
+ private RuleStatus status;
+ private String name;
+ private String configKey;
+
+ /**
+ * Severity can be null on external rule, otherwise it should never be null
+ */
+ private Integer severity;
+
+ private boolean isTemplate;
+
+ /**
+ * This flag specify that this is an external rule, meaning that generated issues from this rule will be provided by the analyzer without being activated on a quality profile.
+ */
+ private boolean isExternal;
+
+ /**
+ * When an external rule is defined as ad hoc, it means that it's not defined using {@link org.sonar.api.server.rule.RulesDefinition.Context#createExternalRepository(String, String)}.
+ * As the opposite, an external rule not being defined as ad hoc is declared by using {@link org.sonar.api.server.rule.RulesDefinition.Context#createExternalRepository(String, String)}.
+ * This flag is only used for external rules (it can only be set to true for when {@link #isExternal()} is true)
+ */
+ private boolean isAdHoc;
+
+ private String language;
+ private String templateUuid;
+ private String defRemediationFunction;
+ private String defRemediationGapMultiplier;
+ private String defRemediationBaseEffort;
+ private String gapDescription;
+ private String systemTagsField;
+ private String securityStandardsField;
+ private int type;
+ private Scope scope;
+
+ private RuleKey key;
+
+ private String pluginKey;
+
+ private long createdAt;
+ private long updatedAt;
+
private final RuleMetadataDto metadata;
public RuleDto() {
- this(new RuleDefinitionDto(), new RuleMetadataDto());
+ this(new RuleMetadataDto());
}
- public RuleDto(RuleDefinitionDto definition, RuleMetadataDto metadata) {
- this.definition = definition;
+ public RuleDto(RuleMetadataDto metadata) {
this.metadata = metadata;
}
- public RuleDefinitionDto getDefinition() {
- return definition;
- }
public RuleMetadataDto getMetadata() {
return metadata;
}
public RuleKey getKey() {
- return definition.getKey();
+ if (key == null) {
+ key = RuleKey.of(getRepositoryKey(), getRuleKey());
+ }
+ return key;
+ }
+
+ RuleDto setKey(RuleKey key) {
+ this.key = key;
+ setRepositoryKey(key.repository());
+ setRuleKey(key.rule());
+ return this;
}
public String getUuid() {
- return definition.getUuid();
+ return uuid;
}
public RuleDto setUuid(String uuid) {
- definition.setUuid(uuid);
+ this.uuid = uuid;
metadata.setRuleUuid(uuid);
return this;
}
public String getRepositoryKey() {
- return definition.getRepositoryKey();
+ return repositoryKey;
}
- public RuleDto setRepositoryKey(String s) {
- definition.setRepositoryKey(s);
+ public RuleDto setRepositoryKey(String repositoryKey) {
+ checkArgument(repositoryKey.length() <= 255, "Rule repository is too long: %s", repositoryKey);
+ this.repositoryKey = repositoryKey;
return this;
}
public String getRuleKey() {
- return definition.getRuleKey();
+ return ruleKey;
}
- public RuleDto setRuleKey(String s) {
- definition.setRuleKey(s);
+ public RuleDto setRuleKey(String ruleKey) {
+ checkArgument(ruleKey.length() <= 200, "Rule key is too long: %s", ruleKey);
+ this.ruleKey = ruleKey;
+ return this;
+ }
+
+ public RuleDto setRuleKey(RuleKey ruleKey) {
+ this.repositoryKey = ruleKey.repository();
+ this.ruleKey = ruleKey.rule();
+ this.key = ruleKey;
return this;
}
@CheckForNull
public String getPluginKey() {
- return definition.getPluginKey();
+ return pluginKey;
}
- public RuleDto setPluginKey(@Nullable String s) {
- definition.setPluginKey(s);
+ public RuleDto setPluginKey(@Nullable String pluginKey) {
+ this.pluginKey = pluginKey;
return this;
}
- @CheckForNull
- public RuleDescriptionSectionDto getRuleDescriptionSection(String ruleDescriptionSectionKey) {
- return definition.getRuleDescriptionSectionDto(ruleDescriptionSectionKey);
+ public Set<RuleDescriptionSectionDto> getRuleDescriptionSectionDtos() {
+ return ruleDescriptionSectionDtos;
}
@CheckForNull
- public RuleDescriptionSectionDto getDefaultRuleDescriptionSection() {
- return definition.getDefaultRuleDescriptionSectionDto();
+ public RuleDescriptionSectionDto getRuleDescriptionSectionDto(String ruleDescriptionSectionKey) {
+ return findExistingSectionWithSameKey(ruleDescriptionSectionKey).orElse(null);
}
- public Collection<RuleDescriptionSectionDto> getRuleDescriptionSectionDtos() {
- return definition.getRuleDescriptionSectionDtos();
+ @CheckForNull
+ public RuleDescriptionSectionDto getDefaultRuleDescriptionSection() {
+ return findExistingSectionWithSameKey(DEFAULT_KEY).orElse(null);
}
public RuleDto addRuleDescriptionSectionDto(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- definition.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
+ checkArgument(sectionWithSameKeyShouldNotExist(ruleDescriptionSectionDto),
+ "A section with key %s already exists", ruleDescriptionSectionDto.getKey());
+ ruleDescriptionSectionDtos.add(ruleDescriptionSectionDto);
return this;
}
+ private boolean sectionWithSameKeyShouldNotExist(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
+ return findExistingSectionWithSameKey(ruleDescriptionSectionDto.getKey()).isEmpty();
+ }
+
public RuleDto addOrReplaceRuleDescriptionSectionDto(RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- definition.addOrReplaceRuleDescriptionSectionDto(ruleDescriptionSectionDto);
+ Optional<RuleDescriptionSectionDto> existingSectionWithSameKey = findExistingSectionWithSameKey(ruleDescriptionSectionDto.getKey());
+ existingSectionWithSameKey.ifPresent(ruleDescriptionSectionDtos::remove);
+ ruleDescriptionSectionDtos.add(ruleDescriptionSectionDto);
return this;
}
- void setRuleDescriptionSectionDtos(Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos) {
- definition.setRuleDescriptionSectionDtos(ruleDescriptionSectionDtos);
+ private Optional<RuleDescriptionSectionDto> findExistingSectionWithSameKey(String ruleDescriptionSectionKey) {
+ return ruleDescriptionSectionDtos.stream().filter(section -> section.getKey().equals(ruleDescriptionSectionKey)).findAny();
}
+
+ @CheckForNull
public Format getDescriptionFormat() {
- return definition.getDescriptionFormat();
+ return descriptionFormat;
}
public RuleDto setDescriptionFormat(Format descriptionFormat) {
- definition.setDescriptionFormat(descriptionFormat);
+ this.descriptionFormat = descriptionFormat;
return this;
}
public RuleStatus getStatus() {
- return definition.getStatus();
+ return status;
}
- public RuleDto setStatus(@Nullable RuleStatus s) {
- definition.setStatus(s);
+ public RuleDto setStatus(@Nullable RuleStatus status) {
+ this.status = status;
return this;
}
public String getName() {
- return definition.getName();
+ return name;
}
- public RuleDto setName(@Nullable String s) {
- definition.setName(s);
+ public RuleDto setName(@Nullable String name) {
+ checkArgument(name == null || name.length() <= 255, "Rule name is too long: %s", name);
+ this.name = name;
return this;
}
public String getConfigKey() {
- return definition.getConfigKey();
+ return configKey;
}
public RuleDto setConfigKey(@Nullable String configKey) {
- definition.setConfigKey(configKey);
+ this.configKey = configKey;
return this;
}
public Scope getScope() {
- return definition.getScope();
+ return scope;
}
public RuleDto setScope(Scope scope) {
- definition.setScope(scope);
+ this.scope = scope;
return this;
}
@CheckForNull
public Integer getSeverity() {
- return definition.getSeverity();
+ return severity;
}
@CheckForNull
public String getSeverityString() {
- return definition.getSeverityString();
+ return severity != null ? SeverityUtil.getSeverityFromOrdinal(severity) : null;
}
public RuleDto setSeverity(@Nullable String severity) {
- definition.setSeverity(severity);
- return this;
+ return this.setSeverity(severity != null ? SeverityUtil.getOrdinalFromSeverity(severity) : null);
}
public RuleDto setSeverity(@Nullable Integer severity) {
- definition.setSeverity(severity);
+ this.severity = severity;
return this;
}
public boolean isExternal() {
- return definition.isExternal();
+ return isExternal;
}
public RuleDto setIsExternal(boolean isExternal) {
- definition.setIsExternal(isExternal);
+ this.isExternal = isExternal;
return this;
}
public boolean isAdHoc() {
- return definition.isAdHoc();
+ return isAdHoc;
}
public RuleDto setIsAdHoc(boolean isAdHoc) {
- definition.setIsAdHoc(isAdHoc);
+ this.isAdHoc = isAdHoc;
return this;
}
}
public boolean isTemplate() {
- return definition.isTemplate();
+ return isTemplate;
}
public RuleDto setIsTemplate(boolean isTemplate) {
- definition.setIsTemplate(isTemplate);
+ this.isTemplate = isTemplate;
return this;
}
@CheckForNull
public String getLanguage() {
- return definition.getLanguage();
+ return language;
}
public RuleDto setLanguage(String language) {
- definition.setLanguage(language);
+ this.language = language;
return this;
}
@CheckForNull
public String getTemplateUuid() {
- return definition.getTemplateUuid();
+ return templateUuid;
}
public RuleDto setTemplateUuid(@Nullable String templateUuid) {
- definition.setTemplateUuid(templateUuid);
+ this.templateUuid = templateUuid;
return this;
}
- @CheckForNull
- public String getDefRemediationFunction() {
- return definition.getDefRemediationFunction();
+ public boolean isCustomRule() {
+ return getTemplateUuid() != null;
}
- public RuleDto setDefRemediationFunction(@Nullable String defaultRemediationFunction) {
- definition.setDefRemediationFunction(defaultRemediationFunction);
- return this;
- }
-
- @CheckForNull
- public String getDefRemediationGapMultiplier() {
- return definition.getDefRemediationGapMultiplier();
- }
-
- public RuleDto setDefRemediationGapMultiplier(@Nullable String defaultRemediationGapMultiplier) {
- definition.setDefRemediationGapMultiplier(defaultRemediationGapMultiplier);
- return this;
- }
-
- @CheckForNull
- public String getDefRemediationBaseEffort() {
- return definition.getDefRemediationBaseEffort();
- }
-
- public RuleDto setDefRemediationBaseEffort(@Nullable String defaultRemediationBaseEffort) {
- definition.setDefRemediationBaseEffort(defaultRemediationBaseEffort);
+ public RuleDto setSystemTags(Set<String> tags) {
+ this.systemTagsField = serializeStringSet(tags);
return this;
}
- @CheckForNull
- public String getGapDescription() {
- return definition.getGapDescription();
- }
-
- public RuleDto setGapDescription(@Nullable String s) {
- definition.setGapDescription(s);
+ public RuleDto setSecurityStandards(Set<String> standards) {
+ this.securityStandardsField = serializeStringSet(standards);
return this;
}
- public RuleDto setSystemTags(Set<String> tags) {
- this.definition.setSystemTags(tags);
- return this;
+ public Set<String> getSystemTags() {
+ return deserializeTagsString(systemTagsField);
}
- public RuleDto setSecurityStandards(Set<String> standards) {
- this.definition.setSecurityStandards(standards);
- return this;
+ public Set<String> getSecurityStandards() {
+ return deserializeSecurityStandardsString(securityStandardsField);
}
public int getType() {
- return definition.getType();
+ return type;
}
public RuleDto setType(int type) {
- definition.setType(type);
+ this.type = type;
return this;
}
public RuleDto setType(RuleType type) {
- definition.setType(type);
+ this.type = type.getDbConstant();
return this;
}
- public Set<String> getSystemTags() {
- return definition.getSystemTags();
- }
-
- /**
- * Used in MyBatis mapping.
- */
- private void setSystemTagsField(String s) {
- definition.setSystemTagsField(s);
- }
-
- public Set<String> getSecurityStandards() {
- return definition.getSecurityStandards();
- }
-
- /**
- * Used in MyBatis mapping.
- */
- private void setSecurityStandardsField(String s) {
- definition.setSecurityStandardsField(s);
- }
public long getCreatedAt() {
- return definition.getCreatedAt();
- }
-
- public RuleDto setCreatedAt(long createdAt) {
- definition.setCreatedAt(createdAt);
- metadata.setCreatedAt(createdAt);
- return this;
- }
-
- /**
- * Used in MyBatis mapping.
- */
- private void setCreatedAtFromDefinition(@Nullable Long createdAt) {
- if (createdAt != null && createdAt > definition.getCreatedAt()) {
- setCreatedAt(createdAt);
- }
+ return createdAt;
}
- /**
- * Used in MyBatis mapping.
- */
- private void setCreatedAtFromMetadata(@Nullable Long createdAt) {
- if (createdAt != null && createdAt > definition.getCreatedAt()) {
- setCreatedAt(createdAt);
+ public RuleDto setCreatedAt(@Nullable Long createdAt) {
+ if ((this.createdAt == 0 && createdAt != null) || (createdAt != null && createdAt < this.createdAt)) {
+ this.createdAt = createdAt;
+ metadata.setCreatedAt(createdAt);
}
- }
-
- public long getUpdatedAt() {
- return definition.getUpdatedAt();
- }
-
- public RuleDto setUpdatedAt(long updatedAt) {
- definition.setUpdatedAt(updatedAt);
- metadata.setUpdatedAt(updatedAt);
return this;
}
- /**
- * Used in MyBatis mapping.
- */
- private void setUpdatedAtFromDefinition(@Nullable Long updatedAt) {
- if (updatedAt != null && updatedAt > definition.getUpdatedAt()) {
- setUpdatedAt(updatedAt);
- }
+ public long getUpdatedAt() {
+ return updatedAt;
}
- /**
- * Used in MyBatis mapping.
- */
- private void setUpdatedAtFromMetadata(@Nullable Long updatedAt) {
- if (updatedAt != null && updatedAt > definition.getUpdatedAt()) {
- setUpdatedAt(updatedAt);
+ public RuleDto setUpdatedAt(@Nullable Long updatedAt) {
+ if (updatedAt != null && updatedAt > this.updatedAt) {
+ this.updatedAt = updatedAt;
+ metadata.setUpdatedAt(updatedAt);
}
+ return this;
}
@CheckForNull
return this;
}
+
+ @CheckForNull
+ public String getDefRemediationFunction() {
+ return defRemediationFunction;
+ }
+
+ public RuleDto setDefRemediationFunction(@Nullable String defaultRemediationFunction) {
+ this.defRemediationFunction = defaultRemediationFunction;
+ return this;
+ }
+
+ @CheckForNull
+ public String getDefRemediationGapMultiplier() {
+ return defRemediationGapMultiplier;
+ }
+
+ public RuleDto setDefRemediationGapMultiplier(@Nullable String defaultRemediationGapMultiplier) {
+ this.defRemediationGapMultiplier = defaultRemediationGapMultiplier;
+ return this;
+ }
+
+ @CheckForNull
+ public String getDefRemediationBaseEffort() {
+ return defRemediationBaseEffort;
+ }
+
+ public RuleDto setDefRemediationBaseEffort(@Nullable String defaultRemediationBaseEffort) {
+ this.defRemediationBaseEffort = defaultRemediationBaseEffort;
+ return this;
+ }
+
+ @CheckForNull
+ public String getGapDescription() {
+ return gapDescription;
+ }
+
+ public RuleDto setGapDescription(@Nullable String s) {
+ this.gapDescription = s;
+ return this;
+ }
+
+
@CheckForNull
public String getRemediationFunction() {
return metadata.getRemediationFunction();
metadata.setTagsField(s);
}
+
+ public static Set<String> deserializeTagsString(@Nullable String tags) {
+ return deserializeStringSet(tags);
+ }
+
+ public static Set<String> deserializeSecurityStandardsString(@Nullable String securityStandards) {
+ return deserializeStringSet(securityStandards);
+ }
+
+ private static Set<String> deserializeStringSet(@Nullable String str) {
+ if (str == null || str.isEmpty()) {
+ return emptySet();
+ }
+
+ return ImmutableSet.copyOf(SPLITTER.split(str));
+ }
+
public RuleDto setTags(Set<String> tags) {
this.metadata.setTags(tags);
return this;
}
-
+ private static String serializeStringSet(@Nullable Set<String> strings) {
+ return strings == null || strings.isEmpty() ? null : StringUtils.join(strings, ',');
+ }
@Override
public boolean equals(Object obj) {
return true;
}
RuleDto other = (RuleDto) obj;
- return new EqualsBuilder()
- .append(getRepositoryKey(), other.getRepositoryKey())
- .append(getRuleKey(), other.getRuleKey())
- .isEquals();
+ return Objects.equals(this.uuid, other.uuid);
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
- .append(getRepositoryKey())
- .append(getRuleKey())
+ .append(this.uuid)
.toHashCode();
}
- @Override
- public String toString() {
- return "RuleDto{" +
- "definition=" + definition +
- ", metadata=" + metadata +
- '}';
- }
-
- public static RuleDto createFor(RuleKey key) {
- return new RuleDto()
- .setRepositoryKey(key.repository())
- .setRuleKey(key.rule());
- }
-
}
import java.util.List;
import java.util.Set;
import org.apache.ibatis.annotations.Param;
-import org.apache.ibatis.session.ResultHandler;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleQuery;
List<RuleDto> selectAll();
- List<RuleDefinitionDto> selectAllDefinitions();
-
- List<RuleDefinitionDto> selectEnabled();
+ List<RuleDto> selectEnabled();
RuleDto selectByUuid(@Param("uuid") String uuid);
- RuleDefinitionDto selectDefinitionByUuid(String uuid);
-
List<RuleDto> selectByUuids(@Param("uuids") List<String> uuids);
- List<RuleDefinitionDto> selectDefinitionByUuids(@Param("uuids") List<String> uuids);
-
RuleDto selectByKey(@Param("ruleKey") RuleKey ruleKey);
- RuleDefinitionDto selectDefinitionByKey(RuleKey ruleKey);
-
RuleMetadataDto selectMetadataByKey(@Param("ruleKey") RuleKey ruleKey);
- List<RuleMetadataDto> selectMetadataByKeys(@Param("ruleKeys") List<RuleKey> keys);
-
List<RuleDto> selectByKeys(@Param("ruleKeys") List<RuleKey> keys);
- List<RuleDefinitionDto> selectDefinitionByKeys(@Param("ruleKeys") List<RuleKey> keys);
-
- void scrollIndexingRules(ResultHandler<RuleForIndexingDto> handler);
-
- List<RuleForIndexingDto> selectIndexingRulesByUuids(@Param("ruleUuids") List<String> ruleUuids);
-
List<RuleExtensionForIndexingDto> selectIndexingRuleExtensionsByIds(@Param("ruleExtensionIds") List<String> ruleExtensionIds);
List<RuleDto> selectByQuery(@Param("query") RuleQuery ruleQuery);
List<RuleDto> selectByTypeAndLanguages(@Param("types") List<Integer> types, @Param("languages") List<String> languages);
- void insertDefinition(RuleDefinitionDto ruleDefinitionDto);
+ void insertRule(RuleDto ruleDefinitionDto);
void insertRuleDescriptionSection(@Param("ruleUuid") String ruleUuid, @Param("dto") RuleDescriptionSectionDto ruleDescriptionSectionDto);
- void updateDefinition(RuleDefinitionDto ruleDefinitionDto);
+ void updateRule(RuleDto ruleDefinitionDto);
void deleteRuleDescriptionSection(String ruleUuid);
void insertMetadata(RuleMetadataDto ruleMetadataDto);
+ void deleteMetadata(@Param("uuid") String uuid);
+
void updateMetadata(RuleMetadataDto ruleMetadataDto);
List<RuleParamDto> selectParamsByRuleUuids(@Param("ruleUuids") List<String> ruleUuids);
/**
* Name of on ad hoc rule.
- * When {@link RuleDefinitionDto#isAdHoc} is true, this field should always be set
*/
private String adHocName;
/**
* Severity of on ad hoc rule.
- * When {@link RuleDefinitionDto#isAdHoc} is true, this field should always be set
+ * When {@link RuleDto#isAdHoc()} is true, this field should always be set
*/
private String adHocSeverity;
/**
* Type of on ad hoc rule.
- * When {@link RuleDefinitionDto#isAdHoc} is true, this field should always be set
+ * When {@link RuleDto#isAdHoc()} is true, this field should always be set
*/
private Integer adHocType;
", updatedAt=" + updatedAt +
'}';
}
+
+ public boolean isUndefined() {
+ return StringUtils.isEmpty(noteData) && StringUtils.isEmpty(noteUserUuid) && noteCreatedAt == null && noteUpdatedAt == null && StringUtils.isEmpty(remediationFunction) &&
+ StringUtils.isEmpty(remediationGapMultiplier) && StringUtils.isEmpty(remediationBaseEffort) && StringUtils.isEmpty(tags)
+ && StringUtils.isEmpty(adHocName) && StringUtils.isEmpty(adHocDescription) && StringUtils.isEmpty(adHocSeverity) && adHocType == null;
+ }
}
return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString();
}
- public static RuleParamDto createFor(RuleDefinitionDto rule) {
+ public static RuleParamDto createFor(RuleDto rule) {
// Should eventually switch to RuleKey (RuleKey is available before insert)
return new RuleParamDto().setRuleUuid(rule.getUuid());
}
p.value as value
</sql>
- <resultMap id="ruleDefinitionResultMap" type="org.sonar.db.qualityprofile.ExportRuleDto">
+ <resultMap id="exportRuleResultMap" type="org.sonar.db.qualityprofile.ExportRuleDto">
<id property="activeRuleUuid" column="activeRuleUuid"/>
<result property="ruleKey" column="ruleKey"/>
<result property="severity" column="severity"/>
</resultMap>
- <select id="selectByProfileUuid" parameterType="string" resultMap="ruleDefinitionResultMap">
+ <select id="selectByProfileUuid" parameterType="string" resultMap="exportRuleResultMap">
select
<include refid="exportRuleColumns"/>
from active_rules a
<mapper namespace="org.sonar.db.rule.RuleMapper">
- <sql id="selectRuleDescriptionSectionColumns">
- rds.uuid as "rds_uuid",
- rds.kee as "rds_kee",
- rds.content as "rds_content",
- </sql>
-
<sql id="leftOuterJoinRulesDescriptionSections">
left outer join rule_desc_sections rds on
rds.rule_uuid = r.uuid
</sql>
- <sql id="selectDefinitionColumns">
- <include refid="selectRuleDescriptionSectionColumns"/>
+ <sql id="selectJoinedTablesColumns">
+ rds.uuid as "rds_uuid",
+ rds.kee as "rds_kee",
+ rds.content as "rds_content",
r.uuid as "r_uuid",
r.plugin_rule_key as "ruleKey",
r.plugin_name as "repositoryKey",
r.rule_type as "type",
r.plugin_key as "pluginKey",
r.scope,
- </sql>
-
- <sql id="selectRuleTableColumns">
- <include refid="selectDefinitionColumns"/>
- r.created_at as "createdAt",
- r.updated_at as "updatedAt"
- </sql>
-
- <sql id="selectJoinedTablesColumns">
- <include refid="selectDefinitionColumns"/>
- r.created_at as "createdAtFromDefinition",
- r.updated_at as "updatedAtFromDefinition",
rm.note_data as "noteData",
rm.note_user_uuid as "noteUserUuid",
rm.note_created_at as "noteCreatedAt",
rm.ad_hoc_description as "adHocDescription",
rm.ad_hoc_severity as "adHocSeverity",
rm.ad_hoc_type as "adHocType",
- rm.created_at as "createdAtFromMetadata",
- rm.updated_at as "updatedAtFromMetadata"
+ case
+ when rm.created_at is null then r.created_at
+ else case
+ when r.created_at < rm.created_at then r.created_at
+ else rm.created_at
+ end end as "createdAt",
+ case
+ when rm.updated_at is null then r.updated_at
+ else case
+ when r.updated_at < rm.updated_at then rm.updated_at
+ else r.updated_at
+ end end as "updatedAt"
</sql>
<sql id="outerJoinRulesMetadata">
<resultMap id="ruleResultMap" type="org.sonar.db.rule.RuleDto">
<id property="uuid" column="r_uuid"/>
- <result property="createdAtFromDefinition" column="createdAtFromDefinition"/>
- <result property="updatedAtFromDefinition" column="updatedAtFromDefinition"/>
+ <result property="createdAt" column="createdAt"/>
+ <result property="updatedAt" column="updatedAt"/>
<result property="noteData" column="noteData" typeHandler="org.apache.ibatis.type.StringTypeHandler"/>
<result property="noteUserUuid" column="noteUserUuid"/>
<result property="noteCreatedAt" column="noteCreatedAt"/>
<result property="adHocDescription" column="adHocDescription" typeHandler="org.apache.ibatis.type.StringTypeHandler"/>
<result property="adHocSeverity" column="adHocSeverity"/>
<result property="adHocType" column="adHocType"/>
- <result property="createdAtFromMetadata" column="createdAtFromMetadata"/>
- <result property="updatedAtFromMetadata" column="updatedAtFromMetadata"/>
<result property="ruleKey" column="ruleKey"/>
<result property="repositoryKey" column="repositoryKey"/>
<result property="type" column="type"/>
<result property="pluginKey" column="pluginKey"/>
<result property="scope" column="scope"/>
- <result property="createdAt" column="created_at"/>
- <result property="updatedAt" column="updated_at"/>
<collection property="ruleDescriptionSectionDtos" ofType="org.sonar.db.rule.RuleDescriptionSectionDto">
<id property="uuid" column="rds_uuid"/>
</collection>
</resultMap>
- <resultMap id="ruleDefinitionResultMap" type="org.sonar.db.rule.RuleDefinitionDto">
- <id property="uuid" column="r_uuid"/>
- <result property="ruleKey" column="ruleKey"/>
- <result property="repositoryKey" column="repositoryKey"/>
- <result property="descriptionFormat" column="descriptionFormat"/>
- <result property="status" column="status"/>
- <result property="name" column="name"/>
- <result property="configKey" column="configKey"/>
- <result property="severity" column="severity"/>
- <result property="isTemplate" column="isTemplate"/>
- <result property="isExternal" column="isExternal"/>
- <result property="isAdHoc" column="isAdHoc"/>
- <result property="language" column="language"/>
- <result property="templateUuid" column="templateUuid"/>
- <result property="defRemediationFunction" column="defRemediationFunction"/>
- <result property="defRemediationGapMultiplier" column="defRemediationGapMultiplier"/>
- <result property="defRemediationBaseEffort" column="defRemediationBaseEffort"/>
- <result property="gapDescription" column="gapDescription"/>
- <result property="systemTagsField" column="systemTagsField"/>
- <result property="securityStandardsField" column="securityStandardsField"/>
- <result property="type" column="type"/>
- <result property="pluginKey" column="pluginKey"/>
- <result property="scope" column="scope"/>
- <result property="createdAt" column="createdAt"/>
- <result property="updatedAt" column="updatedAt"/>
-
- <collection property="ruleDescriptionSectionDtos" ofType="org.sonar.db.rule.RuleDescriptionSectionDto">
- <id property="uuid" column="rds_uuid"/>
- <result property="key" column="rds_kee"/>
- <result property="content" column="rds_content" typeHandler="org.apache.ibatis.type.StringTypeHandler"/>
- </collection>
-
- </resultMap>
- <select id="selectAllDefinitions" resultMap="ruleDefinitionResultMap">
- select
- <include refid="selectRuleTableColumns"/>
- from
- rules r
- <include refid="leftOuterJoinRulesDescriptionSections"/>
- </select>
- <select id="selectEnabled" resultMap="ruleDefinitionResultMap">
+ <select id="selectEnabled" resultMap="ruleResultMap">
select
- <include refid="selectRuleTableColumns"/>
+ <include refid="selectJoinedTablesColumns"/>
from
rules r
+ <include refid="outerJoinRulesMetadata"/>
<include refid="leftOuterJoinRulesDescriptionSections"/>
where
r.status != 'REMOVED'
r.uuid=#{uuid,jdbcType=VARCHAR}
</select>
- <select id="selectDefinitionByUuid" parameterType="String" resultMap="ruleDefinitionResultMap">
- select
- <include refid="selectRuleTableColumns"/>
- from
- rules r
- <include refid="leftOuterJoinRulesDescriptionSections"/>
- where
- r.uuid=#{uuid,jdbcType=VARCHAR}
- </select>
-
<select id="selectByUuids" parameterType="map" resultMap="ruleResultMap">
select
<include refid="selectJoinedTablesColumns"/>
</foreach>
</select>
- <select id="selectDefinitionByUuids" parameterType="map" resultMap="ruleDefinitionResultMap">
- select
- <include refid="selectRuleTableColumns"/>
- from
- rules r
- <include refid="leftOuterJoinRulesDescriptionSections"/>
- where
- <foreach collection="uuids" index="index" item="uuid" open="" separator=" or " close="">
- r.uuid=#{uuid,jdbcType=VARCHAR}
- </foreach>
- </select>
-
<select id="selectByKey" parameterType="map" resultMap="ruleResultMap">
select
<include refid="selectJoinedTablesColumns"/>
and r.plugin_rule_key=#{ruleKey.rule,jdbcType=VARCHAR}
</select>
- <select id="selectDefinitionByKey" parameterType="map" resultMap="ruleDefinitionResultMap">
- select
- <include refid="selectRuleTableColumns"/>
- from
- rules r
- <include refid="leftOuterJoinRulesDescriptionSections"/>
- where
- r.plugin_name=#{repository,jdbcType=VARCHAR}
- and r.plugin_rule_key=#{rule,jdbcType=VARCHAR}
- </select>
-
<select id="selectIndexingRuleExtensionsByIds" parameterType="map" resultType="org.sonar.db.rule.RuleExtensionForIndexingDto">
<include refid="sqlSelectIndexingRuleExtensions"/>
and
rm.ad_hoc_description as "adHocDescription",
rm.ad_hoc_severity as "adHocSeverity",
rm.ad_hoc_type as "adHocType",
- rm.created_at as "createdAt",
+ rm.created_at as "createdAt",
rm.updated_at as "updatedAt"
from
rules_metadata rm
and r.plugin_rule_key=#{ruleKey.rule,jdbcType=VARCHAR}
</select>
- <select id="selectMetadataByKeys" parameterType="map" resultType="org.sonar.db.rule.RuleMetadataDto">
- select
- rm.rule_uuid as "ruleUuid",
- rm.note_data as "noteData",
- rm.note_user_uuid as "noteUserUuid",
- rm.note_created_at as "noteCreatedAt",
- rm.note_updated_at as "noteUpdatedAt",
- rm.remediation_function as "remediationFunction",
- rm.remediation_gap_mult as "remediationGapMultiplier",
- rm.remediation_base_effort as "remediationBaseEffort",
- rm.tags as "tagsField",
- rm.ad_hoc_name as "adHocName",
- rm.ad_hoc_description as "adHocDescription",
- rm.ad_hoc_severity as "adHocSeverity",
- rm.ad_hoc_type as "adHocType",
- rm.created_at as "createdAt",
- rm.updated_at as "updatedAt"
- from
- rules_metadata rm
- inner join rules r on rm.rule_uuid = r.uuid
- where
- <foreach collection="ruleKeys" index="index" item="ruleKey" open="" separator=" or " close="">
- (r.plugin_name=#{ruleKey.repository,jdbcType=VARCHAR} and r.plugin_rule_key=#{ruleKey.rule,jdbcType=VARCHAR})
- </foreach>
- </select>
-
<select id="selectByKeys" parameterType="map" resultMap="ruleResultMap">
select
<include refid="selectJoinedTablesColumns"/>
</foreach>
</select>
- <select id="selectDefinitionByKeys" parameterType="map" resultMap="ruleDefinitionResultMap">
- select
- <include refid="selectRuleTableColumns"/>
- from
- rules r
- <include refid="leftOuterJoinRulesDescriptionSections"/>
- where
- <foreach collection="ruleKeys" index="index" item="ruleKey" open="" separator=" or " close="">
- (r.plugin_name=#{ruleKey.repository,jdbcType=VARCHAR} and r.plugin_rule_key=#{ruleKey.rule,jdbcType=VARCHAR})
- </foreach>
- </select>
-
<select id="selectByQuery" parameterType="map" resultMap="ruleResultMap">
select
<include refid="selectJoinedTablesColumns"/>
)
</insert>
- <insert id="insertDefinition" parameterType="org.sonar.db.rule.RuleDefinitionDto" useGeneratedKeys="false">
+ <insert id="insertRule" parameterType="org.sonar.db.rule.RuleDto" useGeneratedKeys="false">
insert into rules (
uuid,
plugin_key,
)
</insert>
- <update id="updateDefinition" parameterType="org.sonar.db.rule.RuleDefinitionDto">
+ <update id="updateRule" parameterType="org.sonar.db.rule.RuleDto">
update rules set
plugin_key=#{pluginKey,jdbcType=VARCHAR},
plugin_rule_key=#{ruleKey,jdbcType=VARCHAR},
delete from
rule_desc_sections
where
- rule_uuid=#{uuid,jdbcType=VARCHAR}
+ rule_uuid=#{ruleUuid,jdbcType=VARCHAR}
</delete>
<select id="countMetadata" parameterType="org.sonar.db.rule.RuleMetadataDto" resultType="int">
rule_uuid=#{ruleUuid,jdbcType=VARCHAR}
</update>
+ <delete id="deleteMetadata" parameterType="String">
+ delete from
+ rules_metadata
+ where
+ rule_uuid=#{uuid,jdbcType=INTEGER}
+ </delete>
+
<delete id="deleteParams" parameterType="String">
delete from
active_rule_parameters
import org.sonar.db.issue.IssueDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.source.FileSourceDto;
import static com.google.common.collect.ImmutableSet.of;
ComponentDto branch2 = db.components().insertProjectBranch(project, ComponentTesting.newBranchDto(project.getUuid(), BRANCH).setKey("branch2"));
ComponentDto fileBranch2 = db.components().insertComponent(ComponentTesting.newFileDto(branch2));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.issues().insert(new IssueDto().setKee("i1").setComponent(fileBranch1).setProject(branch1).setRule(rule).setStatus(STATUS_CONFIRMED));
db.issues().insert(new IssueDto().setKee("i2").setComponent(fileBranch2).setProject(branch2).setRule(rule).setStatus(STATUS_CLOSED));
db.issues().insert(new IssueDto().setKee("i3").setComponent(fileBranch2).setProject(branch2).setRule(rule).setStatus(STATUS_OPEN));
final ProjectDto project = db.components().insertPrivateProjectDto(b -> b.setName("foo"));
ComponentDto branch1 = db.components().insertProjectBranch(project, ComponentTesting.newBranchDto(project.getUuid(), BRANCH).setKey("branch1"));
ComponentDto fileBranch1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.issues().insert(new IssueDto().setKee("i").setComponent(fileBranch1).setProject(branch1).setRule(rule).setStatus(STATUS_CLOSED));
List<KeyWithUuidDto> result = underTest.selectComponentsFromBranchesThatHaveOpenIssues(db.getSession(), singleton(branch1.uuid()));
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ComponentUpdateDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
@Test
public void scrollNonClosedByComponentUuid() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto openIssue1OnFile = db.issues().insert(rule, project, file, i -> i.setStatus("OPEN").setResolution(null).setType(randomRuleTypeExceptHotspot()));
IssueDto securityHotspot = db.issues().insert(rule, project, file, i -> i.setType(RuleType.SECURITY_HOTSPOT));
- RuleDefinitionDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
+ RuleDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
IssueDto issueFromExteralruleOnFile = db.issues().insert(external, project, file, i -> i.setKee("ON_FILE_FROM_EXTERNAL").setType(randomRuleTypeExceptHotspot()));
assertThat(underTest.selectNonClosedByComponentUuidExcludingExternalsAndSecurityHotspots(db.getSession(), file.uuid()))
@Test
public void scrollNonClosedByModuleOrProject() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto anotherProject = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
IssueDto securityHotspot = db.issues().insert(rule, project, file, i -> i.setType(RuleType.SECURITY_HOTSPOT));
- RuleDefinitionDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
+ RuleDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
IssueDto issueFromExteralruleOnFile = db.issues().insert(external, project, file, i -> i.setKee("ON_FILE_FROM_EXTERNAL").setType(randomRuleTypeExceptHotspot()));
assertThat(underTest.selectNonClosedByModuleOrProjectExcludingExternalsAndSecurityHotspots(db.getSession(), project))
@Test
public void selectOpenByComponentUuid() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto projectBranch = db.components().insertProjectBranch(project,
b -> b.setKey("feature/foo")
@Test
public void selectOpenByComponentUuid_should_correctly_map_required_fields() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto projectBranch = db.components().insertProjectBranch(project,
b -> b.setKey("feature/foo")
public void selectGroupsOfComponentTreeOnLeak_on_file() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto fpBug = db.issues().insert(rule, project, file,
i -> i.setStatus("RESOLVED").setResolution("FALSE-POSITIVE").setSeverity("MAJOR").setType(RuleType.BUG).setIssueCreationTime(1_500L));
IssueDto criticalBug1 = db.issues().insert(rule, project, file,
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public void set_rule() {
IssueDto dto = new IssueDto()
.setKee("100")
- .setRule(new RuleDefinitionDto().setUuid("uuid-1").setRuleKey("AvoidCycle").setRepositoryKey("squid").setIsExternal(true))
+ .setRule(new RuleDto().setUuid("uuid-1").setRuleKey("AvoidCycle").setRepositoryKey("squid").setIsExternal(true))
.setLanguage("xoo");
assertThat(dto.getRuleUuid()).isEqualTo("uuid-1");
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
ComponentDto component = randomComponent();
IssueDto issueWithRule = insertNewClosedIssue(component, ruleType);
IssueChangeDto issueChange = insertToClosedDiff(issueWithRule);
- IssueDto issueWithoutRule = insertNewClosedIssue(component, new RuleDefinitionDto().setType(ruleType).setUuid("uuid-50"));
+ IssueDto issueWithoutRule = insertNewClosedIssue(component, new RuleDto().setType(ruleType).setUuid("uuid-50"));
insertToClosedDiff(issueWithoutRule);
RecorderResultHandler resultHandler = new RecorderResultHandler();
public void scrollClosedByComponentUuid_returns_closed_issues_which_close_date_is_greater_or_equal_to_requested() {
RuleType ruleType = randomSupportedRuleType();
ComponentDto component = randomComponent();
- RuleDefinitionDto rule1 = dbTester.rules().insert(t -> t.setType(ruleType));
+ RuleDto rule1 = dbTester.rules().insert(t -> t.setType(ruleType));
IssueDto[] issues = new IssueDto[] {
insertNewClosedIssue(component, rule1, 1_999_999L),
insertNewClosedIssue(component, rule1, 3_999_999L),
@SafeVarargs
private final IssueDto insertNewClosedIssue(ComponentDto component, RuleType ruleType, Consumer<IssueDto>... consumers) {
- RuleDefinitionDto rule = dbTester.rules().insert(t -> t.setType(ruleType));
+ RuleDto rule = dbTester.rules().insert(t -> t.setType(ruleType));
return insertNewClosedIssue(component, rule, system2.now(), consumers);
}
@SafeVarargs
- private final IssueDto insertNewClosedIssue(ComponentDto component, RuleDefinitionDto rule, Consumer<IssueDto>... consumers) {
+ private final IssueDto insertNewClosedIssue(ComponentDto component, RuleDto rule, Consumer<IssueDto>... consumers) {
return insertNewClosedIssue(component, rule, system2.now(), consumers);
}
@SafeVarargs
- private final IssueDto insertNewClosedIssue(ComponentDto component, RuleDefinitionDto rule, long issueCloseTime, Consumer<IssueDto>... consumers) {
+ private final IssueDto insertNewClosedIssue(ComponentDto component, RuleDto rule, long issueCloseTime, Consumer<IssueDto>... consumers) {
IssueDto res = new IssueDto()
.setKee(UuidFactoryFast.getInstance().create())
.setRuleUuid(rule.getUuid())
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.portfolio.PortfolioProjectDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
@Test
@UseDataProvider("projectsAndViews")
public void deleteIssues_deletes_all_issues_of_specified_root_component(ComponentDto projectOrView) {
- RuleDefinitionDto rule1 = dbTester.rules().insert();
- RuleDefinitionDto rule2 = dbTester.rules().insert();
+ RuleDto rule1 = dbTester.rules().insert();
+ RuleDto rule2 = dbTester.rules().insert();
dbTester.components().insertComponent(projectOrView);
ComponentDto file = dbTester.components().insertComponent(newFileDto(projectOrView));
ComponentDto otherProject = dbTester.components().insertPrivateProject();
@Test
@UseDataProvider("projectsAndViews")
public void deleteIssues_deletes_issue_changes(ComponentDto projectOrView) {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
dbTester.components().insertComponent(projectOrView);
ComponentDto file = dbTester.components().insertComponent(newFileDto(projectOrView));
int count = 5;
@Test
@UseDataProvider("projectsAndViews")
public void deleteIssues_deletes_new_code_reference_issues(ComponentDto projectOrView) {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
dbTester.components().insertComponent(projectOrView);
ComponentDto file = dbTester.components().insertComponent(newFileDto(projectOrView));
List<String> issueKeys = new ArrayList<>();
import org.sonar.db.portfolio.PortfolioProjectDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.source.FileSourceDto;
import org.sonar.db.user.UserDismissedMessageDto;
import org.sonar.db.user.UserDto;
@Test
public void purge_inactive_branches() {
when(system2.now()).thenReturn(new Date().getTime());
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto branch1 = db.components().insertProjectBranch(project);
ComponentDto branch2 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
@Test
public void purge_inactive_pull_request() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto nonMainBranch = db.components().insertProjectBranch(project);
db.components().insertSnapshot(nonMainBranch);
@Test
public void purge_inactive_branches_when_analyzing_non_main_branch() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto nonMainBranch = db.components().insertProjectBranch(project);
db.components().insertSnapshot(nonMainBranch);
@Test
public void close_issues_clean_index_and_file_sources_of_disabled_components_specified_by_uuid_in_configuration() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
db.components().insertSnapshot(project);
db.components().insertSnapshot(project);
@Test
public void delete_project_and_associated_data() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto directory = db.components().insertComponent(newDirectory(module, "a/b"));
MetricDto metric = db.measures().insertMetric();
ComponentDto project = db.components().insertPrivateProject();
BranchDto projectBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.uuid()).get();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto app = db.components().insertPrivateApplication();
ComponentDto appBranch = db.components().insertProjectBranch(app);
MetricDto metric = db.measures().insertMetric();
ComponentDto project = db.components().insertPrivateProject();
BranchDto projectBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), project.uuid()).get();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto app = db.components().insertPrivateApplication();
ComponentDto appBranch = db.components().insertProjectBranch(app);
}
private ComponentDto insertProjectWithBranchAndRelatedData() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto module = db.components().insertComponent(newModuleDto(branch));
@Test
public void should_delete_old_closed_issues() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto enabledFileWithoutIssues = db.components().insertComponent(newFileDto(project).setEnabled(true));
ComponentDto disabledFileWithoutIssues = db.components().insertComponent(newFileDto(project).setEnabled(false));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto closed1 = db.issues().insert(rule, project, enabledFileWithIssues, issue -> {
issue.setStatus("CLOSED");
issue.setResolution(Issue.RESOLUTION_FIXED);
.map(t -> (String) t.get("UUID"));
}
- private void addComponentsSnapshotsAndIssuesToBranch(ComponentDto branch, RuleDefinitionDto rule, int branchAge) {
+ private void addComponentsSnapshotsAndIssuesToBranch(ComponentDto branch, RuleDto rule, int branchAge) {
db.components().insertSnapshot(branch, dto -> dto.setCreatedAt(DateUtils.addDays(new Date(), -branchAge).getTime()));
ComponentDto module = db.components().insertComponent(newModuleDto(branch));
ComponentDto subModule = db.components().insertComponent(newModuleDto(module));
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import static com.google.common.collect.Lists.newArrayList;
private QProfileDto profile1;
private QProfileDto profile2;
- private RuleDefinitionDto rule1;
- private RuleDefinitionDto rule2;
- private RuleDefinitionDto rule3;
- private RuleDefinitionDto removedRule;
+ private RuleDto rule1;
+ private RuleDto rule2;
+ private RuleDto rule3;
+ private RuleDto removedRule;
private RuleParamDto rule1Param1;
private RuleParamDto rule1Param2;
private RuleParamDto rule2Param1;
@Test
public void selectByTypeAndProfileUuids() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
+ RuleDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
ActiveRuleDto activeRule1 = createFor(profile1, rule1).setSeverity(BLOCKER);
underTest.insert(dbSession, activeRule1);
@Test
public void selectByTypeAndProfileUuids_ignores_rules_in_other_profiles() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
+ RuleDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
ActiveRuleDto activeRule1 = createFor(profile2, rule1).setSeverity(BLOCKER);
underTest.insert(dbSession, activeRule1);
@Test
public void selectByTypeAndProfileUuids_ignores_rules_with_another_rule_type() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
+ RuleDto rule1 = db.rules().insert(r -> r.setType(RuleType.VULNERABILITY.getDbConstant()));
ActiveRuleDto activeRule1 = createFor(profile1, rule1).setSeverity(BLOCKER);
underTest.insert(dbSession, activeRule1);
assertThat(db.countRowsOfTable(dbSession, "active_rules")).isOne();
}
- private static ActiveRuleDto newRow(QProfileDto profile, RuleDefinitionDto rule) {
+ private static ActiveRuleDto newRow(QProfileDto profile, RuleDto rule) {
return createFor(profile, rule).setSeverity(BLOCKER);
}
@Test
public void countActiveRulesByQuery_filter_by_rule_status() {
- RuleDefinitionDto betaRule = db.rules().insert(r -> r.setStatus(BETA));
+ RuleDto betaRule = db.rules().insert(r -> r.setStatus(BETA));
db.qualityProfiles().activateRule(profile1, rule1);
db.qualityProfiles().activateRule(profile1, rule2);
db.qualityProfiles().activateRule(profile1, betaRule);
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static com.google.common.collect.ImmutableList.of;
import static com.google.common.collect.Lists.newArrayList;
// a built-in quality profile with active rules
QProfileDto builtInQPWithActiveRules = db.qualityProfiles().insert(qp -> qp.setIsBuiltIn(true));
- RuleDefinitionDto ruleDefinitionDto = db.rules().insert();
+ RuleDto ruleDefinitionDto = db.rules().insert();
db.qualityProfiles().activateRule(builtInQPWithActiveRules, ruleDefinitionDto);
dbSession.commit();
// a built-in quality profile with active rules
QProfileDto builtInQPWithActiveRules = db.qualityProfiles().insert(qp -> qp.setIsBuiltIn(true).setLanguage("java"));
- RuleDefinitionDto ruleDefinitionDto = db.rules().insert();
+ RuleDto ruleDefinitionDto = db.rules().insert();
db.qualityProfiles().activateRule(builtInQPWithActiveRules, ruleDefinitionDto);
dbSession.commit();
import org.sonar.api.rules.RuleType;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.rule.RuleParamDto;
@Test
public void selectRulesByProfile_ready_rules_only() {
String language = "java";
- RuleDefinitionDto rule1 = createRule(language);
- RuleDefinitionDto rule2 = createRule(language);
- RuleDefinitionDto rule3 = createRule(language);
+ RuleDto rule1 = createRule(language);
+ RuleDto rule2 = createRule(language);
+ RuleDto rule3 = createRule(language);
createRule(language, RuleStatus.REMOVED);
QProfileDto profile = createProfile(language);
@Test
public void selectRulesByProfile_verify_columns() {
String language = "java";
- RuleDefinitionDto ruleTemplate = createRule(language);
- RuleDefinitionDto customRule = createRule(language, RuleStatus.READY, ruleTemplate.getUuid());
- var customRuleContent = customRule.getDefaultRuleDescriptionSectionDto().getContent();
+ RuleDto ruleTemplate = createRule(language);
+ RuleDto customRule = createRule(language, RuleStatus.READY, ruleTemplate.getUuid());
+ var customRuleContent = customRule.getDefaultRuleDescriptionSection().getContent();
RuleMetadataDto customRuleMetadata = createRuleMetadata(new RuleMetadataDto()
.setRuleUuid(customRule.getUuid())
.setNoteData("Extended description")
.setTags(Sets.newHashSet("tag1", "tag2", "tag3")));
- RuleDefinitionDto rule = createRule(language, RuleStatus.READY, null);
- var ruleContent = rule.getDefaultRuleDescriptionSectionDto().getContent();
+ RuleDto rule = createRule(language, RuleStatus.READY, null);
+ var ruleContent = rule.getDefaultRuleDescriptionSection().getContent();
RuleMetadataDto ruleMetadata = createRuleMetadata(new RuleMetadataDto()
.setRuleUuid(rule.getUuid()));
QProfileDto profile = createProfile(language);
public void selectRulesByProfile_verify_rows_over_1000() {
String language = "java";
int numberOfParamsToCreate = 1005;
- RuleDefinitionDto rule = createRule(language);
+ RuleDto rule = createRule(language);
List<RuleParamDto> ruleParams = addParamsToRule(rule, numberOfParamsToCreate);
QProfileDto profile = createProfile(language);
@Test
public void selectRulesByProfile_params_assigned_correctly() {
String language = "java";
- RuleDefinitionDto firstRule = createRule(language);
+ RuleDto firstRule = createRule(language);
List<RuleParamDto> ruleParamsOfFirstRule = addParamsToRule(firstRule, 2);
- RuleDefinitionDto secondRule = createRule(language);
+ RuleDto secondRule = createRule(language);
List<RuleParamDto> ruleParamsOfSecondRule = addParamsToRule(secondRule, 3);
String otherLanguage = "js";
- RuleDefinitionDto thirdRule = createRule(otherLanguage);
+ RuleDto thirdRule = createRule(otherLanguage);
List<RuleParamDto> ruleParamsOfThirdRule = addParamsToRule(thirdRule, 4);
QProfileDto profile = createProfile(language);
return found.get();
}
- private List<RuleParamDto> addParamsToRule(RuleDefinitionDto firstRule, int numberOfParams) {
+ private List<RuleParamDto> addParamsToRule(RuleDto firstRule, int numberOfParams) {
return IntStream.range(0, numberOfParams)
.mapToObj(value -> db.rules().insertRuleParam(firstRule,
ruleParamDto -> ruleParamDto.setName("name_" + firstRule.getUuid() + "_" + value)))
.collect(Collectors.toList());
}
- private RuleDefinitionDto createRule(String language) {
+ private RuleDto createRule(String language) {
return createRule(language, RuleStatus.READY);
}
- private RuleDefinitionDto createRule(String language, RuleStatus status) {
+ private RuleDto createRule(String language, RuleStatus status) {
return createRule(language, status, null);
}
- private RuleDefinitionDto createRule(String language, RuleStatus status, @Nullable String templateUuid) {
+ private RuleDto createRule(String language, RuleStatus status, @Nullable String templateUuid) {
return db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setRepositoryKey("repoKey").setLanguage(language).setStatus(status)
.setTemplateUuid(templateUuid));
}
return db.qualityProfiles().insert(p -> p.setLanguage(lanugage));
}
- private List<ActiveRuleDto> activate(QProfileDto profile, RuleDefinitionDto... rules) {
+ private List<ActiveRuleDto> activate(QProfileDto profile, RuleDto... rules) {
return Stream.of(rules)
.map(ruleDefinitionDto -> db.qualityProfiles().activateRule(profile, ruleDefinitionDto))
.collect(Collectors.toList());
}
- private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule, Collection<RuleParamDto> params) {
+ private ActiveRuleDto activate(QProfileDto profile, RuleDto rule, Collection<RuleParamDto> params) {
ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile, rule);
params.forEach(ruleParamDto -> {
@Test
public void selectByKey() {
- RuleDefinitionDto ruleDefinition = db.rules().insert();
- RuleMetadataDto metadata = newRuleMetadata(ruleDefinition);
- db.rules().insertRule(ruleDefinition, metadata);
+ RuleDto ruleDto = db.rules().insert();
+ RuleMetadataDto metadata = newRuleMetadata(ruleDto);
+ db.rules().insertRule(ruleDto, metadata);
assertThat(underTest.selectByKey(db.getSession(), RuleKey.of("foo", "bar")))
.isEmpty();
- RuleDto rule = underTest.selectByKey(db.getSession(), ruleDefinition.getKey()).get();
- assertEquals(rule.getDefinition(), ruleDefinition);
+ RuleDto rule = underTest.selectByKey(db.getSession(), ruleDto.getKey()).get();
+ assertEquals(rule, ruleDto);
verifyMetadata(rule.getMetadata(), metadata);
}
@Test
public void selectByKey_return_rule() {
- RuleDefinitionDto ruleDefinition = db.rules().insert();
+ RuleDto ruleDto = db.rules().insert();
- assertThat(underTest.selectByKey(db.getSession(), ruleDefinition.getKey())).isNotEmpty();
+ assertThat(underTest.selectByKey(db.getSession(), ruleDto.getKey())).isNotEmpty();
}
@Test
public void selectByKey_returns_metadata() {
- RuleDefinitionDto ruleDefinition = db.rules().insert();
- RuleMetadataDto ruleMetadata = newRuleMetadata(ruleDefinition);
- db.rules().insertRule(ruleDefinition, ruleMetadata);
+ RuleDto ruleDto = db.rules().insert();
+ RuleMetadataDto ruleMetadata = newRuleMetadata(ruleDto);
+ db.rules().insertRule(ruleDto, ruleMetadata);
- RuleDto rule = underTest.selectByKey(db.getSession(), ruleDefinition.getKey()).get();
+ RuleDto rule = underTest.selectByKey(db.getSession(), ruleDto.getKey()).get();
verifyMetadata(rule.getMetadata(), ruleMetadata);
}
@Test
public void selectDefinitionByKey() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
- assertThat(underTest.selectDefinitionByKey(db.getSession(), RuleKey.of("NOT", "FOUND"))).isEmpty();
+ assertThat(underTest.selectByKey(db.getSession(), RuleKey.of("NOT", "FOUND"))).isEmpty();
- Optional<RuleDefinitionDto> reloaded = underTest.selectDefinitionByKey(db.getSession(), rule.getKey());
+ Optional<RuleDto> reloaded = underTest.selectByKey(db.getSession(), rule.getKey());
assertThat(reloaded).isPresent();
}
@Test
- public void selectMetadataByKeys() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ public void selectMetadataByKey() {
+ RuleDto rule1 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule1);
- assertThat(underTest.selectMetadataByKeys(db.getSession(), Collections.emptyList())).isEmpty();
- assertThat(underTest.selectMetadataByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
+ assertThat(underTest.selectByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
- List<RuleMetadataDto> rulesMetadata = underTest.selectMetadataByKeys(db.getSession(), asList(rule1.getKey(),
- RuleKey.of("java", "OTHER")));
- assertThat(rulesMetadata).hasSize(1);
- assertThat(rulesMetadata.get(0).getRuleUuid()).isEqualTo(rule1.getUuid());
+ Optional<RuleMetadataDto> rulesMetadata = underTest.selectMetadataByKey(db.getSession(), rule1.getKey());
+ assertThat(rulesMetadata).isPresent();
+ assertThat(rulesMetadata.get().getRuleUuid()).isEqualTo(rule1.getUuid());
}
@Test
public void selectByUuid() {
- RuleDefinitionDto ruleDefinition = db.rules().insert();
- RuleMetadataDto metadata = newRuleMetadata(ruleDefinition);
- RuleDto expected = db.rules().insertRule(ruleDefinition, metadata);
+ RuleDto ruleDto = db.rules().insert();
+ RuleMetadataDto metadata = newRuleMetadata(ruleDto);
+ RuleDto expected = db.rules().insertRule(ruleDto, metadata);
- assertThat(underTest.selectByUuid(expected.getUuid() + 500, db.getSession()))
- .isEmpty();
+ assertThat(underTest.selectByUuid(expected.getUuid() + 500, db.getSession())).isEmpty();
RuleDto rule = underTest.selectByUuid(expected.getUuid(), db.getSession()).get();
- assertEquals(rule.getDefinition(), ruleDefinition);
+ assertEquals(rule, ruleDto);
verifyMetadata(rule.getMetadata(), metadata);
}
@Test
public void selectDefinitionByUuid() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
- assertThat(underTest.selectDefinitionByUuid(UNKNOWN_RULE_UUID, db.getSession())).isEmpty();
- Optional<RuleDefinitionDto> ruleDtoOptional = underTest.selectDefinitionByUuid(rule.getUuid(), db.getSession());
+ assertThat(underTest.selectByUuid(UNKNOWN_RULE_UUID, db.getSession())).isEmpty();
+ Optional<RuleDto> ruleDtoOptional = underTest.selectByUuid(rule.getUuid(), db.getSession());
assertThat(ruleDtoOptional).isPresent();
}
@Test
public void selectByUuids() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule2);
- RuleDefinitionDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
+ RuleDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
db.rules().insertOrUpdateMetadata(removedRule);
assertThat(underTest.selectByUuids(db.getSession(), singletonList(rule1.getUuid()))).hasSize(1);
@Test
public void selectDefinitionByUuids() {
- RuleDefinitionDto rule1 = db.rules().insert();
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
- assertThat(underTest.selectDefinitionByUuids(db.getSession(), singletonList(rule1.getUuid()))).hasSize(1);
- assertThat(underTest.selectDefinitionByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid()))).hasSize(2);
- assertThat(underTest.selectDefinitionByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), UNKNOWN_RULE_UUID))).hasSize(2);
- assertThat(underTest.selectDefinitionByUuids(db.getSession(), singletonList(UNKNOWN_RULE_UUID))).isEmpty();
+ assertThat(underTest.selectByUuids(db.getSession(), singletonList(rule1.getUuid()))).hasSize(1);
+ assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid()))).hasSize(2);
+ assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), UNKNOWN_RULE_UUID))).hasSize(2);
+ assertThat(underTest.selectByUuids(db.getSession(), singletonList(UNKNOWN_RULE_UUID))).isEmpty();
}
@Test
public void selectOrFailByKey() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insert();
RuleDto rule = underTest.selectOrFailByKey(db.getSession(), rule1.getKey());
@Test
public void selectOrFailDefinitionByKey_fails_if_rule_not_found() {
- assertThatThrownBy(() -> underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of("NOT", "FOUND")))
+ assertThatThrownBy(() -> underTest.selectOrFailByKey(db.getSession(), RuleKey.of("NOT", "FOUND")))
.isInstanceOf(RowNotFoundException.class)
.hasMessage("Rule with key 'NOT:FOUND' does not exist");
}
@Test
public void selectByKeys() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule2);
assertThat(underTest.selectByKeys(db.getSession(), Collections.emptyList())).isEmpty();
@Test
public void selectDefinitionByKeys() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
- assertThat(underTest.selectDefinitionByKeys(db.getSession(), Collections.emptyList())).isEmpty();
- assertThat(underTest.selectDefinitionByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
+ assertThat(underTest.selectByKeys(db.getSession(), Collections.emptyList())).isEmpty();
+ assertThat(underTest.selectByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
- List<RuleDefinitionDto> rules = underTest.selectDefinitionByKeys(db.getSession(), asList(rule.getKey(), RuleKey.of("java", "OTHER")));
+ List<RuleDto> rules = underTest.selectByKeys(db.getSession(), asList(rule.getKey(), RuleKey.of("java", "OTHER")));
assertThat(rules).hasSize(1);
assertThat(rules.get(0).getUuid()).isEqualTo(rule.getUuid());
}
@Test
public void selectAll_returns_metadata() {
- RuleDefinitionDto ruleDefinition = db.rules().insert();
- RuleMetadataDto expected = newRuleMetadata(ruleDefinition);
- db.rules().insertRule(ruleDefinition, expected);
+ RuleDto ruleDto = db.rules().insert();
+ RuleMetadataDto expected = newRuleMetadata(ruleDto);
+ db.rules().insertRule(ruleDto, expected);
List<RuleDto> rules = underTest.selectAll(db.getSession());
assertThat(rules).hasSize(1);
verifyMetadata(rules.iterator().next().getMetadata(), expected);
}
- private void assertEquals(RuleDefinitionDto actual, RuleDefinitionDto expected) {
+ private void assertEquals(RuleDto actual, RuleDto expected) {
assertThat(actual.getUuid()).isEqualTo(expected.getUuid());
assertThat(actual.getRepositoryKey()).isEqualTo(expected.getRepositoryKey());
assertThat(actual.getRuleKey()).isEqualTo(expected.getRuleKey());
@Test
public void selectAllDefinitions() {
- RuleDefinitionDto rule1 = db.rules().insert();
- RuleDefinitionDto rule2 = db.rules().insert();
- RuleDefinitionDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
+ RuleDto rule1 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
+ RuleDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
- List<RuleDefinitionDto> ruleDtos = underTest.selectAllDefinitions(db.getSession());
+ List<RuleDto> ruleDtos = underTest.selectAll(db.getSession());
- assertThat(ruleDtos).extracting(RuleDefinitionDto::getUuid).containsOnly(rule1.getUuid(), rule2.getUuid(), removedRule.getUuid());
+ assertThat(ruleDtos).extracting(RuleDto::getUuid).containsOnly(rule1.getUuid(), rule2.getUuid(), removedRule.getUuid());
}
@Test
public void selectEnabled_with_ResultHandler() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.rules().insert(r -> r.setStatus(REMOVED));
- List<RuleDefinitionDto> rules = underTest.selectEnabled(db.getSession());
+ List<RuleDto> rules = underTest.selectEnabled(db.getSession());
assertThat(rules.size()).isOne();
- RuleDefinitionDto ruleDto = rules.get(0);
+ RuleDto ruleDto = rules.get(0);
assertThat(ruleDto.getUuid()).isEqualTo(rule.getUuid());
}
@Test
public void selectByTypeAndLanguages() {
- RuleDefinitionDto rule1 = db.rules().insert(
+ RuleDto rule1 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S001"))
.setConfigKey("S1")
.setType(RuleType.VULNERABILITY)
.setLanguage("java"));
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert(
+ RuleDto rule2 = db.rules().insert(
r -> r.setKey(RuleKey.of("js", "S002"))
.setType(RuleType.SECURITY_HOTSPOT)
.setLanguage("js"));
@Test
public void selectByTypeAndLanguages_return_nothing_when_no_rule_on_languages() {
- RuleDefinitionDto rule1 = db.rules().insert(
+ RuleDto rule1 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S001"))
.setConfigKey("S1")
.setType(RuleType.VULNERABILITY)
.setLanguage("java"));
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert(
+ RuleDto rule2 = db.rules().insert(
r -> r.setKey(RuleKey.of("js", "S002"))
.setType(RuleType.VULNERABILITY)
.setLanguage("js"));
@Test
public void selectByTypeAndLanguages_return_nothing_when_no_rule_with_type() {
- RuleDefinitionDto rule1 = db.rules().insert(
+ RuleDto rule1 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S001"))
.setConfigKey("S1")
.setType(RuleType.VULNERABILITY)
.setLanguage("java"));
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert(
+ RuleDto rule2 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S002"))
.setType(RuleType.SECURITY_HOTSPOT)
.setLanguage("java"));
db.rules().insertOrUpdateMetadata(rule2);
- RuleDefinitionDto rule3 = db.rules().insert(
+ RuleDto rule3 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S003"))
.setType(RuleType.CODE_SMELL)
.setLanguage("java"));
@Test
public void selectByTypeAndLanguages_ignores_external_rules() {
- RuleDefinitionDto rule1 = db.rules().insert(
+ RuleDto rule1 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S001"))
.setConfigKey("S1")
.setType(RuleType.VULNERABILITY)
@Test
public void selectByTypeAndLanguages_ignores_template_rules() {
- RuleDefinitionDto rule1 = db.rules().insert(
+ RuleDto rule1 = db.rules().insert(
r -> r.setKey(RuleKey.of("java", "S001"))
.setConfigKey("S1")
.setType(RuleType.VULNERABILITY)
@Test
public void select_by_query() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setKey(RuleKey.of("java", "S001")).setConfigKey("S1"));
+ RuleDto rule1 = db.rules().insert(r -> r.setKey(RuleKey.of("java", "S001")).setConfigKey("S1"));
db.rules().insertOrUpdateMetadata(rule1);
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setKey(RuleKey.of("java", "S002")));
+ RuleDto rule2 = db.rules().insert(r -> r.setKey(RuleKey.of("java", "S002")));
db.rules().insertOrUpdateMetadata(rule2);
- RuleDefinitionDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
+ RuleDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create())).hasSize(2);
assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create().withKey("S001"))).hasSize(1);
@Test
public void insert() {
RuleDescriptionSectionDto sectionDto = createDefaultRuleDescriptionSection();
- RuleDefinitionDto newRule = new RuleDefinitionDto()
+ RuleDto newRule = new RuleDto()
.setUuid("rule-uuid")
.setRuleKey("NewRuleKey")
.setRepositoryKey("plugin")
underTest.insert(db.getSession(), newRule);
db.getSession().commit();
- RuleDefinitionDto ruleDto = underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
+ RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
assertThat(ruleDto.getUuid()).isNotNull();
assertThat(ruleDto.getName()).isEqualTo("new name");
assertThat(ruleDto.getStatus()).isEqualTo(RuleStatus.DEPRECATED);
@Test
public void update_RuleDefinitionDto() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleDescriptionSectionDto sectionDto = createDefaultRuleDescriptionSection();
- RuleDefinitionDto ruleToUpdate = new RuleDefinitionDto()
+ RuleDto ruleToUpdate = new RuleDto()
.setUuid(rule.getUuid())
.setRuleKey("NewRuleKey")
.setRepositoryKey("plugin")
underTest.update(db.getSession(), ruleToUpdate);
db.getSession().commit();
- RuleDefinitionDto ruleDto = underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
+ RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
assertThat(ruleDto.getName()).isEqualTo("new name");
assertThat(ruleDto.getStatus()).isEqualTo(RuleStatus.DEPRECATED);
assertThat(ruleDto.getRuleKey()).isEqualTo("NewRuleKey");
@Test
public void update_rule_sections_add_new_section() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next();
RuleDescriptionSectionDto newSection = RuleDescriptionSectionDto.builder()
.uuid(randomAlphanumeric(20))
underTest.update(db.getSession(), rule);
db.getSession().commit();
- RuleDefinitionDto ruleDto = underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
+ RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
assertThat(ruleDto.getRuleDescriptionSectionDtos())
.usingRecursiveFieldByFieldElementComparator()
@Test
public void update_rule_sections_replaces_section() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next();
RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder()
.uuid(randomAlphanumeric(20))
underTest.update(db.getSession(), rule);
db.getSession().commit();
- RuleDefinitionDto ruleDto = underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
+ RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
assertThat(ruleDto.getRuleDescriptionSectionDtos())
.usingRecursiveFieldByFieldElementComparator()
@Test
public void update_RuleMetadataDto_inserts_row_in_RULE_METADATA_if_not_exists_yet() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
+
+ rule.setNoteData("My note");
+ rule.setNoteUserUuid("admin");
+ rule.setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime());
+ rule.setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime());
+ rule.setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString());
+ rule.setRemediationGapMultiplier("1h");
+ rule.setRemediationBaseEffort("5min");
+ rule.setTags(newHashSet("tag1", "tag2"));
+ rule.setAdHocName("ad hoc name");
+ rule.setAdHocDescription("ad hoc desc");
+ rule.setAdHocSeverity(Severity.BLOCKER);
+ rule.setAdHocType(RuleType.CODE_SMELL);
+ rule.setCreatedAt(3_500_000_000_000L);
+ rule.setUpdatedAt(4_000_000_000_000L);
- RuleMetadataDto metadataToUpdate = new RuleMetadataDto()
- .setRuleUuid(rule.getUuid())
- .setNoteData("My note")
- .setNoteUserUuid("admin")
- .setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime())
- .setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime())
- .setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString())
- .setRemediationGapMultiplier("1h")
- .setRemediationBaseEffort("5min")
- .setTags(newHashSet("tag1", "tag2"))
- .setAdHocName("ad hoc name")
- .setAdHocDescription("ad hoc desc")
- .setAdHocSeverity(Severity.BLOCKER)
- .setAdHocType(RuleType.CODE_SMELL)
- .setCreatedAt(3_500_000_000_000L)
- .setUpdatedAt(4_000_000_000_000L);
-
- underTest.insertOrUpdate(db.getSession(), metadataToUpdate);
+ underTest.update(db.getSession(), rule);
db.getSession().commit();
RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
assertThat(ruleDto.getAdHocSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(ruleDto.getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
assertThat(ruleDto.getSecurityStandards()).isEmpty();
- assertThat(ruleDto.getCreatedAt()).isEqualTo(3_500_000_000_000L);
+ assertThat(ruleDto.getCreatedAt()).isEqualTo(rule.getCreatedAt());
assertThat(ruleDto.getUpdatedAt()).isEqualTo(4_000_000_000_000L);
// Info from rule definition
assertThat(ruleDto.getDefRemediationFunction()).isEqualTo(rule.getDefRemediationFunction());
@Test
public void update_RuleMetadataDto_updates_row_in_RULE_METADATA_if_already_exists() {
- RuleDefinitionDto rule = db.rules().insert();
- RuleMetadataDto metadataV1 = new RuleMetadataDto()
- .setRuleUuid(rule.getUuid())
- .setCreatedAt(3_500_000_000_000L)
- .setUpdatedAt(4_000_000_000_000L);
- RuleMetadataDto metadataV2 = new RuleMetadataDto()
- .setRuleUuid(rule.getUuid())
- .setNoteData("My note")
- .setNoteUserUuid("admin")
- .setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime())
- .setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime())
- .setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString())
- .setRemediationGapMultiplier("1h")
- .setRemediationBaseEffort("5min")
- .setTags(newHashSet("tag1", "tag2"))
- .setAdHocName("ad hoc name")
- .setAdHocDescription("ad hoc desc")
- .setAdHocSeverity(Severity.BLOCKER)
- .setAdHocType(RuleType.CODE_SMELL)
- .setCreatedAt(6_500_000_000_000L)
- .setUpdatedAt(7_000_000_000_000L);
-
- underTest.insertOrUpdate(db.getSession(), metadataV1);
+ RuleDto rule = db.rules().insert();
+ rule.setAdHocDescription("ad-hoc-desc");
+ rule.setCreatedAt(3_500_000_000_000L);
+ rule.setUpdatedAt(4_000_000_000_000L);
+
+
+ underTest.update(db.getSession(), rule);
db.commit();
assertThat(db.countRowsOfTable("RULES_METADATA")).isOne();
assertThat(ruleDto.getRemediationBaseEffort()).isNull();
assertThat(ruleDto.getTags()).isEmpty();
assertThat(ruleDto.getAdHocName()).isNull();
- assertThat(ruleDto.getAdHocDescription()).isNull();
+ assertThat(ruleDto.getAdHocDescription()).isEqualTo("ad-hoc-desc");
assertThat(ruleDto.getAdHocSeverity()).isNull();
assertThat(ruleDto.getAdHocType()).isNull();
assertThat(ruleDto.getSecurityStandards()).isEmpty();
- assertThat(ruleDto.getCreatedAt()).isEqualTo(3_500_000_000_000L);
+ assertThat(ruleDto.getCreatedAt()).isEqualTo(rule.getCreatedAt());
+ assertThat(ruleDto.getMetadata().getCreatedAt()).isEqualTo(rule.getCreatedAt());
assertThat(ruleDto.getUpdatedAt()).isEqualTo(4_000_000_000_000L);
-
- underTest.insertOrUpdate(db.getSession(), metadataV2);
+ assertThat(ruleDto.getMetadata().getUpdatedAt()).isEqualTo(4_000_000_000_000L);
+
+ rule.setNoteData("My note");
+ rule.setNoteUserUuid("admin");
+ rule.setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime());
+ rule.setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime());
+ rule.setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString());
+ rule.setRemediationGapMultiplier("1h");
+ rule.setRemediationBaseEffort("5min");
+ rule.setTags(newHashSet("tag1", "tag2"));
+ rule.setAdHocName("ad hoc name");
+ rule.setAdHocDescription("ad hoc desc");
+ rule.setAdHocSeverity(Severity.BLOCKER);
+ rule.setAdHocType(RuleType.CODE_SMELL);
+ rule.setCreatedAt(6_500_000_000_000L);
+ rule.setUpdatedAt(7_000_000_000_000L);
+ underTest.update(db.getSession(), rule);
db.commit();
ruleDto = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
assertThat(ruleDto.getAdHocSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(ruleDto.getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
assertThat(ruleDto.getSecurityStandards()).isEmpty();
- assertThat(ruleDto.getCreatedAt()).isEqualTo(3_500_000_000_000L);
+ assertThat(ruleDto.getCreatedAt()).isEqualTo(rule.getCreatedAt());
+ assertThat(ruleDto.getMetadata().getCreatedAt()).isEqualTo(rule.getCreatedAt());
assertThat(ruleDto.getUpdatedAt()).isEqualTo(7_000_000_000_000L);
+ assertThat(ruleDto.getMetadata().getUpdatedAt()).isEqualTo(7_000_000_000_000L);
}
@Test
public void select_all_rule_params() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
RuleParamDto ruleParam1 = db.rules().insertRuleParam(rule1);
RuleParamDto ruleParam12 = db.rules().insertRuleParam(rule1);
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
RuleParamDto ruleParam2 = db.rules().insertRuleParam(rule2);
- RuleDefinitionDto rule3 = db.rules().insert();
+ RuleDto rule3 = db.rules().insert();
RuleParamDto ruleParam3 = db.rules().insertRuleParam(rule3);
List<RuleParamDto> ruleDtos = underTest.selectAllRuleParams(db.getSession());
@Test
public void select_parameters_by_rule_key() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
List<RuleParamDto> ruleDtos = underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey());
@Test
public void select_parameters_by_rule_keys() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insertRuleParam(rule1);
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
db.rules().insertRuleParam(rule2);
assertThat(underTest.selectRuleParamsByRuleKeys(db.getSession(),
@Test
public void insert_parameter() {
- RuleDefinitionDto ruleDefinitionDto = db.rules().insert();
+ RuleDto ruleDefinitionDto = db.rules().insert();
RuleParamDto orig = RuleParamDto.createFor(ruleDefinitionDto)
.setName("max")
@Test
public void should_fail_to_insert_duplicate_parameter() {
- RuleDefinitionDto ruleDefinitionDto = db.rules().insert();
+ RuleDto ruleDefinitionDto = db.rules().insert();
RuleParamDto param = RuleParamDto.createFor(ruleDefinitionDto)
.setName("max")
@Test
public void update_parameter() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
List<RuleParamDto> params = underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey());
@Test
public void delete_parameter() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
assertThat(underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey())).hasSize(1);
.uuid("uuid")
.content("my description")
.build();
- RuleDefinitionDto r1 = db.rules().insert(r -> {
+ RuleDto r1 = db.rules().insert(r -> {
r.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
});
- RuleDefinitionDto r2 = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto r2 = db.rules().insert(r -> r.setIsExternal(true));
underTest.selectIndexingRules(db.getSession(), accumulator);
assertThat(firstRule.getRuleDescriptionSectionsDtos().stream()
.filter(s -> s.getKey().equals(ruleDescriptionSectionDto.getKey()))
.collect(MoreCollectors.onlyElement()))
+ .usingRecursiveComparison()
.isEqualTo(ruleDescriptionSectionDto);
assertThat(firstRule.getDescriptionFormat()).isEqualTo(r1.getDescriptionFormat());
assertThat(firstRule.getSeverity()).isEqualTo(r1.getSeverity());
@Test
public void scrollIndexingRules_maps_rule_definition_fields_for_regular_rule_and_template_rule() {
Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
- RuleDefinitionDto r1 = db.rules().insert();
- RuleMetadataDto r1Metadatas = db.rules().insertOrUpdateMetadata(r1, r -> r.setTagsField("t1,t2"));
- RuleDefinitionDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1.getUuid()));
+ RuleDto r1 = db.rules().insert();
+ r1.setTags(Set.of("t1", "t2"));
+ r1 = db.rules().update(r1);
+
+ String r1Uuid = r1.getUuid();
+ RuleDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1Uuid));
underTest.selectIndexingRules(db.getSession(), accumulator);
RuleForIndexingDto firstRule = findRuleForIndexingWithUuid(accumulator, r1.getUuid());
RuleForIndexingDto secondRule = findRuleForIndexingWithUuid(accumulator, r2.getUuid());
- assertRuleDefinitionFieldsAreEquals(r1, firstRule);
- assertRuleMetadataFieldsAreEquals(r1Metadatas, firstRule);
+ assertRuleDefinitionFieldsAreEquals(r1, r1.getMetadata().getUpdatedAt(), firstRule);
+ assertRuleMetadataFieldsAreEquals(r1.getMetadata(), firstRule);
assertThat(firstRule.getTemplateRuleKey()).isNull();
assertThat(firstRule.getTemplateRepository()).isNull();
- assertRuleDefinitionFieldsAreEquals(r2, secondRule);
+ assertRuleDefinitionFieldsAreEquals(r2, r2.getUpdatedAt(), secondRule);
assertThat(secondRule.getTemplateRuleKey()).isEqualTo(r1.getRuleKey());
assertThat(secondRule.getTemplateRepository()).isEqualTo(r1.getRepositoryKey());
}
@Test
public void scrollIndexingRulesByKeys() {
Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
- RuleDefinitionDto r1 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
db.rules().insert();
underTest.selectIndexingRulesByKeys(db.getSession(), singletonList(r1.getUuid()), accumulator);
@Test
public void scrollIndexingRulesByKeys_maps_rule_definition_fields_for_regular_rule_and_template_rule() {
Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
- RuleDefinitionDto r1 = db.rules().insert();
- RuleDefinitionDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1.getUuid()));
+ RuleDto r1 = db.rules().insert();
+ RuleDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1.getUuid()));
underTest.selectIndexingRulesByKeys(db.getSession(), Arrays.asList(r1.getUuid(), r2.getUuid()), accumulator);
RuleForIndexingDto firstRule = accumulator.list.stream().filter(t -> t.getUuid().equals(r1.getUuid())).findFirst().get();
RuleForIndexingDto secondRule = accumulator.list.stream().filter(t -> t.getUuid().equals(r2.getUuid())).findFirst().get();
- assertRuleDefinitionFieldsAreEquals(r1, firstRule);
+ assertRuleDefinitionFieldsAreEquals(r1, r1.getMetadata().getUpdatedAt(), firstRule);
assertThat(firstRule.getTemplateRuleKey()).isNull();
assertThat(firstRule.getTemplateRepository()).isNull();
- assertRuleDefinitionFieldsAreEquals(r2, secondRule);
+ assertRuleDefinitionFieldsAreEquals(r2, r2.getUpdatedAt(), secondRule);
assertThat(secondRule.getTemplateRuleKey()).isEqualTo(r1.getRuleKey());
assertThat(secondRule.getTemplateRepository()).isEqualTo(r1.getRepositoryKey());
}
- private void assertRuleDefinitionFieldsAreEquals(RuleDefinitionDto r1, RuleForIndexingDto firstRule) {
- assertThat(firstRule.getUuid()).isEqualTo(r1.getUuid());
- assertThat(firstRule.getRuleKey()).isEqualTo(r1.getKey());
- assertThat(firstRule.getRepository()).isEqualTo(r1.getRepositoryKey());
- assertThat(firstRule.getPluginRuleKey()).isEqualTo(r1.getRuleKey());
- assertThat(firstRule.getName()).isEqualTo(r1.getName());
- assertThat(firstRule.getRuleDescriptionSectionsDtos()).isEqualTo(r1.getRuleDescriptionSectionDtos());
- assertThat(firstRule.getDescriptionFormat()).isEqualTo(r1.getDescriptionFormat());
- assertThat(firstRule.getSeverity()).isEqualTo(r1.getSeverity());
- assertThat(firstRule.getSeverityAsString()).isEqualTo(SeverityUtil.getSeverityFromOrdinal(r1.getSeverity()));
- assertThat(firstRule.getStatus()).isEqualTo(r1.getStatus());
- assertThat(firstRule.isTemplate()).isEqualTo(r1.isTemplate());
- assertThat(firstRule.getSystemTags()).isEqualTo(r1.getSystemTags());
- assertThat(firstRule.getSecurityStandards()).isEqualTo(r1.getSecurityStandards());
- assertThat(firstRule.getInternalKey()).isEqualTo(r1.getConfigKey());
- assertThat(firstRule.getLanguage()).isEqualTo(r1.getLanguage());
- assertThat(firstRule.getType()).isEqualTo(r1.getType());
- assertThat(firstRule.getTypeAsRuleType()).isEqualTo(RuleType.valueOf(r1.getType()));
- assertThat(firstRule.getCreatedAt()).isEqualTo(r1.getCreatedAt());
- assertThat(firstRule.getUpdatedAt()).isEqualTo(r1.getUpdatedAt());
+ private void assertRuleDefinitionFieldsAreEquals(RuleDto r1, long updatedAt, RuleForIndexingDto ruleForIndexing) {
+ assertThat(ruleForIndexing.getUuid()).isEqualTo(r1.getUuid());
+ assertThat(ruleForIndexing.getRuleKey()).isEqualTo(r1.getKey());
+ assertThat(ruleForIndexing.getRepository()).isEqualTo(r1.getRepositoryKey());
+ assertThat(ruleForIndexing.getPluginRuleKey()).isEqualTo(r1.getRuleKey());
+ assertThat(ruleForIndexing.getName()).isEqualTo(r1.getName());
+ assertThat(ruleForIndexing.getRuleDescriptionSectionsDtos())
+ .usingRecursiveComparison()
+ .isEqualTo(r1.getRuleDescriptionSectionDtos());
+ assertThat(ruleForIndexing.getDescriptionFormat()).isEqualTo(r1.getDescriptionFormat());
+ assertThat(ruleForIndexing.getSeverity()).isEqualTo(r1.getSeverity());
+ assertThat(ruleForIndexing.getSeverityAsString()).isEqualTo(SeverityUtil.getSeverityFromOrdinal(r1.getSeverity()));
+ assertThat(ruleForIndexing.getStatus()).isEqualTo(r1.getStatus());
+ assertThat(ruleForIndexing.isTemplate()).isEqualTo(r1.isTemplate());
+ assertThat(ruleForIndexing.getSystemTags()).isEqualTo(r1.getSystemTags());
+ assertThat(ruleForIndexing.getSecurityStandards()).isEqualTo(r1.getSecurityStandards());
+ assertThat(ruleForIndexing.getInternalKey()).isEqualTo(r1.getConfigKey());
+ assertThat(ruleForIndexing.getLanguage()).isEqualTo(r1.getLanguage());
+ assertThat(ruleForIndexing.getType()).isEqualTo(r1.getType());
+ assertThat(ruleForIndexing.getTypeAsRuleType()).isEqualTo(RuleType.valueOf(r1.getType()));
+ assertThat(ruleForIndexing.getCreatedAt()).isEqualTo(r1.getCreatedAt());
+ assertThat(ruleForIndexing.getUpdatedAt()).isEqualTo(updatedAt);
}
private static void assertRuleMetadataFieldsAreEquals(RuleMetadataDto r1Metadatas, RuleForIndexingDto firstRule) {
@Test
public void scrollIndexingRuleExtensionsByIds() {
Accumulator<RuleExtensionForIndexingDto> accumulator = new Accumulator<>();
- RuleDefinitionDto r1 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
RuleMetadataDto r1Extension = db.rules().insertOrUpdateMetadata(r1, r -> r.setTagsField("t1,t2"));
- RuleDefinitionDto r2 = db.rules().insert();
+ RuleDto r2 = db.rules().insert();
db.rules().insertOrUpdateMetadata(r2, r -> r.setTagsField("t1,t3"));
underTest.scrollIndexingRuleExtensionsByIds(db.getSession(), singletonList(r1.getUuid()), accumulator);
@Test
public void selectAllDeprecatedRuleKeys() {
- RuleDefinitionDto r1 = db.rules().insert();
- RuleDefinitionDto r2 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
+ RuleDto r2 = db.rules().insert();
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r2.getUuid()));
@Test
public void selectDeprecatedRuleKeysByRuleUuids() {
- RuleDefinitionDto r1 = db.rules().insert();
- RuleDefinitionDto r2 = db.rules().insert();
- RuleDefinitionDto r3 = db.rules().insert();
- RuleDefinitionDto r4 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
+ RuleDto r2 = db.rules().insert();
+ RuleDto r3 = db.rules().insert();
+ RuleDto r4 = db.rules().insert();
DeprecatedRuleKeyDto drk1 = db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
DeprecatedRuleKeyDto drk2 = db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
@Test
public void insertDeprecatedRuleKey() {
- RuleDefinitionDto r1 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
DeprecatedRuleKeyDto deprecatedRuleKeyDto = db.rules().insertDeprecatedKey(d -> d.setRuleUuid(r1.getUuid()));
db.getSession().commit();
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2022 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.db.rule;
-
-import org.junit.Test;
-import org.sonar.core.util.Uuids;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.db.rule.RuleTesting.newRule;
-
-public class RuleDefinitionDtoTest {
-
- @Test
- public void equals_is_based_on_uuid() {
- String uuid = Uuids.createFast();
- RuleDefinitionDto dto = newRule().setUuid(uuid);
-
- assertThat(dto)
- .isEqualTo(dto)
- .isEqualTo(newRule().setUuid(uuid))
- .isEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid))
- .isNotNull()
- .isNotEqualTo(new Object())
- .isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()))
- .isNotEqualTo(newRule().setUuid(Uuids.createFast()));
- }
-
- @Test
- public void hashcode_is_based_on_uuid() {
- String uuid = Uuids.createFast();
- RuleDefinitionDto dto = newRule().setUuid(uuid);
-
- assertThat(dto)
- .hasSameHashCodeAs(dto)
- .hasSameHashCodeAs(newRule().setUuid(uuid))
- .hasSameHashCodeAs(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid));
- assertThat(dto.hashCode())
- .isNotEqualTo(new Object().hashCode())
- .isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()).hashCode())
- .isNotEqualTo(newRule().setUuid(Uuids.createFast()).hashCode());
- }
-}
.uuid("uuid")
.content("desc").build();
- @Test
- public void testEquals() {
-
- Assertions.assertThat(RuleDescriptionSectionDto.builder()
- .key("key")
- .uuid("uuid")
- .content("desc")
- .build())
- .isEqualTo(SECTION);
-
- Assertions.assertThat(SECTION).isEqualTo(SECTION);
- }
-
@Test
public void testToString() {
Assertions.assertThat(SECTION).hasToString("RuleDescriptionSectionDto[uuid='uuid', key='key', content='desc']");
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
+import org.sonar.core.util.Uuids;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.sonar.db.rule.RuleTesting.newRule;
public class RuleDtoTest {
RuleDto dto = new RuleDto().setTags(Collections.emptySet());
assertThat(dto.getTags()).isEmpty();
}
+
+ @Test
+ public void equals_is_based_on_uuid() {
+ String uuid = Uuids.createFast();
+ RuleDto dto = newRule().setUuid(uuid);
+
+ assertThat(dto)
+ .isEqualTo(dto)
+ .isEqualTo(newRule().setUuid(uuid))
+ .isEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid))
+ .isNotNull()
+ .isNotEqualTo(new Object())
+ .isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()))
+ .isNotEqualTo(newRule().setUuid(Uuids.createFast()));
+ }
+
+ @Test
+ public void hashcode_is_based_on_uuid() {
+ String uuid = Uuids.createFast();
+ RuleDto dto = newRule().setUuid(uuid);
+
+ assertThat(dto)
+ .hasSameHashCodeAs(dto)
+ .hasSameHashCodeAs(newRule().setUuid(uuid))
+ .hasSameHashCodeAs(newRule().setRuleKey(dto.getRuleKey()).setUuid(uuid));
+ assertThat(dto.hashCode())
+ .isNotEqualTo(new Object().hashCode())
+ .isNotEqualTo(newRule().setRuleKey(dto.getRuleKey()).setUuid(Uuids.createFast()).hashCode())
+ .isNotEqualTo(newRule().setUuid(Uuids.createFast()).hashCode());
+ }
}
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkArgument;
* Inserts an issue or a security hotspot.
*/
@SafeVarargs
- public final IssueDto insert(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+ public final IssueDto insert(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
IssueDto issue = newIssue(rule, project, file);
stream(populators).forEach(p -> p.accept(issue));
return insert(issue);
*/
@SafeVarargs
public final IssueDto insert(Consumer<IssueDto>... populators) {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(rule, project, file);
* @throws AssertionError if rule is a Security Hotspot
*/
@SafeVarargs
- public final IssueDto insertIssue(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+ public final IssueDto insertIssue(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
assertThat(rule.getType())
.describedAs("rule must not be a Security Hotspot type")
.isNotEqualTo(SECURITY_HOTSPOT.getDbConstant());
}
@SafeVarargs
- public final IssueDto insert(RuleDefinitionDto rule, ProjectDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+ public final IssueDto insert(RuleDto rule, ProjectDto project, ComponentDto file, Consumer<IssueDto>... populators) {
IssueDto issue = newIssue(rule, project, file);
stream(populators).forEach(p -> p.accept(issue));
return insert(issue);
*/
@SafeVarargs
public final IssueDto insertIssue(Consumer<IssueDto>... populators) {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(rule, project, file)
* @throws AssertionError if rule is not Security Hotspot
*/
@SafeVarargs
- public final IssueDto insertHotspot(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
+ public final IssueDto insertHotspot(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
checkArgument(rule.getType() == RuleType.SECURITY_HOTSPOT.getDbConstant(), "rule must be a hotspot rule");
IssueDto issue = newIssue(rule, project, file)
*/
@SafeVarargs
public final IssueDto insertHotspot(ComponentDto project, ComponentDto file, Consumer<IssueDto>... populators) {
- RuleDefinitionDto rule = db.rules().insertHotspotRule();
+ RuleDto rule = db.rules().insertHotspotRule();
IssueDto issue = newIssue(rule, project, file)
.setType(SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
*/
@SafeVarargs
public final IssueDto insertHotspot(Consumer<IssueDto>... populators) {
- RuleDefinitionDto rule = db.rules().insertHotspotRule();
+ RuleDto rule = db.rules().insertHotspotRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = newIssue(rule, project, file)
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
return this;
}
- public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule) {
+ public ActiveRuleDto activateRule(QProfileDto profile, RuleDto rule) {
return activateRule(profile, rule, ar -> {
});
}
- public ActiveRuleDto activateRule(QProfileDto profile, RuleDefinitionDto rule, Consumer<ActiveRuleDto> consumer) {
+ public ActiveRuleDto activateRule(QProfileDto profile, RuleDto rule, Consumer<ActiveRuleDto> consumer) {
ActiveRuleDto activeRule = createFor(profile, rule)
.setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())))
.setCreatedAt(nextLong())
import java.util.function.Consumer;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
-import org.sonar.api.server.rule.RuleParamType;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import static java.util.Arrays.asList;
-import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.db.rule.RuleTesting.newDeprecatedRuleKey;
import static org.sonar.db.rule.RuleTesting.newRule;
this.db = db;
}
- public RuleDefinitionDto insert() {
+ public RuleDto insert() {
return insert(newRule());
}
- public RuleDefinitionDto insert(RuleKey key) {
+ public RuleDto insert(RuleKey key) {
return insert(newRule(key));
}
@SafeVarargs
- public final RuleDefinitionDto insert(Consumer<RuleDefinitionDto>... populaters) {
- RuleDefinitionDto rule = newRule();
+ public final RuleDto insert(Consumer<RuleDto>... populaters) {
+ RuleDto rule = newRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
- public RuleDefinitionDto insert(RuleKey key, Consumer<RuleDefinitionDto> populater) {
- RuleDefinitionDto rule = newRule(key);
+ public RuleDto insert(RuleKey key, Consumer<RuleDto> populater) {
+ RuleDto rule = newRule(key);
populater.accept(rule);
return insert(rule);
}
- public RuleDefinitionDto insertIssueRule() {
+ public RuleDto insertIssueRule() {
return insert(newIssueRule());
}
- public RuleDefinitionDto insertIssueRule(RuleKey key) {
+ public RuleDto insertIssueRule(RuleKey key) {
return insert(newIssueRule(key));
}
@SafeVarargs
- public final RuleDefinitionDto insertIssueRule(Consumer<RuleDefinitionDto>... populaters) {
- RuleDefinitionDto rule = newIssueRule();
+ public final RuleDto insertIssueRule(Consumer<RuleDto>... populaters) {
+ RuleDto rule = newIssueRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
- public RuleDefinitionDto insertIssueRule(RuleKey key, Consumer<RuleDefinitionDto> populater) {
- RuleDefinitionDto rule = newIssueRule(key);
+ public RuleDto insertIssueRule(RuleKey key, Consumer<RuleDto> populater) {
+ RuleDto rule = newIssueRule(key);
populater.accept(rule);
return insert(rule);
}
- private static RuleDefinitionDto newIssueRule(RuleKey key) {
+ private static RuleDto newIssueRule(RuleKey key) {
return newRule(key).setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
}
- private static RuleDefinitionDto newIssueRule() {
+ private static RuleDto newIssueRule() {
return newRule().setType(RULE_TYPES_EXCEPT_HOTSPOTS[new Random().nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)]);
}
- public RuleDefinitionDto insertHotspotRule() {
+ public RuleDto insertHotspotRule() {
return insert(newHotspotRule());
}
@SafeVarargs
- public final RuleDefinitionDto insertHotspotRule(Consumer<RuleDefinitionDto>... populaters) {
- RuleDefinitionDto rule = newHotspotRule();
+ public final RuleDto insertHotspotRule(Consumer<RuleDto>... populaters) {
+ RuleDto rule = newHotspotRule();
asList(populaters).forEach(populater -> populater.accept(rule));
return insert(rule);
}
- private static RuleDefinitionDto newHotspotRule() {
+ private static RuleDto newHotspotRule() {
return newRule().setType(SECURITY_HOTSPOT);
}
- public RuleDefinitionDto insert(RuleDefinitionDto rule) {
+ public RuleDto insert(RuleDto rule) {
if (rule.getUuid() == null) {
rule.setUuid(Uuids.createFast());
}
return rule;
}
- public RuleDefinitionDto update(RuleDefinitionDto rule) {
+ public RuleDto update(RuleDto rule) {
db.getDbClient().ruleDao().update(db.getSession(), rule);
db.commit();
return rule;
}
@SafeVarargs
- public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, Consumer<RuleMetadataDto>... populaters) {
+ public final RuleMetadataDto insertOrUpdateMetadata(RuleDto rule, Consumer<RuleMetadataDto>... populaters) {
RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule);
asList(populaters).forEach(populater -> populater.accept(dto));
return insertOrUpdateMetadata(dto);
}
@SafeVarargs
- public final RuleMetadataDto insertOrUpdateMetadata(RuleDefinitionDto rule, UserDto noteUser, Consumer<RuleMetadataDto>... populaters) {
+ public final RuleMetadataDto insertOrUpdateMetadata(RuleDto rule, UserDto noteUser, Consumer<RuleMetadataDto>... populaters) {
RuleMetadataDto dto = RuleTesting.newRuleMetadata(rule, noteUser);
asList(populaters).forEach(populater -> populater.accept(dto));
return insertOrUpdateMetadata(dto);
}
public RuleMetadataDto insertOrUpdateMetadata(RuleMetadataDto metadata) {
- db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata);
+ db.getDbClient().ruleDao().insertOrUpdateRuleMetadata(db.getSession(), metadata);
db.commit();
- return metadata;
- }
-
- public RuleParamDto insertRuleParam(RuleDefinitionDto rule) {
- return insertRuleParam(rule, p -> {
- });
+ return db.getDbClient().ruleDao().selectByUuid(metadata.getRuleUuid(), db.getSession()).get().getMetadata();
}
@SafeVarargs
- public final RuleParamDto insertRuleParam(RuleDefinitionDto rule, Consumer<RuleParamDto>... populaters) {
+ public final RuleParamDto insertRuleParam(RuleDto rule, Consumer<RuleParamDto>... populaters) {
RuleParamDto param = RuleTesting.newRuleParam(rule);
asList(populaters).forEach(populater -> populater.accept(param));
db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule, param);
ruleDto.setUuid(Uuids.createFast());
}
- insert(ruleDto.getDefinition());
+ insert(ruleDto);
RuleMetadataDto metadata = ruleDto.getMetadata();
- db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), metadata.setRuleUuid(ruleDto.getUuid()));
+ db.getDbClient().ruleDao().insertOrUpdateRuleMetadata(db.getSession(), metadata.setRuleUuid(ruleDto.getUuid()));
db.commit();
return ruleDto;
}
return deprecatedRuleKeyDto;
}
- public RuleParamDto insertRuleParam(RuleDto rule) {
- RuleParamDto param = new RuleParamDto();
- param.setRuleUuid(rule.getUuid());
- param.setName(randomAlphabetic(10));
- param.setType(RuleParamType.STRING.type());
- db.getDbClient().ruleDao().insertRuleParam(db.getSession(), rule.getDefinition(), param);
- db.commit();
- return param;
- }
-
- public RuleDto insertRule(RuleDefinitionDto ruleDefinition, RuleMetadataDto ruleMetadata) {
- db.getDbClient().ruleDao().insertOrUpdate(db.getSession(), ruleMetadata.setRuleUuid(ruleDefinition.getUuid()));
+ public RuleDto insertRule(RuleDto ruleDto, RuleMetadataDto ruleMetadata) {
+ db.getDbClient().ruleDao().insertOrUpdateRuleMetadata(db.getSession(), ruleMetadata.setRuleUuid(ruleDto.getUuid()));
db.commit();
- return new RuleDto(ruleDefinition, ruleMetadata);
+ return db.getDbClient().ruleDao().selectOrFailByKey(db.getSession(), ruleDto.getKey());
}
}
// only static helpers
}
- public static RuleDefinitionDto newRule() {
+ public static RuleDto newRule() {
return newRule(randomRuleKey());
}
- public static RuleDefinitionDto newRule(RuleKey key) {
- RuleDefinitionDto ruleDefinitionDto = newRuleWithoutDescriptionSection(key);
- ruleDefinitionDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5)));
- return ruleDefinitionDto;
+ public static RuleDto newRule(RuleKey key) {
+ RuleDto ruleDto = newRuleWithoutDescriptionSection(key);
+ ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5)));
+ return ruleDto;
}
- public static RuleDefinitionDto newRuleWithoutDescriptionSection() {
+ public static RuleDto newRuleWithoutDescriptionSection() {
return newRuleWithoutDescriptionSection(randomRuleKey());
}
- public static RuleDefinitionDto newRuleWithoutDescriptionSection(RuleKey ruleKey) {
+ public static RuleDto newRuleWithoutDescriptionSection(RuleKey ruleKey) {
long currentTimeMillis = System.currentTimeMillis();
- return new RuleDefinitionDto()
+ return new RuleDto()
.setRepositoryKey(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setUuid("rule_uuid_" + randomAlphanumeric(5))
.setAdHocDescription("adHocDescription_" + randomAlphanumeric(5))
.setAdHocSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())))
.setAdHocType(RuleType.values()[nextInt(RuleType.values().length - 1)])
- .setCreatedAt(System.currentTimeMillis() - 100)
- .setUpdatedAt(System.currentTimeMillis() - 50);
+ .setCreatedAt(System.currentTimeMillis())
+ .setUpdatedAt(System.currentTimeMillis() + 50);
}
- public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule) {
+ public static RuleMetadataDto newRuleMetadata(RuleDto rule) {
return newRuleMetadata()
.setRuleUuid(rule.getUuid());
}
- public static RuleMetadataDto newRuleMetadata(RuleDefinitionDto rule, UserDto noteUser) {
+ public static RuleMetadataDto newRuleMetadata(RuleDto rule, UserDto noteUser) {
return newRuleMetadata(rule).setNoteUserUuid(noteUser.getUuid());
}
- public static RuleParamDto newRuleParam(RuleDefinitionDto rule) {
+ public static RuleParamDto newRuleParam(RuleDto rule) {
return new RuleParamDto()
.setRuleUuid(rule.getUuid())
.setName("name_" + randomAlphabetic(5))
.setIsTemplate(true);
}
- /**
- * @deprecated use {@link #newCustomRule(RuleDefinitionDto)}
- */
- @Deprecated
- public static RuleDto newCustomRule(RuleDto templateRule) {
- checkNotNull(templateRule.getUuid(), "The template rule need to be persisted before creating this custom rule.");
- return newDto(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis()))
- .setLanguage(templateRule.getLanguage())
- .setTemplateUuid(templateRule.getUuid())
- .setType(templateRule.getType());
- }
- public static RuleDefinitionDto newCustomRule(RuleDefinitionDto templateRule) {
+ public static RuleDto newCustomRule(RuleDto templateRule) {
checkNotNull(templateRule.getUuid(), "The template rule need to be persisted before creating this custom rule.");
return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis()))
.setLanguage(templateRule.getLanguage())
return RuleKey.of(randomAlphabetic(255), randomAlphabetic(200));
}
- public static Consumer<RuleDefinitionDto> setRepositoryKey(String repositoryKey) {
+ public static Consumer<RuleDto> setRepositoryKey(String repositoryKey) {
return rule -> rule.setRepositoryKey(repositoryKey);
}
- public static Consumer<RuleDefinitionDto> setCreatedAt(long createdAt) {
+ public static Consumer<RuleDto> setCreatedAt(long createdAt) {
return rule -> rule.setCreatedAt(createdAt);
}
- public static Consumer<RuleDefinitionDto> setUpdatedAt(long updatedtAt) {
+ public static Consumer<RuleDto> setUpdatedAt(long updatedtAt) {
return rule -> rule.setUpdatedAt(updatedtAt);
}
- public static Consumer<RuleDefinitionDto> setRuleKey(String ruleKey) {
+ public static Consumer<RuleDto> setRuleKey(String ruleKey) {
return rule -> rule.setRuleKey(ruleKey);
}
- public static Consumer<RuleDefinitionDto> setName(String name) {
+ public static Consumer<RuleDto> setName(String name) {
return rule -> rule.setName(name);
}
- public static Consumer<RuleDefinitionDto> setLanguage(String language) {
+ public static Consumer<RuleDto> setLanguage(String language) {
return rule -> rule.setLanguage(language);
}
- public static Consumer<RuleDefinitionDto> setSeverity(String severity) {
+ public static Consumer<RuleDto> setSeverity(String severity) {
return rule -> rule.setSeverity(severity);
}
- public static Consumer<RuleDefinitionDto> setStatus(RuleStatus status) {
+ public static Consumer<RuleDto> setStatus(RuleStatus status) {
return rule -> rule.setStatus(status);
}
- public static Consumer<RuleDefinitionDto> setType(RuleType type) {
+ public static Consumer<RuleDto> setType(RuleType type) {
return rule -> rule.setType(type);
}
- public static Consumer<RuleDefinitionDto> setIsExternal(boolean isExternal) {
+ public static Consumer<RuleDto> setIsExternal(boolean isExternal) {
return rule -> rule.setIsExternal(isExternal);
}
- public static Consumer<RuleDefinitionDto> setSecurityStandards(Set<String> securityStandards) {
+ public static Consumer<RuleDto> setSecurityStandards(Set<String> securityStandards) {
return rule -> rule.setSecurityStandards(securityStandards);
}
- public static Consumer<RuleDefinitionDto> setIsTemplate(boolean isTemplate) {
+ public static Consumer<RuleDto> setIsTemplate(boolean isTemplate) {
return rule -> rule.setIsTemplate(isTemplate);
}
- public static Consumer<RuleDefinitionDto> setTemplateId(@Nullable String templateUuid) {
+ public static Consumer<RuleDto> setTemplateId(@Nullable String templateUuid) {
return rule -> rule.setTemplateUuid(templateUuid);
}
- public static Consumer<RuleDefinitionDto> setSystemTags(String... tags) {
+ public static Consumer<RuleDto> setSystemTags(String... tags) {
return rule -> rule.setSystemTags(copyOf(tags));
}
public static final int UUID_VARCHAR_SIZE = 50;
public static final int UUID_SIZE = 40;
+ public static final int DESCRIPTION_SECTION_KEY_SIZE = 50;
/**
* UUID length of the USERS table is not using the standard UUID length.
* The reason of this is because when the UUID column was introduced in the USERS table, existing rows were fed with the login, which has a length of 255.
import org.sonar.server.platform.db.migration.step.CreateTableChange;
import static org.sonar.server.platform.db.migration.def.ClobColumnDef.newClobColumnDefBuilder;
+import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.DESCRIPTION_SECTION_KEY_SIZE;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder;
static final String RULE_DESCRIPTION_SECTIONS_TABLE = "rule_desc_sections";
+
public CreateRuleDescSectionsTable(Database db) {
super(db, RULE_DESCRIPTION_SECTIONS_TABLE);
}
public void execute(Context context, String tableName) throws SQLException {
context.execute(new CreateTableBuilder(getDialect(), tableName)
.addPkColumn(newVarcharColumnDefBuilder().setColumnName("uuid").setIsNullable(false).setLimit(UUID_SIZE).build())
- .addColumn(newVarcharColumnDefBuilder().setColumnName("rule_uuid").setIsNullable(false).setLimit(40).build())
- .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setIsNullable(false).setLimit(50).build())
+ .addColumn(newVarcharColumnDefBuilder().setColumnName("rule_uuid").setIsNullable(false).setLimit(UUID_SIZE).build())
+ .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setIsNullable(false).setLimit(DESCRIPTION_SECTION_KEY_SIZE).build())
.addColumn(newClobColumnDefBuilder().setColumnName("content").setIsNullable(false).build())
.build());
}
import static org.elasticsearch.common.Strings.isNullOrEmpty;
import static org.sonar.api.utils.DateUtils.longToDate;
import static org.sonar.db.DatabaseUtils.getLong;
-import static org.sonar.db.rule.RuleDefinitionDto.deserializeSecurityStandardsString;
+import static org.sonar.db.rule.RuleDto.deserializeSecurityStandardsString;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
/**
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileChangeDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
public class ActiveRuleChange {
private ActiveRuleInheritance inheritance = null;
private final Map<String, String> parameters = new HashMap<>();
- public ActiveRuleChange(Type type, ActiveRuleDto activeRule, RuleDefinitionDto ruleDefinition) {
+ public ActiveRuleChange(Type type, ActiveRuleDto activeRule, RuleDto ruleDto) {
this.type = type;
this.key = activeRule.getKey();
- this.ruleUuid = ruleDefinition.getUuid();
+ this.ruleUuid = ruleDto.getUuid();
this.activeRule = activeRule;
}
- public ActiveRuleChange(Type type, ActiveRuleKey key, RuleDefinitionDto ruleDefinition) {
+ public ActiveRuleChange(Type type, ActiveRuleKey key, RuleDto ruleDto) {
this.type = type;
this.key = key;
- this.ruleUuid = ruleDefinition.getUuid();
+ this.ruleUuid = ruleDto.getUuid();
}
public ActiveRuleKey getKey() {
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
}
@Override
- public Optional<RuleDefinitionDto> findDtoByKey(RuleKey key) {
+ public Optional<RuleDto> findDtoByKey(RuleKey key) {
try (DbSession dbSession = dbClient.openSession(false)) {
- return ruleDao.selectDefinitionByKey(dbSession, key)
+ return ruleDao.selectByKey(dbSession, key)
.filter(r -> r.getStatus() != RuleStatus.REMOVED);
}
}
@Override
- public Optional<RuleDefinitionDto> findDtoByUuid(String uuid) {
+ public Optional<RuleDto> findDtoByUuid(String uuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
- return ruleDao.selectDefinitionByUuid(uuid, dbSession)
+ return ruleDao.selectByUuid(uuid, dbSession)
.filter(r -> r.getStatus() != RuleStatus.REMOVED);
}
}
@Override
- public Collection<RuleDefinitionDto> findAll() {
+ public Collection<RuleDto> findAll() {
try (DbSession dbSession = dbClient.openSession(false)) {
return ruleDao.selectEnabled(dbSession);
}
.setStatus(rule.getStatus().name())
.setSystemTags(rule.getSystemTags().toArray(new String[rule.getSystemTags().size()]))
.setTags(rule.getTags().toArray(new String[rule.getTags().size()]))
- .setDescription(getDescriptionAsHtml(rule.getDefinition()));
+ .setDescription(getDescriptionAsHtml(rule));
List<org.sonar.api.rules.RuleParam> apiParams = new ArrayList<>();
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleForIndexingDto;
import static java.util.Optional.ofNullable;
this.fixIt = fixIt;
}
- public static HotspotRuleDescription from(RuleDefinitionDto dto) {
+ public static HotspotRuleDescription from(RuleDto dto) {
String description = RuleDescriptionFormatter.getDescriptionAsHtml(dto);
return from(description);
}
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleForIndexingDto;
private RuleDescriptionFormatter() { /* static helpers */ }
- public static String getDescriptionAsHtml(RuleDefinitionDto ruleDefinitionDto) {
- if (ruleDefinitionDto.getDescriptionFormat() == null) {
+ public static String getDescriptionAsHtml(RuleDto ruleDto) {
+ if (ruleDto.getDescriptionFormat() == null) {
return null;
}
- Collection<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = ruleDefinitionDto.getRuleDescriptionSectionDtos();
- return retrieveDescription(ruleDescriptionSectionDtos, ruleDefinitionDto.getRuleKey(), ruleDefinitionDto.getDescriptionFormat());
+ Collection<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = ruleDto.getRuleDescriptionSectionDtos();
+ return retrieveDescription(ruleDescriptionSectionDtos, ruleDto.getRuleKey(), Objects.requireNonNull(ruleDto.getDescriptionFormat()));
}
public static String getDescriptionAsHtml(RuleForIndexingDto ruleForIndexingDto) {
}
private static String toHtml(String ruleKey, RuleDto.Format descriptionFormat, RuleDescriptionSectionDto ruleDescriptionSectionDto) {
- RuleDto.Format nonNullDescriptionFormat = Objects.requireNonNull(descriptionFormat,
- "Rule " + descriptionFormat + " contains section(s) but has no format set");
- switch (nonNullDescriptionFormat) {
+ switch (descriptionFormat) {
case MARKDOWN:
return Markdown.convertToHtml(ruleDescriptionSectionDto.getContent());
case HTML:
import java.util.Optional;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleFinder;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
public interface ServerRuleFinder extends RuleFinder {
- Optional<RuleDefinitionDto> findDtoByKey(RuleKey key);
+ Optional<RuleDto> findDtoByKey(RuleKey key);
- Optional<RuleDefinitionDto> findDtoByUuid(String uuid);
+ Optional<RuleDto> findDtoByUuid(String uuid);
- Collection<RuleDefinitionDto> findAll();
+ Collection<RuleDto> findAll();
}
import org.sonar.db.es.EsQueueDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.IndexingResult;
import org.sonar.server.es.ProjectIndexer;
@Test
public void verify_indexed_fields() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo"));
ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1"));
@Test
public void verify_security_standards_indexation() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setSecurityStandards(new HashSet<>(Arrays.asList("cwe:123", "owaspTop10:a3", "cwe:863"))));
+ RuleDto rule = db.rules().insert(r -> r.setSecurityStandards(new HashSet<>(Arrays.asList("cwe:123", "owaspTop10:a3", "cwe:863"))));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo"));
ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1"));
@Test
public void indexOnAnalysis_indexes_the_issues_of_project() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insert(rule, project, file);
@Test
public void indexOnAnalysis_does_not_delete_orphan_docs() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insert(rule, project, file);
@Test
public void commitAndIndexIssues_commits_db_transaction_and_adds_issues_to_index() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
@Test
public void indexing_errors_during_commitAndIndexIssues_are_recovered() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
@Test
public void indexing_recovers_multiple_errors_on_the_same_project() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue1 = db.issues().insert(rule, project, file);
@Test
public void index_issue_in_non_main_branch() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo"));
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(branch, "src/main/java/foo"));
@Test
public void issue_on_test_file_has_test_scope() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo"));
ComponentDto file = db.components().insertComponent(newFileDto(project, dir, "F1").setQualifier("UTS"));
@Test
public void issue_on_directory_has_main_code_scope() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto dir = db.components().insertComponent(ComponentTesting.newDirectory(project, "src/main/java/foo"));
IssueDto issue = db.issues().insert(rule, project, dir);
@Test
public void issue_on_project_has_main_code_scope() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
IssueDto issue = db.issues().insert(rule, project, project);
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.component.ComponentTesting.newDirectory;
@Test
public void iterator_over_one_issue() {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project = dbTester.components().insertPrivateProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project)
.setPath("src/main/java/Action.java"));
@Test
public void iterator_over_issues() {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project = dbTester.components().insertPrivateProject();
ComponentDto module = dbTester.components().insertComponent(newModuleDto(project));
ComponentDto directory = dbTester.components().insertComponent(newDirectory(module, "src/main/java"));
@Test
public void iterator_over_issue_from_project() {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project1 = dbTester.components().insertPrivateProject();
ComponentDto module1 = dbTester.components().insertComponent(newModuleDto(project1));
ComponentDto file1 = dbTester.components().insertComponent(newFileDto(module1));
@Test
public void extract_directory_path() {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project = dbTester.components().insertPrivateProject();
ComponentDto module = dbTester.components().insertComponent(newModuleDto(project));
ComponentDto fileInRootDir = dbTester.components().insertComponent(newFileDto(module).setPath("pom.xml"));
@Test
public void extract_file_path() {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project = dbTester.components().insertPrivateProject();
ComponentDto module = dbTester.components().insertComponent(newModuleDto(project));
ComponentDto fileInRootDir = dbTester.components().insertComponent(newFileDto(module).setPath("pom.xml"));
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier;
import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition;
ComponentDto project = db.components().insertPrivateProject();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "path"));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
+ RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp")));
IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp")));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "path"));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
+ RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp")));
IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp")));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "path"));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
+ RuleDto rule1 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-world").setName("Rule the World").setLanguage("Java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setRepositoryKey("SonarQube").setRuleKey("rule1-the-universe").setName("Rule the Universe").setLanguage("Clojure"));
IssueDto issue1 = db.issues().insert(rule1, project, file, i -> i.setType(BUG).setAssigneeUuid(maynard.getUuid()).setTags(asList("bug", "owasp")));
IssueDto issue2 = db.issues().insert(rule2, project, directory, i -> i.setType(CODE_SMELL).setAssigneeUuid(keenan.getUuid()).setTags(singletonList("owasp")));
}
}
- private void mockDetailsSupplierRules(RuleDefinitionDto... rules) {
- for (RuleDefinitionDto rule : rules) {
+ private void mockDetailsSupplierRules(RuleDto... rules) {
+ for (RuleDto rule : rules) {
when(detailsSupplier.getRuleDefinitionByRuleKey(rule.getKey()))
.thenReturn(Optional.of(new RuleDefinition(rule.getName(), rule.getLanguage())));
}
public void set_assignee() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
IssueDto issue = db.issues().insert(rule, project, file, i -> i.setAssigneeUuid(user.getUuid()));
NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true);
UserDto user8 = db.users().insertUser();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true);
IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user1.getUuid())).toDefaultIssue()));
IntStream.rangeClosed(1, 9).forEach(i -> stats.add(db.issues().insert(rule, project, file, issue -> issue.setAssigneeUuid(user2.getUuid())).toDefaultIssue()));
@Test
public void add_only_5_components_with_biggest_issue_counts() {
ComponentDto project = db.components().insertPrivateProject();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true);
ComponentDto file1 = db.components().insertComponent(newFileDto(project));
IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule, project, file1).toDefaultIssue()));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
NewIssuesStatistics.Stats stats = new NewIssuesStatistics.Stats(i -> true);
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 10).forEach(i -> stats.add(db.issues().insert(rule1, project, file).toDefaultIssue()));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 9).forEach(i -> stats.add(db.issues().insert(rule2, project, file).toDefaultIssue()));
- RuleDefinitionDto rule3 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule3 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 8).forEach(i -> stats.add(db.issues().insert(rule3, project, file).toDefaultIssue()));
- RuleDefinitionDto rule4 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule4 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 7).forEach(i -> stats.add(db.issues().insert(rule4, project, file).toDefaultIssue()));
- RuleDefinitionDto rule5 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule5 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 6).forEach(i -> stats.add(db.issues().insert(rule5, project, file).toDefaultIssue()));
- RuleDefinitionDto rule6 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule6 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 5).forEach(i -> stats.add(db.issues().insert(rule6, project, file).toDefaultIssue()));
- RuleDefinitionDto rule7 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule7 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 4).forEach(i -> stats.add(db.issues().insert(rule7, project, file).toDefaultIssue()));
- RuleDefinitionDto rule8 = db.rules().insert(r -> r.setLanguage("Java"));
+ RuleDto rule8 = db.rules().insert(r -> r.setLanguage("Java"));
IntStream.rangeClosed(1, 3).forEach(i -> stats.add(db.issues().insert(rule8, project, file).toDefaultIssue()));
mockDetailsSupplierComponents(project, file);
mockDetailsSupplierRules(rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8);
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto;
QProfileDto profile = newQualityProfileDto();
ActiveRuleKey key = ActiveRuleKey.of(profile, RuleKey.of("P1", "R1"));
String ruleUuid = Uuids.createFast();
- ActiveRuleChange underTest = new ActiveRuleChange(ACTIVATED, key, new RuleDefinitionDto().setUuid(ruleUuid));
+ ActiveRuleChange underTest = new ActiveRuleChange(ACTIVATED, key, new RuleDto().setUuid(ruleUuid));
QProfileChangeDto result = underTest.toDto(A_USER_UUID);
import org.sonar.db.es.EsQueueDto;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.qualityprofile.ActiveRuleChange;
public EsTester es = EsTester.create();
private ActiveRuleIndexer underTest = new ActiveRuleIndexer(db.getDbClient(), es.client());
- private RuleDefinitionDto rule1;
- private RuleDefinitionDto rule2;
+ private RuleDto rule1;
+ private RuleDto rule2;
private QProfileDto profile1;
private QProfileDto profile2;
.containsExactlyInAnyOrder(Tuple.tuple(expected.getDocId(), expected.getDocIdType(), expected.getDocRouting()));
}
- private void commitAndIndex(RuleDefinitionDto rule, ActiveRuleDto... ar) {
+ private void commitAndIndex(RuleDto rule, ActiveRuleDto... ar) {
underTest.commitAndIndex(db.getSession(), stream(ar)
.map(a -> new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, a, rule))
.collect(Collectors.toList()));
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
assertThat(underTest.findAll(RuleQuery.create())).extracting(Rule::ruleKey).containsOnly(rule1.getKey(), rule3.getKey(), rule4.getKey());
// find_all
- assertThat(underTest.findAll()).extracting(RuleDefinitionDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule());
+ assertThat(underTest.findAll()).extracting(RuleDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule());
// do_not_find_disabled_rules
assertThat(underTest.findByKey("checkstyle", "DisabledCheck")).isNull();
public void find_all_not_include_removed_rule() {
// rule 3 is REMOVED
assertThat(underTest.findAll(RuleQuery.create())).extracting(Rule::ruleKey).containsOnly(rule1.getKey(), rule3.getKey(), rule4.getKey());
- assertThat(underTest.findAll()).extracting(RuleDefinitionDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule());
+ assertThat(underTest.findAll()).extracting(RuleDto::getRuleKey).containsOnly(rule1.getKey().rule(), rule3.getKey().rule(), rule4.getKey().rule());
}
@Test
public void findByKey_populates_system_tags_but_not_tags() {
- RuleDefinitionDto ruleDefinition = dbTester.rules()
+ RuleDto ruleDto = dbTester.rules()
.insert(t -> t.setSystemTags(ImmutableSet.of(randomAlphanumeric(5), randomAlphanumeric(6))));
dbTester.rules().insertRule();
- Rule rule = underTest.findByKey(ruleDefinition.getKey());
+ Rule rule = underTest.findByKey(ruleDto.getKey());
assertThat(rule.getSystemTags())
- .containsOnlyElementsOf(ruleDefinition.getSystemTags());
+ .containsOnlyElementsOf(ruleDto.getSystemTags());
assertThat(rule.getTags()).isEmpty();
- rule = underTest.findByKey(ruleDefinition.getRepositoryKey(), ruleDefinition.getRuleKey());
+ rule = underTest.findByKey(ruleDto.getRepositoryKey(), ruleDto.getRuleKey());
assertThat(rule.getSystemTags())
- .containsOnlyElementsOf(ruleDefinition.getSystemTags());
+ .containsOnlyElementsOf(ruleDto.getSystemTags());
assertThat(rule.getTags()).isEmpty();
}
}
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
-import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection;
@RunWith(DataProviderRunner.class)
public class HotspotRuleDescriptionTest {
@Test
public void parse_returns_all_empty_fields_when_no_description() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection();
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection();
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_returns_all_empty_fields_when_empty_description() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", ""));
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", ""));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
@UseDataProvider("descriptionsWithoutTitles")
public void parse_to_risk_description_fields_when_desc_contains_no_section(String description) {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", description));
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", description));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_return_null_risk_when_desc_starts_with_ask_yourself_title() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
createDefaultRuleDescriptionSection("uuid", (ASKATRISK + RECOMMENTEDCODINGPRACTICE)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_return_null_vulnerable_when_no_ask_yourself_whether_title() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection()
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", (DESCRIPTION + RECOMMENTEDCODINGPRACTICE)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_return_null_fixIt_when_desc_has_no_Recommended_Secure_Coding_Practices_title() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection()
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection("uuid", (DESCRIPTION + ASKATRISK)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_with_noncompliant_section_not_removed() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
createDefaultRuleDescriptionSection("uuid", (DESCRIPTION + NONCOMPLIANTCODE + COMPLIANTCODE)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_moved_noncompliant_code() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
createDefaultRuleDescriptionSection("uuid", (DESCRIPTION + RECOMMENTEDCODINGPRACTICE + NONCOMPLIANTCODE + SEE)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
@Test
public void parse_moved_sensitivecode_code() {
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection().addRuleDescriptionSectionDto(
createDefaultRuleDescriptionSection("uuid", (DESCRIPTION + ASKATRISK + RECOMMENTEDCODINGPRACTICE + SENSITIVECODE + SEE)));
HotspotRuleDescription result = HotspotRuleDescription.from(dto);
String askContent = "This is the ask section content";
String recommendedContent = "This is the recommended section content";
- RuleDefinitionDto dto = RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto dto = RuleTesting.newRuleWithoutDescriptionSection()
.setTemplateUuid("123")
.setDescriptionFormat(RuleDto.Format.MARKDOWN)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleForIndexingDto;
@Test
public void getMarkdownDescriptionAsHtml() {
- RuleDefinitionDto rule = new RuleDefinitionDto().setDescriptionFormat(RuleDto.Format.MARKDOWN).addRuleDescriptionSectionDto(MARKDOWN_SECTION);
+ RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.MARKDOWN).addRuleDescriptionSectionDto(MARKDOWN_SECTION);
String html = RuleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo("<strong>md</strong> <code>description</code>");
}
@Test
public void getHtmlDescriptionAsIs() {
- RuleDefinitionDto rule = new RuleDefinitionDto().setDescriptionFormat(RuleDto.Format.HTML).addRuleDescriptionSectionDto(HTML_SECTION);
+ RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML).addRuleDescriptionSectionDto(HTML_SECTION);
String html = RuleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo(HTML_SECTION.getContent());
}
@Test
public void handleEmptyDescription() {
- RuleDefinitionDto rule = new RuleDefinitionDto().setDescriptionFormat(RuleDto.Format.HTML);
+ RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML);
String result = RuleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(result).isNull();
}
@Test
public void handleNullDescriptionFormat() {
RuleDescriptionSectionDto sectionWithNullFormat = createDefaultRuleDescriptionSection("uuid", "whatever");
- RuleDefinitionDto rule = new RuleDefinitionDto().addRuleDescriptionSectionDto(sectionWithNullFormat);
+ RuleDto rule = new RuleDto().addRuleDescriptionSectionDto(sectionWithNullFormat);
String result = RuleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(result).isNull();
}
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.Facets;
@Test
public void search_by_key() {
- RuleDefinitionDto js1 = createRule(
+ RuleDto js1 = createRule(
setRepositoryKey("javascript"),
setRuleKey("X001"));
- RuleDefinitionDto cobol1 = createRule(
+ RuleDto cobol1 = createRule(
setRepositoryKey("cobol"),
setRuleKey("X001"));
createRule(
@Test
public void search_by_case_insensitive_key() {
- RuleDefinitionDto ruleDto = createRule(
+ RuleDto ruleDto = createRule(
setRepositoryKey("javascript"),
setRuleKey("X001"));
index();
@Test
public void search_name_with_protected_chars() {
- RuleDefinitionDto rule = createRule(setName("ja#va&sc\"r:ipt"));
+ RuleDto rule = createRule(setName("ja#va&sc\"r:ipt"));
index();
RuleQuery protectedCharsQuery = new RuleQuery().setQueryText(rule.getName());
public void search_content_by_query() {
// it's important to set all the fields being used by the search (name, desc, key, lang, ...),
// otherwise the generated random values may raise false-positives
- RuleDefinitionDto rule1 = createJavaRule(rule -> rule.setRuleKey("123")
+ RuleDto rule1 = createJavaRule(rule -> rule.setRuleKey("123")
.setName("rule 123")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "My great rule CWE-123 which makes your code 1000 times better!")));
- RuleDefinitionDto rule2 = createJavaRule(rule -> rule.setRuleKey("124")
+ RuleDto rule2 = createJavaRule(rule -> rule.setRuleKey("124")
.setName("rule 124")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another great and shiny rule CWE-124")));
- RuleDefinitionDto rule3 = createJavaRule(rule -> rule.setRuleKey("1000")
+ RuleDto rule3 = createJavaRule(rule -> rule.setRuleKey("1000")
.setName("rule 1000")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another great rule CWE-1000")));
- RuleDefinitionDto rule4 = createJavaRule(rule -> rule.setRuleKey("404")
+ RuleDto rule4 = createJavaRule(rule -> rule.setRuleKey("404")
.setName("rule 404")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(),
"<h1>HTML-Geeks</h1><p style=\"color:blue\">special formatting!</p><table><tr><td>inside</td><td>tables</td></tr></table>")));
- RuleDefinitionDto rule5 = createJavaRule(rule -> rule.setRuleKey("405")
+ RuleDto rule5 = createJavaRule(rule -> rule.setRuleKey("405")
.setName("rule 405")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "internationalization missunderstandings alsdkjfnadklsjfnadkdfnsksdjfn")));
index();
@Test
public void search_by_any_of_repositories() {
- RuleDefinitionDto findbugs = createRule(
+ RuleDto findbugs = createRule(
setRepositoryKey("findbugs"),
setRuleKey("S001"));
- RuleDefinitionDto pmd = createRule(
+ RuleDto pmd = createRule(
setRepositoryKey("pmd"),
setRuleKey("S002"));
index();
@Test
public void filter_by_tags() {
- RuleDefinitionDto rule1 = createRule(setSystemTags("tag1s"));
+ RuleDto rule1 = createRule(setSystemTags("tag1s"));
createRuleMetadata(rule1, setTags("tag1"));
- RuleDefinitionDto rule2 = createRule(setSystemTags("tag2s"));
+ RuleDto rule2 = createRule(setSystemTags("tag2s"));
createRuleMetadata(rule2, setTags("tag2"));
index();
@Test
public void tags_facet_supports_selected_value_with_regexp_special_characters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
createRuleMetadata(rule, setTags("misra++"));
index();
@Test
public void search_by_types() {
createRule(setType(CODE_SMELL));
- RuleDefinitionDto vulnerability = createRule(setType(VULNERABILITY));
- RuleDefinitionDto bug1 = createRule(setType(BUG));
- RuleDefinitionDto bug2 = createRule(setType(BUG));
+ RuleDto vulnerability = createRule(setType(VULNERABILITY));
+ RuleDto bug1 = createRule(setType(BUG));
+ RuleDto bug2 = createRule(setType(BUG));
index();
// find all
@Test
public void search_by_is_template() {
- RuleDefinitionDto ruleNoTemplate = createRule(setIsTemplate(false));
- RuleDefinitionDto ruleIsTemplate = createRule(setIsTemplate(true));
+ RuleDto ruleNoTemplate = createRule(setIsTemplate(false));
+ RuleDto ruleIsTemplate = createRule(setIsTemplate(true));
index();
// find all
@Test
public void search_by_is_external() {
- RuleDefinitionDto ruleIsNotExternal = createRule(setIsExternal(false));
- RuleDefinitionDto ruleIsExternal = createRule(setIsExternal(true));
+ RuleDto ruleIsNotExternal = createRule(setIsExternal(false));
+ RuleDto ruleIsExternal = createRule(setIsExternal(true));
index();
// Only external
@Test
public void search_by_template_key() {
- RuleDefinitionDto template = createRule(setIsTemplate(true));
- RuleDefinitionDto customRule = createRule(setTemplateId(template.getUuid()));
+ RuleDto template = createRule(setIsTemplate(true));
+ RuleDto customRule = createRule(setTemplateId(template.getUuid()));
index();
// find all
@Test
public void search_by_any_of_languages() {
createRule(setLanguage("java"));
- RuleDefinitionDto javascript = createRule(setLanguage("js"));
+ RuleDto javascript = createRule(setLanguage("js"));
index();
RuleQuery query = new RuleQuery().setLanguages(asList("cobol", "js"));
@Test
public void search_by_security_cwe_return_vulnerabilities_and_hotspots_only() {
- RuleDefinitionDto rule1 = createRule(setSecurityStandards(of("cwe:543", "cwe:123", "owaspTop10:a1")), r -> r.setType(VULNERABILITY));
- RuleDefinitionDto rule2 = createRule(setSecurityStandards(of("cwe:543", "owaspTop10:a1")), r -> r.setType(SECURITY_HOTSPOT));
+ RuleDto rule1 = createRule(setSecurityStandards(of("cwe:543", "cwe:123", "owaspTop10:a1")), r -> r.setType(VULNERABILITY));
+ RuleDto rule2 = createRule(setSecurityStandards(of("cwe:543", "owaspTop10:a1")), r -> r.setType(SECURITY_HOTSPOT));
createRule(setSecurityStandards(of("owaspTop10:a1")), r -> r.setType(CODE_SMELL));
index();
@Test
public void search_by_security_owaspTop10_2017_return_vulnerabilities_and_hotspots_only() {
- RuleDefinitionDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:543")), r -> r.setType(VULNERABILITY));
- RuleDefinitionDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT));
+ RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:543")), r -> r.setType(VULNERABILITY));
+ RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT));
createRule(setSecurityStandards(of("cwe:543")), r -> r.setType(CODE_SMELL));
index();
@Test
public void search_by_security_owaspTop10_2021_return_vulnerabilities_and_hotspots_only() {
- RuleDefinitionDto rule1 = createRule(setSecurityStandards(of("owaspTop10-2021:a1", "owaspTop10-2021:a10", "cwe:543")), r -> r.setType(VULNERABILITY));
- RuleDefinitionDto rule2 = createRule(setSecurityStandards(of("owaspTop10-2021:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT));
+ RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10-2021:a1", "owaspTop10-2021:a10", "cwe:543")), r -> r.setType(VULNERABILITY));
+ RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10-2021:a10", "cwe:543")), r -> r.setType(SECURITY_HOTSPOT));
createRule(setSecurityStandards(of("cwe:543")), r -> r.setType(CODE_SMELL));
index();
@Test
public void search_by_security_sansTop25_return_vulnerabilities_and_hotspots_only() {
- RuleDefinitionDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:89")), r -> r.setType(VULNERABILITY));
- RuleDefinitionDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:829")), r -> r.setType(SECURITY_HOTSPOT));
+ RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10:a10", "cwe:89")), r -> r.setType(VULNERABILITY));
+ RuleDto rule2 = createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:829")), r -> r.setType(SECURITY_HOTSPOT));
createRule(setSecurityStandards(of("cwe:306")), r -> r.setType(CODE_SMELL));
index();
@Test
public void search_by_security_sonarsource_return_vulnerabilities_and_hotspots_only() {
- RuleDefinitionDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10-2021:a10", "cwe:89")), r -> r.setType(VULNERABILITY));
+ RuleDto rule1 = createRule(setSecurityStandards(of("owaspTop10:a1", "owaspTop10-2021:a10", "cwe:89")), r -> r.setType(VULNERABILITY));
createRule(setSecurityStandards(of("owaspTop10:a10", "cwe:829")), r -> r.setType(CODE_SMELL));
- RuleDefinitionDto rule3 = createRule(setSecurityStandards(of("cwe:601")), r -> r.setType(SECURITY_HOTSPOT));
+ RuleDto rule3 = createRule(setSecurityStandards(of("cwe:601")), r -> r.setType(SECURITY_HOTSPOT));
index();
RuleQuery query = new RuleQuery().setSonarsourceSecurity(of("sql-injection", "open-redirect"));
@Test
public void search_by_security_sonarsource_return_complete_list_of_facets() {
- List<RuleDefinitionDto> rules = new ArrayList<>();
+ List<RuleDto> rules = new ArrayList<>();
//Creation of one rule for each standard security category defined (except other)
for (Map.Entry<SecurityStandards.SQCategory, Set<String>> sqCategorySetEntry : SecurityStandards.CWES_BY_SQ_CATEGORY.entrySet()) {
String xoo = "xoo";
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(xoo));
QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setLanguage(xoo));
- RuleDefinitionDto commonRule = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
- RuleDefinitionDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
- RuleDefinitionDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
- RuleDefinitionDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
- RuleDefinitionDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
- RuleDefinitionDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo)).getDefinition();
+ RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(xoo));
+ RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo));
+ RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo));
+ RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(xoo));
+ RuleDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(xoo));
+ RuleDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(xoo));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(profile, profileRule1);
db.qualityProfiles().activateRule(profile, profileRule2);
}
@SafeVarargs
- private final RuleDefinitionDto createRule(Consumer<RuleDefinitionDto>... consumers) {
+ private final RuleDto createRule(Consumer<RuleDto>... consumers) {
return db.rules().insert(consumers);
}
- private RuleDefinitionDto createJavaRule() {
+ private RuleDto createJavaRule() {
return createRule(r -> r.setLanguage("java"));
}
- private RuleDefinitionDto createJavaRule(Consumer<RuleDefinitionDto> consumer) {
+ private RuleDto createJavaRule(Consumer<RuleDto> consumer) {
return createRule(r -> r.setLanguage("java"), consumer);
}
@SafeVarargs
- private final RuleMetadataDto createRuleMetadata(RuleDefinitionDto rule, Consumer<RuleMetadataDto>... populaters) {
+ private final RuleMetadataDto createRuleMetadata(RuleDto rule, Consumer<RuleMetadataDto>... populaters) {
return db.rules().insertOrUpdateMetadata(rule, populaters);
}
@Test
public void search_by_any_of_severities() {
createRule(setSeverity(BLOCKER));
- RuleDefinitionDto info = createRule(setSeverity(INFO));
+ RuleDto info = createRule(setSeverity(INFO));
index();
RuleQuery query = new RuleQuery().setSeverities(asList(INFO, MINOR));
@Test
public void search_by_any_of_statuses() {
- RuleDefinitionDto beta = createRule(setStatus(RuleStatus.BETA));
- RuleDefinitionDto ready = createRule(setStatus(RuleStatus.READY));
+ RuleDto beta = createRule(setStatus(RuleStatus.BETA));
+ RuleDto ready = createRule(setStatus(RuleStatus.READY));
index();
RuleQuery query = new RuleQuery().setStatuses(asList(RuleStatus.DEPRECATED, RuleStatus.READY));
@Test
public void activation_parameter_is_ignored_if_profile_is_not_set() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
QProfileDto profile1 = createJavaProfile();
db.qualityProfiles().activateRule(profile1, rule1);
index();
@Test
public void search_by_activation() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
- RuleDefinitionDto rule3 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
+ RuleDto rule3 = createJavaRule();
QProfileDto profile1 = createJavaProfile();
QProfileDto profile2 = createJavaProfile();
db.qualityProfiles().activateRule(profile1, rule1);
verifySearch(query);
}
- private void verifySearch(RuleQuery query, RuleDefinitionDto... expectedRules) {
+ private void verifySearch(RuleQuery query, RuleDto... expectedRules) {
SearchIdResult<String> result = underTest.search(query, new SearchOptions());
assertThat(result.getTotal()).isEqualTo(expectedRules.length);
assertThat(result.getUuids()).hasSize(expectedRules.length);
- for (RuleDefinitionDto expectedRule : expectedRules) {
+ for (RuleDto expectedRule : expectedRules) {
assertThat(result.getUuids()).contains(expectedRule.getUuid());
}
}
@Test
public void search_by_activation_and_inheritance() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
- RuleDefinitionDto rule3 = createJavaRule();
- RuleDefinitionDto rule4 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
+ RuleDto rule3 = createJavaRule();
+ RuleDto rule4 = createJavaRule();
QProfileDto parent = createJavaProfile();
QProfileDto child = createJavaProfile();
db.qualityProfiles().activateRule(parent, rule1);
@Test
public void search_by_activation_and_severity() {
- RuleDefinitionDto major = createRule(setSeverity(MAJOR));
- RuleDefinitionDto minor = createRule(setSeverity(MINOR));
- RuleDefinitionDto info = createRule(setSeverity(INFO));
+ RuleDto major = createRule(setSeverity(MAJOR));
+ RuleDto minor = createRule(setSeverity(MINOR));
+ RuleDto info = createRule(setSeverity(INFO));
QProfileDto profile1 = createJavaProfile();
QProfileDto profile2 = createJavaProfile();
db.qualityProfiles().activateRule(profile1, major, ar -> ar.setSeverity(BLOCKER));
@Test
public void facet_by_activation_severity_is_ignored_when_profile_is_not_specified() {
- RuleDefinitionDto rule = createJavaRule();
+ RuleDto rule = createJavaRule();
QProfileDto profile = createJavaProfile();
db.qualityProfiles().activateRule(profile, rule);
index();
@Test
public void listTags_should_return_tags() {
- RuleDefinitionDto rule1 = createRule(setSystemTags("sys1", "sys2"));
+ RuleDto rule1 = createRule(setSystemTags("sys1", "sys2"));
createRuleMetadata(rule1, setTags("tag1"));
- RuleDefinitionDto rule2 = createRule(setSystemTags());
+ RuleDto rule2 = createRule(setSystemTags());
createRuleMetadata(rule2, setTags("tag2"));
index();
@Test
public void available_since() {
- RuleDefinitionDto ruleOld = createRule(setCreatedAt(1_000L));
- RuleDefinitionDto ruleOlder = createRule(setCreatedAt(2_000L));
+ RuleDto ruleOld = createRule(setCreatedAt(-2_000L));
+ RuleDto ruleOlder = createRule(setCreatedAt(-1_000L));
index();
// 0. find all rules;
verifySearch(new RuleQuery(), ruleOld, ruleOlder);
// 1. find all rules available since a date;
- RuleQuery availableSinceQuery = new RuleQuery().setAvailableSince(2000L);
+ RuleQuery availableSinceQuery = new RuleQuery().setAvailableSince(-1000L);
verifySearch(availableSinceQuery, ruleOlder);
// 2. find no new rules since tomorrow.
- RuleQuery availableSinceNowQuery = new RuleQuery().setAvailableSince(3000L);
+ RuleQuery availableSinceNowQuery = new RuleQuery().setAvailableSince(1000L);
verifyEmptySearch(availableSinceNowQuery);
}
@Test
public void global_facet_on_repositories_and_tags() {
createRule(setRepositoryKey("php"), setSystemTags("sysTag"));
- RuleDefinitionDto rule1 = createRule(setRepositoryKey("php"), setSystemTags());
+ RuleDto rule1 = createRule(setRepositoryKey("php"), setSystemTags());
createRuleMetadata(rule1, setTags("tag1"));
- RuleDefinitionDto rule2 = createRule(setRepositoryKey("javascript"), setSystemTags());
+ RuleDto rule2 = createRule(setRepositoryKey("javascript"), setSystemTags());
createRuleMetadata(rule2, setTags("tag1", "tag2"));
index();
@Test
public void tags_facet_should_find_tags() {
- RuleDefinitionDto rule = createRule(setSystemTags());
+ RuleDto rule = createRule(setSystemTags());
createRuleMetadata(rule, setTags("bla"));
index();
@Test
public void sort_by_name() {
- RuleDefinitionDto abcd = createRule(setName("abcd"));
- RuleDefinitionDto abc = createRule(setName("ABC"));
- RuleDefinitionDto fgh = createRule(setName("FGH"));
+ RuleDto abcd = createRule(setName("abcd"));
+ RuleDto abc = createRule(setName("ABC"));
+ RuleDto fgh = createRule(setName("FGH"));
index();
// ascending
@Test
public void default_sort_is_by_updated_at_desc() {
- RuleDefinitionDto old = createRule(setCreatedAt(1000L), setUpdatedAt(1000L));
- RuleDefinitionDto oldest = createRule(setCreatedAt(1000L), setUpdatedAt(3000L));
- RuleDefinitionDto older = createRule(setCreatedAt(1000L), setUpdatedAt(2000L));
+ long currentTimeMillis = System.currentTimeMillis();
+
+ RuleDto old = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 1000L));
+ RuleDto oldest = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 3000L));
+ RuleDto older = createRule(setCreatedAt(1000L), setUpdatedAt(currentTimeMillis + 2000L));
index();
SearchIdResult<String> results = underTest.search(new RuleQuery(), new SearchOptions());
@Test
public void searchAll_keys_by_profile() {
- RuleDefinitionDto rule1 = createRule();
- RuleDefinitionDto rule2 = createRule();
- RuleDefinitionDto rule3 = createRule();
+ RuleDto rule1 = createRule();
+ RuleDto rule2 = createRule();
+ RuleDto rule3 = createRule();
QProfileDto profile1 = createJavaProfile();
QProfileDto profile2 = createJavaProfile();
db.qualityProfiles().activateRule(profile1, rule1);
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
-import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection;
import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE;
import static org.sonar.server.security.SecurityStandards.CWES_BY_SQ_CATEGORY;
import static org.sonar.server.security.SecurityStandards.SQ_CATEGORY_KEYS_ORDERING;
private DbClient dbClient = dbTester.getDbClient();
private final RuleIndexer underTest = new RuleIndexer(es.client(), dbClient);
private DbSession dbSession = dbTester.getSession();
- private RuleDefinitionDto rule = new RuleDefinitionDto()
+ private RuleDto rule = new RuleDto()
.setUuid("rule-uuid")
.setRuleKey("S001")
.setRepositoryKey("xoo")
public void index_long_rule_description() {
String description = IntStream.range(0, 100000).map(i -> i % 100).mapToObj(Integer::toString).collect(joining(" "));
RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), description);
- RuleDefinitionDto rule = dbTester.rules().insert(r -> r.addOrReplaceRuleDescriptionSectionDto(ruleDescriptionSectionDto));
+ RuleDto rule = dbTester.rules().insert(r -> r.addOrReplaceRuleDescriptionSectionDto(ruleDescriptionSectionDto));
underTest.commitAndIndex(dbTester.getSession(), rule.getUuid());
assertThat(es.countDocuments(TYPE_RULE)).isOne();
.flatMap(t -> CWES_BY_SQ_CATEGORY.get(t).stream().map(e -> "cwe:" + e))
.collect(toSet());
SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(standards);
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT)
.setSecurityStandards(standards)
.addRuleDescriptionSectionDto(RULE_DESCRIPTION_SECTION_DTO));
@Test
public void log_debug_when_hotspot_rule_no_description () {
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT));
underTest.commitAndIndex(dbTester.getSession(), rule.getUuid());
@Test
public void log_debug_when_hotspot_rule_description_has_none_of_the_key_titles() {
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), randomAlphabetic(30))));
underTest.commitAndIndex(dbTester.getSession(), rule.getUuid());
@Test
public void log_debug_when_hotspot_rule_description_is_missing_fixIt_tab_content() {
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "bar\n" +
"<h2>Ask Yourself Whether</h2>\n" +
@Test
public void log_debug_when_hotspot_rule_description_is_missing_risk_tab_content() {
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "<h2>Ask Yourself Whether</h2>\n" +
"bar\n" +
@Test
public void log_debug_when_hotspot_rule_description_is_missing_vulnerable_tab_content() {
- RuleDefinitionDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
+ RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection()
.setType(RuleType.SECURITY_HOTSPOT)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "bar\n" +
"<h2>Recommended Secure Coding Practices</h2>\n" +
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
return new Rule(rule.getKey(), RuleType.valueOfNullable(rule.getType()), rule.getName());
}
- public static Rule ruleOf(RuleDefinitionDto rule) {
- return new Rule(rule.getKey(), RuleType.valueOfNullable(rule.getType()), rule.getName());
- }
-
public static User userOf(UserDto changeAuthor) {
return new User(changeAuthor.getUuid(), changeAuthor.getLogin(), changeAuthor.getName());
}
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.rule.index.RuleQuery;
/**
* Delete a rule from all Quality profiles. Db session is not committed. As a
* consequence Elasticsearch indices are NOT updated.
*/
- List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDefinitionDto rule);
+ List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDto rule);
}
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import static java.util.Collections.emptyList;
*/
public class CachingRuleFinder implements ServerRuleFinder {
- private static final Ordering<Map.Entry<RuleDefinitionDto, Rule>> FIND_BY_QUERY_ORDER = Ordering.natural().reverse().onResultOf(entry -> entry.getKey().getUpdatedAt());
+ private static final Ordering<Map.Entry<RuleDto, Rule>> FIND_BY_QUERY_ORDER = Ordering.natural().reverse().onResultOf(entry -> entry.getKey().getUpdatedAt());
- private final Map<RuleKey, RuleDefinitionDto> ruleDtosByKey;
- private final Map<String, RuleDefinitionDto> ruleDtosByUuid;
- private final Map<RuleDefinitionDto, Rule> rulesByRuleDefinition;
+ private final Map<RuleKey, RuleDto> ruleDtosByKey;
+ private final Map<String, RuleDto> ruleDtosByUuid;
+ private final Map<RuleDto, Rule> ruleByRuleDto;
private final Map<RuleKey, Rule> rulesByKey;
public CachingRuleFinder(DbClient dbClient) {
try (DbSession dbSession = dbClient.openSession(false)) {
- List<RuleDefinitionDto> dtos = dbClient.ruleDao().selectAllDefinitions(dbSession);
- this.ruleDtosByKey = dtos.stream().collect(Collectors.toMap(RuleDefinitionDto::getKey, d -> d));
- this.ruleDtosByUuid = dtos.stream().collect(Collectors.toMap(RuleDefinitionDto::getUuid, d -> d));
- this.rulesByRuleDefinition = buildRulesByRuleDefinitionDto(dbClient, dbSession, dtos);
- this.rulesByKey = this.rulesByRuleDefinition.entrySet().stream()
+ List<RuleDto> dtos = dbClient.ruleDao().selectAll(dbSession);
+ this.ruleDtosByKey = dtos.stream().collect(Collectors.toMap(RuleDto::getKey, d -> d));
+ this.ruleDtosByUuid = dtos.stream().collect(Collectors.toMap(RuleDto::getUuid, d -> d));
+ this.ruleByRuleDto = buildRulesByRuleDefinitionDto(dbClient, dbSession, dtos);
+ this.rulesByKey = this.ruleByRuleDto.entrySet().stream()
.collect(uniqueIndex(entry -> entry.getKey().getKey(), Map.Entry::getValue));
}
}
- private static Map<RuleDefinitionDto, Rule> buildRulesByRuleDefinitionDto(DbClient dbClient, DbSession dbSession, List<RuleDefinitionDto> dtos) {
+ private static Map<RuleDto, Rule> buildRulesByRuleDefinitionDto(DbClient dbClient, DbSession dbSession, List<RuleDto> dtos) {
Map<String, List<RuleParamDto>> ruleParamsByRuleUuid = retrieveRuleParameters(dbClient, dbSession);
- Map<RuleDefinitionDto, Rule> rulesByDefinition = new HashMap<>(dtos.size());
- for (RuleDefinitionDto definition : dtos) {
+ Map<RuleDto, Rule> rulesByDefinition = new HashMap<>(dtos.size());
+ for (RuleDto definition : dtos) {
rulesByDefinition.put(definition, toRule(definition, ruleParamsByRuleUuid.getOrDefault(definition.getUuid(), emptyList())));
}
return unmodifiableMap(rulesByDefinition);
return null;
}
- return rulesByRuleDefinition.entrySet().stream()
+ return ruleByRuleDto.entrySet().stream()
.filter(entry -> matchQuery(entry.getKey(), query))
.sorted(FIND_BY_QUERY_ORDER)
.map(Map.Entry::getValue)
if (query == null) {
return Collections.emptyList();
}
- return rulesByRuleDefinition.entrySet().stream()
+ return ruleByRuleDto.entrySet().stream()
.filter(entry -> matchQuery(entry.getKey(), query))
.sorted(FIND_BY_QUERY_ORDER)
.map(Map.Entry::getValue)
.collect(MoreCollectors.toList());
}
- private static boolean matchQuery(RuleDefinitionDto ruleDefinition, RuleQuery ruleQuery) {
- if (RuleStatus.REMOVED.equals(ruleDefinition.getStatus())) {
+ private static boolean matchQuery(RuleDto ruleDto, RuleQuery ruleQuery) {
+ if (RuleStatus.REMOVED.equals(ruleDto.getStatus())) {
return false;
}
String repositoryKey = ruleQuery.getRepositoryKey();
- if (ruleQuery.getRepositoryKey() != null && !repositoryKey.equals(ruleDefinition.getRepositoryKey())) {
+ if (ruleQuery.getRepositoryKey() != null && !repositoryKey.equals(ruleDto.getRepositoryKey())) {
return false;
}
String key = ruleQuery.getKey();
- if (key != null && !key.equals(ruleDefinition.getRuleKey())) {
+ if (key != null && !key.equals(ruleDto.getRuleKey())) {
return false;
}
String configKey = ruleQuery.getConfigKey();
- return configKey == null || configKey.equals(ruleDefinition.getConfigKey());
+ return configKey == null || configKey.equals(ruleDto.getConfigKey());
}
- private static Rule toRule(RuleDefinitionDto ruleDefinition, List<RuleParamDto> params) {
- String severity = ruleDefinition.getSeverityString();
-
- Rule apiRule = new Rule();
- apiRule
- .setName(ruleDefinition.getName())
- .setLanguage(ruleDefinition.getLanguage())
- .setKey(ruleDefinition.getRuleKey())
- .setConfigKey(ruleDefinition.getConfigKey())
- .setIsTemplate(ruleDefinition.isTemplate())
- .setCreatedAt(new Date(ruleDefinition.getCreatedAt()))
- .setUpdatedAt(new Date(ruleDefinition.getUpdatedAt()))
- .setRepositoryKey(ruleDefinition.getRepositoryKey())
+ private static Rule toRule(RuleDto ruleDto, List<RuleParamDto> params) {
+ String severity = ruleDto.getSeverityString();
+
+ Rule apiRule = Rule.create()
+ .setName(ruleDto.getName())
+ .setKey(ruleDto.getRuleKey())
+ .setConfigKey(ruleDto.getConfigKey())
+ .setIsTemplate(ruleDto.isTemplate())
+ .setCreatedAt(new Date(ruleDto.getCreatedAt()))
+ .setUpdatedAt(new Date(ruleDto.getUpdatedAt()))
+ .setRepositoryKey(ruleDto.getRepositoryKey())
.setSeverity(severity != null ? RulePriority.valueOf(severity) : null)
- .setStatus(ruleDefinition.getStatus().name())
- .setSystemTags(ruleDefinition.getSystemTags().toArray(new String[ruleDefinition.getSystemTags().size()]))
+ .setStatus(ruleDto.getStatus().name())
+ .setSystemTags(ruleDto.getSystemTags().toArray(new String[ruleDto.getSystemTags().size()]))
.setTags(new String[0])
- .setDescription(RuleDescriptionFormatter.getDescriptionAsHtml(ruleDefinition));
+ .setDescription(RuleDescriptionFormatter.getDescriptionAsHtml(ruleDto));
+ Optional.ofNullable(ruleDto.getLanguage()).map(apiRule::setLanguage);
List<org.sonar.api.rules.RuleParam> apiParams = new ArrayList<>();
for (RuleParamDto param : params) {
}
@Override
- public Optional<RuleDefinitionDto> findDtoByKey(RuleKey key) {
+ public Optional<RuleDto> findDtoByKey(RuleKey key) {
return Optional.ofNullable(this.ruleDtosByKey.get(key));
}
@Override
- public Optional<RuleDefinitionDto> findDtoByUuid(String uuid) {
+ public Optional<RuleDto> findDtoByUuid(String uuid) {
return Optional.ofNullable(this.ruleDtosByUuid.get(uuid));
}
@Override
- public Collection<RuleDefinitionDto> findAll() {
+ public Collection<RuleDto> findAll() {
return ruleDtosByUuid.values();
}
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleQuery;
import org.sonar.db.DbClient;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
public class WebServerRuleFinderImpl implements WebServerRuleFinder {
private final DbClient dbClient;
}
@Override
- public Optional<RuleDefinitionDto> findDtoByKey(RuleKey key) {
+ public Optional<RuleDto> findDtoByKey(RuleKey key) {
return delegate.findDtoByKey(key);
}
@Override
- public Optional<RuleDefinitionDto> findDtoByUuid(String uuid) {
+ public Optional<RuleDto> findDtoByUuid(String uuid) {
return delegate.findDtoByUuid(uuid);
}
@Override
- public Collection<RuleDefinitionDto> findAll() {
+ public Collection<RuleDto> findAll() {
return delegate.findAll();
}
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDao;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
private final DbClient dbClient = dbTester.getDbClient();
private final AlwaysIncreasingSystem2 system2 = new AlwaysIncreasingSystem2();
- private RuleDefinitionDto[] ruleDefinitions;
+ private RuleDto[] ruleDtos;
private RuleParamDto[] ruleParams;
private CachingRuleFinder underTest;
@Before()
public void setUp() {
- Consumer<RuleDefinitionDto> setUpdatedAt = rule -> rule.setUpdatedAt(system2.now());
- this.ruleDefinitions = new RuleDefinitionDto[] {
+ Consumer<RuleDto> setUpdatedAt = rule -> rule.setUpdatedAt(system2.now());
+ this.ruleDtos = new RuleDto[] {
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt)
};
- this.ruleParams = Arrays.stream(ruleDefinitions)
+ this.ruleParams = Arrays.stream(ruleDtos)
.map(rule -> dbTester.rules().insertRuleParam(rule))
.toArray(RuleParamDto[]::new);
new CachingRuleFinder(dbClient);
verify(dbClient).openSession(anyBoolean());
- verify(ruleDao).selectAllDefinitions(dbSession);
+ verify(ruleDao).selectAll(dbSession);
verify(ruleDao).selectAllRuleParams(dbSession);
verifyNoMoreInteractions(ruleDao);
}
when(dbClient.openSession(anyBoolean())).thenReturn(dbSession);
when(dbClient.ruleDao()).thenReturn(ruleDao);
List<RuleKey> ruleKeys = Arrays.asList(RuleKey.of("A", "B"), RuleKey.of("C", "D"), RuleKey.of("E", "F"));
- when(ruleDao.selectAllDefinitions(dbSession)).thenReturn(ruleKeys.stream().map(RuleTesting::newRule).collect(toList()));
+ when(ruleDao.selectAll(dbSession)).thenReturn(ruleKeys.stream().map(RuleTesting::newRule).collect(toList()));
new CachingRuleFinder(dbClient);
@Test
public void findByKey_returns_all_loaded_rules() {
- for (int i = 0; i < ruleDefinitions.length; i++) {
- RuleDefinitionDto ruleDefinition = ruleDefinitions[i];
+ for (int i = 0; i < ruleDtos.length; i++) {
+ RuleDto ruleDto = ruleDtos[i];
RuleParamDto ruleParam = ruleParams[i];
- org.sonar.api.rules.Rule rule = underTest.findByKey(ruleDefinition.getKey());
- verifyRule(rule, ruleDefinition, ruleParam);
- assertThat(underTest.findByKey(ruleDefinition.getRepositoryKey(), ruleDefinition.getRuleKey()))
+ org.sonar.api.rules.Rule rule = underTest.findByKey(ruleDto.getKey());
+ verifyRule(rule, ruleDto, ruleParam);
+ assertThat(underTest.findByKey(ruleDto.getRepositoryKey(), ruleDto.getRuleKey()))
.isSameAs(rule);
}
}
public void find_returns_most_recent_rule_when_RuleQuery_has_no_non_null_field() {
Rule rule = underTest.find(RuleQuery.create());
- assertThat(toRuleKey(rule)).isEqualTo(ruleDefinitions[5].getKey());
+ assertThat(toRuleKey(rule)).isEqualTo(ruleDtos[5].getKey());
}
@Test
public void find_searches_by_exact_match_of_repository_key_and_returns_most_recent_rule() {
String repoKey = "ABCD";
- RuleDefinitionDto[] sameRepoKey = {
+ RuleDto[] sameRepoKey = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
@Test
public void find_searches_by_exact_match_of_ruleKey_and_returns_most_recent_rule() {
String ruleKey = "ABCD";
- RuleDefinitionDto[] sameRuleKey = {
+ RuleDto[] sameRuleKey = {
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
@Test
public void find_searches_by_exact_match_of_configKey_and_returns_most_recent_rule() {
String configKey = "ABCD";
- RuleDefinitionDto[] sameConfigKey = {
+ RuleDto[] sameConfigKey = {
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
String repoKey = "ABCD";
String ruleKey = "EFGH";
String configKey = "IJKL";
- RuleDefinitionDto[] rules = {
+ RuleDto[] rules = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
public void findAll_returns_all_rules_when_RuleQuery_has_no_non_null_field() {
assertThat(underTest.findAll(RuleQuery.create()))
.extracting(CachingRuleFinderTest::toRuleKey)
- .containsOnly(Arrays.stream(ruleDefinitions).map(RuleDefinitionDto::getKey).toArray(RuleKey[]::new));
+ .containsOnly(Arrays.stream(ruleDtos).map(RuleDto::getKey).toArray(RuleKey[]::new));
}
@Test
public void findAll_returns_all_rules_with_exact_same_repository_key_and_order_them_most_recent_first() {
String repoKey = "ABCD";
- RuleDefinitionDto[] sameRepoKey = {
- dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now())),
- dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now()))
+ long currentTimeMillis = System.currentTimeMillis();
+ RuleDto[] sameRepoKey = {
+ dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(currentTimeMillis + system2.now())),
+ dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(currentTimeMillis + system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(currentTimeMillis + system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
@Test
public void findAll_returns_all_rules_with_exact_same_rulekey_and_order_them_most_recent_first() {
String ruleKey = "ABCD";
- RuleDefinitionDto[] sameRuleKey = {
+ RuleDto[] sameRuleKey = {
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
@Test
public void findAll_returns_all_rules_with_exact_same_configkey_and_order_them_most_recent_first() {
String configKey = "ABCD";
- RuleDefinitionDto[] sameConfigKey = {
+ RuleDto[] sameConfigKey = {
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now()))
};
- RuleDefinitionDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
+ RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient);
String repoKey = "ABCD";
String ruleKey = "EFGH";
String configKey = "IJKL";
- RuleDefinitionDto[] rules = {
+ RuleDto[] rules = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
@Test
public void findDtoByKey_finds_rules() {
- for(RuleDefinitionDto dto : ruleDefinitions) {
+ for(RuleDto dto : ruleDtos) {
assertThat(underTest.findDtoByKey(dto.getKey())).contains(dto);
}
}
@Test
public void findDtoByUuid_finds_rules() {
- for(RuleDefinitionDto dto : ruleDefinitions) {
+ for(RuleDto dto : ruleDtos) {
assertThat(underTest.findDtoByUuid(dto.getUuid())).contains(dto);
}
}
@Test
public void findAll_returns_all_rules() {
- assertThat(underTest.findAll()).containsOnly(ruleDefinitions);
+ assertThat(underTest.findAll()).containsOnly(ruleDtos);
}
private static RuleKey toRuleKey(Rule rule) {
return RuleKey.of(rule.getRepositoryKey(), rule.getKey());
}
- private void verifyRule(@Nullable Rule rule, RuleDefinitionDto ruleDefinition, RuleParamDto ruleParam) {
+ private void verifyRule(@Nullable Rule rule, RuleDto ruleDto, RuleParamDto ruleParam) {
assertThat(rule).isNotNull();
- assertThat(rule.getName()).isEqualTo(ruleDefinition.getName());
- assertThat(rule.getLanguage()).isEqualTo(ruleDefinition.getLanguage());
- assertThat(rule.getKey()).isEqualTo(ruleDefinition.getRuleKey());
- assertThat(rule.getConfigKey()).isEqualTo(ruleDefinition.getConfigKey());
- assertThat(rule.isTemplate()).isEqualTo(ruleDefinition.isTemplate());
- assertThat(rule.getCreatedAt().getTime()).isEqualTo(ruleDefinition.getCreatedAt());
- assertThat(rule.getUpdatedAt().getTime()).isEqualTo(ruleDefinition.getUpdatedAt());
- assertThat(rule.getRepositoryKey()).isEqualTo(ruleDefinition.getRepositoryKey());
- assertThat(rule.getSeverity().name()).isEqualTo(ruleDefinition.getSeverityString());
- assertThat(rule.getSystemTags()).isEqualTo(ruleDefinition.getSystemTags().toArray(new String[0]));
+ assertThat(rule.getName()).isEqualTo(ruleDto.getName());
+ assertThat(rule.getLanguage()).isEqualTo(ruleDto.getLanguage());
+ assertThat(rule.getKey()).isEqualTo(ruleDto.getRuleKey());
+ assertThat(rule.getConfigKey()).isEqualTo(ruleDto.getConfigKey());
+ assertThat(rule.isTemplate()).isEqualTo(ruleDto.isTemplate());
+ assertThat(rule.getCreatedAt().getTime()).isEqualTo(ruleDto.getCreatedAt());
+ assertThat(rule.getUpdatedAt().getTime()).isEqualTo(ruleDto.getUpdatedAt());
+ assertThat(rule.getRepositoryKey()).isEqualTo(ruleDto.getRepositoryKey());
+ assertThat(rule.getSeverity().name()).isEqualTo(ruleDto.getSeverityString());
+ assertThat(rule.getSystemTags()).isEqualTo(ruleDto.getSystemTags().toArray(new String[0]));
assertThat(rule.getTags()).isEmpty();
- assertThat(rule.getDescription()).isEqualTo(ruleDefinition.getDefaultRuleDescriptionSectionDto().getContent());
+ assertThat(rule.getDescription()).isEqualTo(ruleDto.getDefaultRuleDescriptionSection().getContent());
assertThat(rule.getParams()).hasSize(1);
org.sonar.api.rules.RuleParam param = rule.getParams().iterator().next();
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.Startable;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Format;
import org.sonar.db.rule.RuleDto.Scope;
import org.sonar.db.rule.RuleParamDto;
persistRepositories(dbSession, ruleDefinitionContext.repositories());
// FIXME lack of resiliency, active rules index is corrupted if rule index fails
// to be updated. Only a single DB commit should be executed.
- ruleIndexer.commitAndIndex(dbSession, registerRulesContext.getAllModified().map(RuleDefinitionDto::getUuid).collect(toSet()));
+ ruleIndexer.commitAndIndex(dbSession, registerRulesContext.getAllModified().map(RuleDto::getUuid).collect(toSet()));
activeRuleIndexer.commitAndIndex(dbSession, changes);
registerRulesContext.getRenamed().forEach(e -> LOG.info("Rule {} re-keyed to {}", e.getValue(), e.getKey().getKey()));
profiler.stopDebug();
}
private RegisterRulesContext createRegisterRulesContext(DbSession dbSession) {
- Map<RuleKey, RuleDefinitionDto> allRules = dbClient.ruleDao().selectAllDefinitions(dbSession).stream()
- .collect(uniqueIndex(RuleDefinitionDto::getKey));
+ Map<RuleKey, RuleDto> allRules = dbClient.ruleDao().selectAll(dbSession).stream()
+ .collect(uniqueIndex(RuleDto::getKey));
Map<String, Set<SingleDeprecatedRuleKey>> existingDeprecatedKeysById = loadDeprecatedRuleKeys(dbSession);
Map<String, List<RuleParamDto>> ruleParamsByRuleUuid = loadAllRuleParameters(dbSession);
return new RegisterRulesContext(allRules, existingDeprecatedKeysById, ruleParamsByRuleUuid);
private static class RegisterRulesContext {
// initial immutable data
- private final Map<RuleKey, RuleDefinitionDto> dbRules;
- private final Set<RuleDefinitionDto> known;
+ private final Map<RuleKey, RuleDto> dbRules;
+ private final Set<RuleDto> known;
private final Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid;
private final Map<String, List<RuleParamDto>> ruleParamsByRuleUuid;
- private final Map<RuleKey, RuleDefinitionDto> dbRulesByDbDeprecatedKey;
+ private final Map<RuleKey, RuleDto> dbRulesByDbDeprecatedKey;
// mutable data
- private final Set<RuleDefinitionDto> created = new HashSet<>();
- private final Map<RuleDefinitionDto, RuleKey> renamed = new HashMap<>();
- private final Set<RuleDefinitionDto> updated = new HashSet<>();
- private final Set<RuleDefinitionDto> unchanged = new HashSet<>();
- private final Set<RuleDefinitionDto> removed = new HashSet<>();
+ private final Set<RuleDto> created = new HashSet<>();
+ private final Map<RuleDto, RuleKey> renamed = new HashMap<>();
+ private final Set<RuleDto> updated = new HashSet<>();
+ private final Set<RuleDto> unchanged = new HashSet<>();
+ private final Set<RuleDto> removed = new HashSet<>();
- private RegisterRulesContext(Map<RuleKey, RuleDefinitionDto> dbRules, Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid,
+ private RegisterRulesContext(Map<RuleKey, RuleDto> dbRules, Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid,
Map<String, List<RuleParamDto>> ruleParamsByRuleUuid) {
this.dbRules = ImmutableMap.copyOf(dbRules);
this.known = ImmutableSet.copyOf(dbRules.values());
this.dbRulesByDbDeprecatedKey = buildDbRulesByDbDeprecatedKey(dbDeprecatedKeysByUuid, dbRules);
}
- private static Map<RuleKey, RuleDefinitionDto> buildDbRulesByDbDeprecatedKey(Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid,
- Map<RuleKey, RuleDefinitionDto> dbRules) {
- Map<String, RuleDefinitionDto> dbRulesByRuleUuid = dbRules.values().stream()
- .collect(uniqueIndex(RuleDefinitionDto::getUuid));
+ private static Map<RuleKey, RuleDto> buildDbRulesByDbDeprecatedKey(Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid,
+ Map<RuleKey, RuleDto> dbRules) {
+ Map<String, RuleDto> dbRulesByRuleUuid = dbRules.values().stream()
+ .collect(uniqueIndex(RuleDto::getUuid));
- Map<RuleKey, RuleDefinitionDto> rulesByKey = new LinkedHashMap<>();
+ Map<RuleKey, RuleDto> rulesByKey = new LinkedHashMap<>();
for (Map.Entry<String, Set<SingleDeprecatedRuleKey>> entry : dbDeprecatedKeysByUuid.entrySet()) {
String ruleUuid = entry.getKey();
- RuleDefinitionDto rule = dbRulesByRuleUuid.get(ruleUuid);
+ RuleDto rule = dbRulesByRuleUuid.get(ruleUuid);
if (rule == null) {
LOG.warn("Could not retrieve rule with uuid %s referenced by a deprecated rule key. " +
"The following deprecated rule keys seem to be referencing a non-existing rule",
return !dbRules.isEmpty();
}
- private Optional<RuleDefinitionDto> getDbRuleFor(RulesDefinition.Rule ruleDef) {
+ private Optional<RuleDto> getDbRuleFor(RulesDefinition.Rule ruleDef) {
RuleKey ruleKey = RuleKey.of(ruleDef.repository().key(), ruleDef.key());
- Optional<RuleDefinitionDto> res = Stream.concat(Stream.of(ruleKey), ruleDef.deprecatedRuleKeys().stream())
+ Optional<RuleDto> res = Stream.concat(Stream.of(ruleKey), ruleDef.deprecatedRuleKeys().stream())
.map(dbRules::get)
.filter(Objects::nonNull)
.findFirst();
.collect(uniqueIndex(SingleDeprecatedRuleKey::getOldRuleKeyAsRuleKey));
}
- private Set<SingleDeprecatedRuleKey> getDBDeprecatedKeysFor(RuleDefinitionDto rule) {
+ private Set<SingleDeprecatedRuleKey> getDBDeprecatedKeysFor(RuleDto rule) {
return dbDeprecatedKeysByUuid.getOrDefault(rule.getUuid(), emptySet());
}
return ruleParamsByRuleUuid.getOrDefault(ruleUuid, emptyList());
}
- private Stream<RuleDefinitionDto> getRemaining() {
- Set<RuleDefinitionDto> res = new HashSet<>(dbRules.values());
+ private Stream<RuleDto> getRemaining() {
+ Set<RuleDto> res = new HashSet<>(dbRules.values());
res.removeAll(unchanged);
res.removeAll(renamed.keySet());
res.removeAll(updated);
return res.stream();
}
- private Stream<RuleDefinitionDto> getRemoved() {
+ private Stream<RuleDto> getRemoved() {
return removed.stream();
}
- public Stream<Map.Entry<RuleDefinitionDto, RuleKey>> getRenamed() {
+ public Stream<Map.Entry<RuleDto, RuleKey>> getRenamed() {
return renamed.entrySet().stream();
}
- private Stream<RuleDefinitionDto> getAllModified() {
+ private Stream<RuleDto> getAllModified() {
return Stream.of(
created.stream(),
updated.stream(),
.flatMap(s -> s);
}
- private boolean isCreated(RuleDefinitionDto ruleDefinition) {
- return created.contains(ruleDefinition);
+ private boolean isCreated(RuleDto ruleDto) {
+ return created.contains(ruleDto);
}
- private boolean isRenamed(RuleDefinitionDto ruleDefinition) {
- return renamed.containsKey(ruleDefinition);
+ private boolean isRenamed(RuleDto ruleDto) {
+ return renamed.containsKey(ruleDto);
}
- private boolean isUpdated(RuleDefinitionDto ruleDefinition) {
- return updated.contains(ruleDefinition);
+ private boolean isUpdated(RuleDto ruleDto) {
+ return updated.contains(ruleDto);
}
- private void created(RuleDefinitionDto ruleDefinition) {
- checkState(!known.contains(ruleDefinition), "known RuleDefinitionDto can't be created");
- created.add(ruleDefinition);
+ private void created(RuleDto ruleDto) {
+ checkState(!known.contains(ruleDto), "known RuleDto can't be created");
+ created.add(ruleDto);
}
- private void renamed(RuleDefinitionDto ruleDefinition) {
- ensureKnown(ruleDefinition);
- renamed.put(ruleDefinition, ruleDefinition.getKey());
+ private void renamed(RuleDto ruleDto) {
+ ensureKnown(ruleDto);
+ renamed.put(ruleDto, ruleDto.getKey());
}
- private void updated(RuleDefinitionDto ruleDefinition) {
- ensureKnown(ruleDefinition);
- updated.add(ruleDefinition);
+ private void updated(RuleDto ruleDto) {
+ ensureKnown(ruleDto);
+ updated.add(ruleDto);
}
- private void removed(RuleDefinitionDto ruleDefinition) {
- ensureKnown(ruleDefinition);
- removed.add(ruleDefinition);
+ private void removed(RuleDto ruleDto) {
+ ensureKnown(ruleDto);
+ removed.add(ruleDto);
}
- private void unchanged(RuleDefinitionDto ruleDefinition) {
- ensureKnown(ruleDefinition);
- unchanged.add(ruleDefinition);
+ private void unchanged(RuleDto ruleDto) {
+ ensureKnown(ruleDto);
+ unchanged.add(ruleDto);
}
- private void ensureKnown(RuleDefinitionDto ruleDefinition) {
- checkState(known.contains(ruleDefinition), "unknown RuleDefinitionDto");
+ private void ensureKnown(RuleDto ruleDto) {
+ checkState(known.contains(ruleDto), "unknown RuleDto");
}
}
}
private void registerRules(RegisterRulesContext context, List<RulesDefinition.Rule> ruleDefs, DbSession session) {
- Map<RulesDefinition.Rule, RuleDefinitionDto> dtos = new LinkedHashMap<>(ruleDefs.size());
+ Map<RulesDefinition.Rule, RuleDto> dtos = new LinkedHashMap<>(ruleDefs.size());
for (RulesDefinition.Rule ruleDef : ruleDefs) {
RuleKey ruleKey = RuleKey.of(ruleDef.repository().key(), ruleDef.key());
-
- RuleDefinitionDto ruleDefinitionDto = context.getDbRuleFor(ruleDef)
- .orElseGet(() -> {
- RuleDefinitionDto newRule = createRuleDto(ruleDef, session);
- context.created(newRule);
- return newRule;
- });
- dtos.put(ruleDef, ruleDefinitionDto);
+ RuleDto ruleDto = findOrCreateRuleDto(context, session, ruleDef);
+ dtos.put(ruleDef, ruleDto);
// we must detect renaming __before__ we modify the DTO
- if (!ruleDefinitionDto.getKey().equals(ruleKey)) {
- context.renamed(ruleDefinitionDto);
- ruleDefinitionDto.setRuleKey(ruleKey);
- }
-
- if (mergeRule(ruleDef, ruleDefinitionDto)) {
- context.updated(ruleDefinitionDto);
- }
-
- if (mergeDebtDefinitions(ruleDef, ruleDefinitionDto)) {
- context.updated(ruleDefinitionDto);
- }
-
- if (mergeTags(ruleDef, ruleDefinitionDto)) {
- context.updated(ruleDefinitionDto);
+ if (!ruleDto.getKey().equals(ruleKey)) {
+ context.renamed(ruleDto);
+ ruleDto.setRuleKey(ruleKey);
}
- if (mergeSecurityStandards(ruleDef, ruleDefinitionDto)) {
- context.updated(ruleDefinitionDto);
+ if (anyMerge(ruleDef, ruleDto)) {
+ context.updated(ruleDto);
}
- if (context.isUpdated(ruleDefinitionDto) || context.isRenamed(ruleDefinitionDto)) {
- update(session, ruleDefinitionDto);
- } else if (!context.isCreated(ruleDefinitionDto)) {
- context.unchanged(ruleDefinitionDto);
+ if (context.isUpdated(ruleDto) || context.isRenamed(ruleDto)) {
+ update(session, ruleDto);
+ } else if (!context.isCreated(ruleDto)) {
+ context.unchanged(ruleDto);
}
}
- for (Map.Entry<RulesDefinition.Rule, RuleDefinitionDto> e : dtos.entrySet()) {
+ for (Map.Entry<RulesDefinition.Rule, RuleDto> e : dtos.entrySet()) {
mergeParams(context, e.getKey(), e.getValue(), session);
updateDeprecatedKeys(context, e.getKey(), e.getValue(), session);
}
}
- private RuleDefinitionDto createRuleDto(RulesDefinition.Rule ruleDef, DbSession session) {
- RuleDefinitionDto ruleDto = new RuleDefinitionDto()
+ @Nonnull
+ private RuleDto findOrCreateRuleDto(RegisterRulesContext context, DbSession session, RulesDefinition.Rule ruleDef) {
+ return context.getDbRuleFor(ruleDef)
+ .orElseGet(() -> {
+ RuleDto newRule = createRuleDto(ruleDef, session);
+ context.created(newRule);
+ return newRule;
+ });
+ }
+
+ private RuleDto createRuleDto(RulesDefinition.Rule ruleDef, DbSession session) {
+ RuleDto ruleDto = new RuleDto()
.setUuid(uuidFactory.create())
.setRuleKey(RuleKey.of(ruleDef.repository().key(), ruleDef.key()))
.setPluginKey(ruleDef.pluginKey())
}
}
- private boolean mergeRule(RulesDefinition.Rule def, RuleDefinitionDto dto) {
+ private boolean anyMerge(RulesDefinition.Rule ruleDef, RuleDto ruleDto) {
+ boolean ruleMerged = mergeRule(ruleDef, ruleDto);
+ boolean debtDefinitionsMerged = mergeDebtDefinitions(ruleDef, ruleDto);
+ boolean tagsMerged = mergeTags(ruleDef, ruleDto);
+ boolean securityStandardsMerged = mergeSecurityStandards(ruleDef, ruleDto);
+ return ruleMerged || debtDefinitionsMerged || tagsMerged || securityStandardsMerged;
+ }
+
+ private boolean mergeRule(RulesDefinition.Rule def, RuleDto dto) {
boolean changed = false;
if (!Objects.equals(dto.getName(), def.name())) {
dto.setName(def.name());
return changed;
}
- private boolean mergeDescription(RulesDefinition.Rule rule, RuleDefinitionDto ruleDefinitionDto) {
+ private boolean mergeDescription(RulesDefinition.Rule rule, RuleDto ruleDto) {
boolean changed = false;
- String currentDescription = Optional.ofNullable(ruleDefinitionDto.getDefaultRuleDescriptionSectionDto())
+ String currentDescription = Optional.ofNullable(ruleDto.getDefaultRuleDescriptionSection())
.map(RuleDescriptionSectionDto::getContent)
.orElse(null);
String htmlDescription = rule.htmlDescription();
String markdownDescription = rule.markdownDescription();
if (isDescriptionUpdated(htmlDescription, currentDescription)) {
- ruleDefinitionDto.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), htmlDescription));
- ruleDefinitionDto.setDescriptionFormat(Format.HTML);
+ ruleDto.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), htmlDescription));
+ ruleDto.setDescriptionFormat(Format.HTML);
changed = true;
} else if (isDescriptionUpdated(markdownDescription, currentDescription)) {
- ruleDefinitionDto.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), markdownDescription));
- ruleDefinitionDto.setDescriptionFormat(Format.MARKDOWN);
+ ruleDto.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), markdownDescription));
+ ruleDto.setDescriptionFormat(Format.MARKDOWN);
changed = true;
}
return changed;
return isNotEmpty(description) && !Objects.equals(description, currentDescription);
}
- private static boolean mergeDebtDefinitions(RulesDefinition.Rule def, RuleDefinitionDto dto) {
+ private static boolean mergeDebtDefinitions(RulesDefinition.Rule def, RuleDto dto) {
// Debt definitions are set to null if the sub-characteristic and the remediation function are null
DebtRemediationFunction debtRemediationFunction = def.debtRemediationFunction();
boolean hasDebt = debtRemediationFunction != null;
return mergeDebtDefinitions(dto, null, null, null, null);
}
- private static boolean mergeDebtDefinitions(RuleDefinitionDto dto, @Nullable String remediationFunction,
+ private static boolean mergeDebtDefinitions(RuleDto dto, @Nullable String remediationFunction,
@Nullable String remediationCoefficient, @Nullable String remediationOffset, @Nullable String effortToFixDescription) {
boolean changed = false;
return changed;
}
- private void mergeParams(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDefinitionDto rule, DbSession session) {
+ private void mergeParams(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDto rule, DbSession session) {
List<RuleParamDto> paramDtos = context.getRuleParametersFor(rule.getUuid());
Map<String, RuleParamDto> existingParamsByName = new HashMap<>();
return changed;
}
- private void updateDeprecatedKeys(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDefinitionDto rule, DbSession dbSession) {
+ private void updateDeprecatedKeys(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDto rule, DbSession dbSession) {
Set<SingleDeprecatedRuleKey> deprecatedRuleKeysFromDefinition = SingleDeprecatedRuleKey.from(ruleDef);
Set<SingleDeprecatedRuleKey> deprecatedRuleKeysFromDB = context.getDBDeprecatedKeysFor(rule);
.setCreatedAt(system2.now())));
}
- private static boolean mergeTags(RulesDefinition.Rule ruleDef, RuleDefinitionDto dto) {
+ private static boolean mergeTags(RulesDefinition.Rule ruleDef, RuleDto dto) {
boolean changed = false;
if (RuleStatus.REMOVED == ruleDef.status()) {
return changed;
}
- private static boolean mergeSecurityStandards(RulesDefinition.Rule ruleDef, RuleDefinitionDto dto) {
+ private static boolean mergeSecurityStandards(RulesDefinition.Rule ruleDef, RuleDto dto) {
boolean changed = false;
if (RuleStatus.REMOVED == ruleDef.status()) {
private void processRemainingDbRules(RegisterRulesContext recorder, DbSession dbSession) {
// custom rules check status of template, so they must be processed at the end
- List<RuleDefinitionDto> customRules = new ArrayList<>();
+ List<RuleDto> customRules = new ArrayList<>();
recorder.getRemaining().forEach(rule -> {
if (rule.isCustomRule()) {
}
});
- for (RuleDefinitionDto customRule : customRules) {
+ for (RuleDto customRule : customRules) {
String templateUuid = customRule.getTemplateUuid();
checkNotNull(templateUuid, "Template uuid of the custom rule '%s' is null", customRule);
- Optional<RuleDefinitionDto> template = dbClient.ruleDao().selectDefinitionByUuid(templateUuid, dbSession);
+ Optional<RuleDto> template = dbClient.ruleDao().selectByUuid(templateUuid, dbSession);
if (template.isPresent() && template.get().getStatus() != RuleStatus.REMOVED) {
if (updateCustomRuleFromTemplateRule(customRule, template.get())) {
recorder.updated(customRule);
dbSession.commit();
}
- private void removeRule(DbSession session, RegisterRulesContext recorder, RuleDefinitionDto rule) {
+ private void removeRule(DbSession session, RegisterRulesContext recorder, RuleDto rule) {
LOG.info(format("Disable rule %s", rule.getKey()));
rule.setStatus(RuleStatus.REMOVED);
rule.setSystemTags(emptySet());
}
}
- private static boolean updateCustomRuleFromTemplateRule(RuleDefinitionDto customRule, RuleDefinitionDto templateRule) {
+ private static boolean updateCustomRuleFromTemplateRule(RuleDto customRule, RuleDto templateRule) {
boolean changed = false;
if (!Objects.equals(customRule.getLanguage(), templateRule.getLanguage())) {
customRule.setLanguage(templateRule.getLanguage());
return changes;
}
- private void update(DbSession session, RuleDefinitionDto rule) {
+ private void update(DbSession session, RuleDto rule) {
rule.setUpdatedAt(system2.now());
dbClient.ruleDao().update(session, rule);
}
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
execute(new FakeRepositoryV1());
// verify db
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(3);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3);
RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1);
- assertThat(rule1.getName()).isEqualTo("One");
- assertThat(rule1.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Description of One");
- assertThat(rule1.getSeverityString()).isEqualTo(BLOCKER);
- assertThat(rule1.getTags()).isEmpty();
- assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3");
- assertThat(rule1.getConfigKey()).isEqualTo("config1");
- assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA);
- assertThat(rule1.getCreatedAt()).isEqualTo(DATE1.getTime());
- assertThat(rule1.getScope()).isEqualTo(Scope.ALL);
- assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1.getTime());
+ verifyRule(rule1);
+ assertThat(rule1.isExternal()).isFalse();
assertThat(rule1.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(rule1.getDefRemediationGapMultiplier()).isEqualTo("5d");
assertThat(rule1.getDefRemediationBaseEffort()).isEqualTo("10h");
- assertThat(rule1.getType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
- assertThat(rule1.getPluginKey()).isEqualTo(FAKE_PLUGIN_KEY);
- assertThat(rule1.isExternal()).isFalse();
- assertThat(rule1.isAdHoc()).isFalse();
RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), HOTSPOT_RULE_KEY);
- assertThat(hotspotRule.getName()).isEqualTo("Hotspot");
- assertThat(hotspotRule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Minimal hotspot");
- assertThat(hotspotRule.getCreatedAt()).isEqualTo(DATE1.getTime());
- assertThat(hotspotRule.getUpdatedAt()).isEqualTo(DATE1.getTime());
- assertThat(hotspotRule.getType()).isEqualTo(RuleType.SECURITY_HOTSPOT.getDbConstant());
- assertThat(hotspotRule.getSecurityStandards()).containsExactly("cwe:1", "cwe:123", "cwe:863", "owaspTop10-2021:a1", "owaspTop10-2021:a3");
+ verifyHotspot(hotspotRule);
List<RuleParamDto> params = dbClient.ruleDao().selectRuleParamsByRuleKey(db.getSession(), RULE_KEY1);
assertThat(params).hasSize(2);
assertThat(dbClient.ruleRepositoryDao().selectAll(db.getSession())).extracting(RuleRepositoryDto::getKey).containsOnly("fake");
}
+ private void verifyHotspot(RuleDto hotspotRule) {
+ assertThat(hotspotRule.getName()).isEqualTo("Hotspot");
+ assertThat(hotspotRule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Minimal hotspot");
+ assertThat(hotspotRule.getCreatedAt()).isEqualTo(RegisterRulesTest.DATE1.getTime());
+ assertThat(hotspotRule.getUpdatedAt()).isEqualTo(RegisterRulesTest.DATE1.getTime());
+ assertThat(hotspotRule.getType()).isEqualTo(RuleType.SECURITY_HOTSPOT.getDbConstant());
+ assertThat(hotspotRule.getSecurityStandards()).containsExactly("cwe:1", "cwe:123", "cwe:863", "owaspTop10-2021:a1", "owaspTop10-2021:a3");
+ }
+
@Test
public void insert_new_external_rule() {
execute(new ExternalRuleRepository());
// verify db
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(2);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(2);
RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), EXTERNAL_RULE_KEY1);
- assertThat(rule1.getName()).isEqualTo("One");
- assertThat(rule1.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Description of One");
- assertThat(rule1.getSeverityString()).isEqualTo(BLOCKER);
- assertThat(rule1.getTags()).isEmpty();
- assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3");
- assertThat(rule1.getConfigKey()).isEqualTo("config1");
- assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA);
- assertThat(rule1.getCreatedAt()).isEqualTo(DATE1.getTime());
- assertThat(rule1.getScope()).isEqualTo(Scope.ALL);
- assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1.getTime());
+ verifyRule(rule1);
+ assertThat(rule1.isExternal()).isTrue();
assertThat(rule1.getDefRemediationFunction()).isNull();
assertThat(rule1.getDefRemediationGapMultiplier()).isNull();
assertThat(rule1.getDefRemediationBaseEffort()).isNull();
- assertThat(rule1.getType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
- assertThat(rule1.getPluginKey()).isEqualTo(FAKE_PLUGIN_KEY);
- assertThat(rule1.isExternal()).isTrue();
- assertThat(rule1.isAdHoc()).isFalse();
RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), EXTERNAL_HOTSPOT_RULE_KEY);
- assertThat(hotspotRule.getName()).isEqualTo("Hotspot");
- assertThat(hotspotRule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Minimal hotspot");
- assertThat(hotspotRule.getCreatedAt()).isEqualTo(DATE1.getTime());
- assertThat(hotspotRule.getUpdatedAt()).isEqualTo(DATE1.getTime());
- assertThat(hotspotRule.getType()).isEqualTo(RuleType.SECURITY_HOTSPOT.getDbConstant());
- assertThat(hotspotRule.getSecurityStandards()).containsExactly("cwe:1", "cwe:123", "cwe:863", "owaspTop10-2021:a1", "owaspTop10-2021:a3");
+ verifyHotspot(hotspotRule);
+ }
+
+
+ private void verifyRule(RuleDto rule) {
+ assertThat(rule.getName()).isEqualTo("One");
+ assertThat(rule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Description of One");
+ assertThat(rule.getSeverityString()).isEqualTo(BLOCKER);
+ assertThat(rule.getTags()).isEmpty();
+ assertThat(rule.getSystemTags()).containsOnly("tag1", "tag2", "tag3");
+ assertThat(rule.getConfigKey()).isEqualTo("config1");
+ assertThat(rule.getStatus()).isEqualTo(RuleStatus.BETA);
+ assertThat(rule.getCreatedAt()).isEqualTo(DATE1.getTime());
+ assertThat(rule.getScope()).isEqualTo(Scope.ALL);
+ assertThat(rule.getUpdatedAt()).isEqualTo(DATE1.getTime());
+ assertThat(rule.getType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
+ assertThat(rule.getPluginKey()).isEqualTo(FAKE_PLUGIN_KEY);
+ assertThat(rule.isAdHoc()).isFalse();
}
@Test
});
// verify db
- List<RuleDefinitionDto> rules = dbClient.ruleDao().selectAllDefinitions(db.getSession());
+ List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession());
assertThat(rules)
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.extracting(RuleKey::rule)
.containsExactly(ruleKey);
- RuleDefinitionDto rule = rules.iterator().next();
+ RuleDto rule = rules.iterator().next();
// verify index
assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids())
execute(context -> context.createRepository("fake", "java").done());
// verify db
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession()))
- .extracting(RuleDefinitionDto::getKey)
+ assertThat(dbClient.ruleDao().selectAll(db.getSession()))
+ .extracting(RuleDto::getKey)
.extracting(RuleKey::rule)
.containsExactly(ruleKey);
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession()))
- .extracting(RuleDefinitionDto::getStatus)
+ assertThat(dbClient.ruleDao().selectAll(db.getSession()))
+ .extracting(RuleDto::getStatus)
.containsExactly(REMOVED);
// verify index
});
// verify db
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession()))
+ assertThat(dbClient.ruleDao().selectAll(db.getSession()))
.hasSize(numberOfRules)
- .extracting(RuleDefinitionDto::getStatus)
+ .extracting(RuleDto::getStatus)
.containsOnly(READY);
// verify index
execute(context -> context.createRepository("fake", "java").done());
// verify db
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession()))
+ assertThat(dbClient.ruleDao().selectAll(db.getSession()))
.hasSize(numberOfRules)
- .extracting(RuleDefinitionDto::getStatus)
+ .extracting(RuleDto::getStatus)
.containsOnly(REMOVED);
// verify index (documents are still in the index, but all are removed)
@Test
public void update_and_remove_rules_on_changes() {
execute(new FakeRepositoryV1());
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(3);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3);
RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1);
RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2);
RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), HOTSPOT_RULE_KEY);
rule1.setTags(newHashSet("usertag1", "usertag2"));
rule1.setNoteData("user *note*");
rule1.setNoteUserUuid("marius");
- dbClient.ruleDao().insertOrUpdate(db.getSession(), rule1.getMetadata());
+ dbClient.ruleDao().update(db.getSession(), rule1);
db.getSession().commit();
system.setNow(DATE2.getTime());
RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("squid", "rule"));
// insert custom rule
- db.rules().insert(new RuleDefinitionDto()
+ db.rules().insert(new RuleDto()
.setRuleKey(RuleKey.of("squid", "custom"))
.setLanguage("java")
.setScope(Scope.ALL)
@Test
public void rule_previously_created_as_adhoc_becomes_none_adhoc() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake").setIsExternal(true).setIsAdHoc(true));
+ RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake").setIsExternal(true).setIsAdHoc(true));
system.setNow(DATE2.getTime());
execute(context -> {
NewRepository repo = context.createExternalRepository("fake", rule.getLanguage());
repo.createRule(rule.getRuleKey())
.setName(rule.getName())
- .setHtmlDescription(rule.getDefaultRuleDescriptionSectionDto().getContent());
+ .setHtmlDescription(rule.getDefaultRuleDescriptionSection().getContent());
repo.done();
});
@Test
public void remove_no_more_defined_external_rule() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake")
+ RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake")
.setStatus(READY)
.setIsExternal(true)
.setIsAdHoc(false));
@Test
public void do_not_remove_no_more_defined_ad_hoc_rule() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake")
+ RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake")
.setStatus(READY)
.setIsExternal(true)
.setIsAdHoc(true));
@Test
public void do_not_update_rules_when_no_changes() {
execute(new FakeRepositoryV1());
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(3);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3);
system.setNow(DATE2.getTime());
execute(new FakeRepositoryV1());
@Test
public void do_not_update_already_removed_rules() {
execute(new FakeRepositoryV1());
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(3);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3);
RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1);
RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2);
execute(new FakeRepositoryV2());
// On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ???
- dbClient.ruleDao().update(db.getSession(), rule1.getDefinition());
+ dbClient.ruleDao().update(db.getSession(), rule1);
db.getSession().commit();
// rule2 is removed
@Test
public void manage_repository_extensions() {
execute(new FindbugsRepository(), new FbContribRepository());
- List<RuleDefinitionDto> rules = dbClient.ruleDao().selectAllDefinitions(db.getSession());
+ List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession());
assertThat(rules).hasSize(2);
- for (RuleDefinitionDto rule : rules) {
+ for (RuleDto rule : rules) {
assertThat(rule.getRepositoryKey()).isEqualTo("findbugs");
}
}
@Test
public void remove_system_tags_when_plugin_does_not_provide_any() {
// Rule already exists in DB, with some system tags
- db.rules().insert(new RuleDefinitionDto()
+ db.rules().insert(new RuleDto()
.setRuleKey("rule1")
.setRepositoryKey("findbugs")
.setName("Rule One")
// Synchronize rule without tag
execute(new FindbugsRepository());
- List<RuleDefinitionDto> rules = dbClient.ruleDao().selectAllDefinitions(db.getSession());
- assertThat(rules).hasSize(1).extracting(RuleDefinitionDto::getKey, RuleDefinitionDto::getSystemTags)
+ List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession());
+ assertThat(rules).hasSize(1).extracting(RuleDto::getKey, RuleDto::getSystemTags)
.containsOnly(tuple(RuleKey.of("findbugs", "rule1"), emptySet()));
}
repo.done();
});
- List<RuleDefinitionDto> rules = dbClient.ruleDao().selectAllDefinitions(db.getSession());
+ List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession());
Set<DeprecatedRuleKeyDto> deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession());
assertThat(rules).hasSize(1);
assertThat(deprecatedRuleKeys).hasSize(2);
repo.done();
});
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(1);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(1);
Set<DeprecatedRuleKeyDto> deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession());
assertThat(deprecatedRuleKeys).hasSize(2);
repo.done();
});
- assertThat(dbClient.ruleDao().selectAllDefinitions(db.getSession())).hasSize(1);
+ assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(1);
deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession());
assertThat(deprecatedRuleKeys).isEmpty();
}
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
private final Collection<String> directories;
private final Collection<String> files;
private final Collection<String> views;
- private final Collection<RuleDefinitionDto> rules;
+ private final Collection<RuleDto> rules;
private final Collection<String> ruleUuids;
private final Collection<String> assignees;
private final Collection<String> authors;
return views;
}
- public Collection<RuleDefinitionDto> rules() {
+ public Collection<RuleDto> rules() {
return rules;
}
private Collection<String> directories;
private Collection<String> files;
private Collection<String> views;
- private Collection<RuleDefinitionDto> rules;
+ private Collection<RuleDto> rules;
private Collection<String> ruleUuids;
private Collection<String> assigneeUuids;
private Collection<String> authors;
return this;
}
- public Builder rules(@Nullable Collection<RuleDefinitionDto> rules) {
+ public Builder rules(@Nullable Collection<RuleDto> rules) {
this.rules = rules;
return this;
}
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.issue.index.IssueQuery.PeriodStart;
import org.sonar.server.user.UserSession;
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
- Collection<RuleDefinitionDto> ruleDefinitionDtos = ruleKeysToRuleId(dbSession, request.getRules());
- Collection<String> ruleUuids = ruleDefinitionDtos.stream().map(RuleDefinitionDto::getUuid).collect(Collectors.toSet());
+ Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
+ Collection<String> ruleUuids = ruleDtos.stream().map(RuleDto::getUuid).collect(Collectors.toSet());
- if (request.getRules() != null && request.getRules().stream().collect(toSet()).size() != ruleDefinitionDtos.size()) {
+ if (request.getRules() != null && request.getRules().stream().collect(toSet()).size() != ruleDtos.size()) {
ruleUuids.add("non-existing-uuid");
}
.statuses(request.getStatuses())
.resolutions(request.getResolutions())
.resolved(request.getResolved())
- .rules(ruleDefinitionDtos)
+ .rules(ruleDtos)
.ruleUuids(ruleUuids)
.assigneeUuids(request.getAssigneeUuids())
.authors(request.getAuthors())
return componentDtos;
}
- private Collection<RuleDefinitionDto> ruleKeysToRuleId(DbSession dbSession, @Nullable Collection<String> rules) {
+ private Collection<RuleDto> ruleKeysToRuleId(DbSession dbSession, @Nullable Collection<String> rules) {
if (rules != null) {
- return dbClient.ruleDao().selectDefinitionByKeys(dbSession, transform(rules, RuleKey::parse));
+ return dbClient.ruleDao().selectByKeys(dbSession, transform(rules, RuleKey::parse));
}
return Collections.emptyList();
}
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
public void facets_on_languages() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project, null);
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", file).setRuleUuid(ruleDefinitionDto.getUuid()).setLanguage("xoo"));
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.permission.index.IndexPermissions;
public void filter_by_rules() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project, null);
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", file).setRuleUuid(ruleDefinitionDto.getUuid()));
public void filter_by_languages() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project, null);
- RuleDefinitionDto ruleDefinitionDto = newRule();
+ RuleDto ruleDefinitionDto = newRule();
db.rules().insert(ruleDefinitionDto);
indexIssues(newDoc("I1", file).setRuleUuid(ruleDefinitionDto.getUuid()).setLanguage("xoo"));
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
@Test
public void list_tags() {
- RuleDefinitionDto r1 = db.rules().insert();
- RuleDefinitionDto r2 = db.rules().insert();
+ RuleDto r1 = db.rules().insert();
+ RuleDto r2 = db.rules().insert();
ruleIndexer.commitAndIndex(db.getSession(), asList(r1.getUuid(), r2.getUuid()));
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project, null);
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.rule.RuleDbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.SearchRequest;
import org.sonar.server.tester.UserSessionRule;
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = ruleDbTester.insert();
- RuleDefinitionDto rule2 = ruleDbTester.insert();
+ RuleDto rule1 = ruleDbTester.insert();
+ RuleDto rule2 = ruleDbTester.insert();
ruleDbTester.insertOrUpdateMetadata(rule1, m -> m.setAdHocName(ruleAdHocName));
ruleDbTester.insertOrUpdateMetadata(rule2, m -> m.setAdHocName(ruleAdHocName));
newRule(RuleKey.of("findbugs", "NullReference"));
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.Severity;
import org.sonar.core.util.Uuids;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.index.IssueQuery.PeriodStart;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void build_query() {
- RuleDefinitionDto rule = new RuleDefinitionDto().setUuid(Uuids.createFast());
+ RuleDto rule = new RuleDto().setUuid(Uuids.createFast());
PeriodStart filterDate = new IssueQuery.PeriodStart(new Date(10_000_000_000L), false);
IssueQuery query = IssueQuery.builder()
.issueKeys(List.of("ABCDE"))
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventServiceImpl;
// Template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("xoo", "template-key"));
- db.rules().insert(templateRule.getDefinition());
+ db.rules().insert(templateRule);
// Custom rule
- RuleDefinitionDto rule1 = newCustomRule(templateRule.getDefinition())
+ RuleDto rule1 = newCustomRule(templateRule)
.setLanguage("xoo")
.setRepositoryKey("repo")
.setRuleKey("ruleKey")
QProfileDto activatedQualityProfile = QualityProfileTesting.newQualityProfileDto();
activatedQualityProfile.setLanguage("xoo");
db.qualityProfiles().insert(activatedQualityProfile);
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo").setRuleKey("ruleKey"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo").setRuleKey("ruleKey"));
RuleParamDto rule1Param = db.rules().insertRuleParam(rule1);
ActiveRuleDto activeRule1 = db.qualityProfiles().activateRule(activatedQualityProfile, rule1);
QProfileDto deactivatedQualityProfile = QualityProfileTesting.newQualityProfileDto();
db.qualityProfiles().insert(deactivatedQualityProfile);
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo2").setRuleKey("ruleKey2"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("repo2").setRuleKey("ruleKey2"));
RuleParamDto rule2Param = db.rules().insertRuleParam(rule2);
ActiveRuleDto activeRule2 = db.qualityProfiles().activateRule(deactivatedQualityProfile, rule2);
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.TextRangeResponseFormatter;
.map(IssueDto::getRuleKey)
.collect(Collectors.toSet());
if (!ruleKeys.isEmpty()) {
- searchResponseData.addRules(dbClient.ruleDao().selectDefinitionByKeys(dbSession, ruleKeys));
+ searchResponseData.addRules(dbClient.ruleDao().selectByKeys(dbSession, ruleKeys));
}
}
SearchWsResponse.Hotspot.Builder builder = SearchWsResponse.Hotspot.newBuilder();
for (IssueDto hotspot : orderedHotspots) {
- RuleDefinitionDto rule = searchResponseData.getRule(hotspot.getRuleKey())
+ RuleDto rule = searchResponseData.getRule(hotspot.getRuleKey())
// due to join with table Rule when retrieving data from Issues, this can't happen
.orElseThrow(() -> new IllegalStateException(format(
"Rule with key '%s' not found for Hotspot '%s'", hotspot.getRuleKey(), hotspot.getKey())));
private final Paging paging;
private final List<IssueDto> orderedHotspots;
private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
- private final Map<RuleKey, RuleDefinitionDto> rulesByRuleKey = new HashMap<>();
+ private final Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
private SearchResponseData(Paging paging, List<IssueDto> orderedHotspots) {
this.paging = paging;
return componentsByUuid;
}
- void addRules(Collection<RuleDefinitionDto> rules) {
+ void addRules(Collection<RuleDto> rules) {
rules.forEach(t -> rulesByRuleKey.put(t.getKey(), t));
}
- Optional<RuleDefinitionDto> getRule(RuleKey ruleKey) {
+ Optional<RuleDto> getRule(RuleKey ruleKey) {
return ofNullable(rulesByRuleKey.get(ruleKey));
}
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.protobuf.DbIssues.Locations;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.IssueChangeWSSupport;
Components components = loadComponents(dbSession, hotspot);
Users users = loadUsers(dbSession, hotspot);
- RuleDefinitionDto rule = loadRule(dbSession, hotspot);
+ RuleDto rule = loadRule(dbSession, hotspot);
ShowWsResponse.Builder responseBuilder = ShowWsResponse.newBuilder();
formatHotspot(responseBuilder, hotspot, users);
responseBuilder.setCanChangeStatus(hotspotWsSupport.canChangeStatus(components.getProject()));
}
- private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDefinitionDto ruleDefinitionDto) {
+ private static void formatRule(ShowWsResponse.Builder responseBuilder, RuleDto ruleDefinitionDto) {
SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(ruleDefinitionDto.getSecurityStandards());
SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory();
.forEach(responseBuilder::addUsers);
}
- private RuleDefinitionDto loadRule(DbSession dbSession, IssueDto hotspot) {
+ private RuleDto loadRule(DbSession dbSession, IssueDto hotspot) {
RuleKey ruleKey = hotspot.getRuleKey();
- return dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey)
+ return dbClient.ruleDao().selectByKey(dbSession, ruleKey)
.orElseThrow(() -> new NotFoundException(format("Rule '%s' does not exist", ruleKey)));
}
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeMapper;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.index.IssueIndexer;
import org.sonar.server.rule.ServerRuleFinder;
}
protected Optional<String> getRuleUuid(Issue issue) {
- return ruleFinder.findDtoByKey(issue.ruleKey()).map(RuleDefinitionDto::getUuid);
+ return ruleFinder.findDtoByKey(issue.ruleKey()).map(RuleDto::getUuid);
}
}
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.Action;
import org.sonar.server.issue.ActionContext;
return null;
}
- RuleDefinitionDto ruleDefinitionDto = bulkChangeData.rulesByKey.get(issue.ruleKey());
+ RuleDto ruleDefinitionDto = bulkChangeData.rulesByKey.get(issue.ruleKey());
ComponentDto projectDto = bulkChangeData.projectsByUuid.get(issue.projectUuid());
if (ruleDefinitionDto == null || projectDto == null) {
return null;
private final Map<String, ComponentDto> projectsByUuid;
private final Map<String, BranchDto> branchesByProjectUuid;
private final Map<String, ComponentDto> componentsByUuid;
- private final Map<RuleKey, RuleDefinitionDto> rulesByKey;
+ private final Map<RuleKey, RuleDto> rulesByKey;
private final List<Action> availableActions;
BulkChangeData(DbSession dbSession, Request request) {
this.componentsByUuid = getComponents(dbSession,
issues.stream().map(DefaultIssue::componentUuid).collect(MoreCollectors.toSet())).stream()
.collect(uniqueIndex(ComponentDto::uuid, identity()));
- this.rulesByKey = dbClient.ruleDao().selectDefinitionByKeys(dbSession,
+ this.rulesByKey = dbClient.ruleDao().selectByKeys(dbSession,
issues.stream().map(DefaultIssue::ruleKey).collect(MoreCollectors.toSet())).stream()
- .collect(uniqueIndex(RuleDefinitionDto::getKey, identity()));
+ .collect(uniqueIndex(RuleDto::getKey, identity()));
this.availableActions = actions.stream()
.filter(action -> propertiesByActions.containsKey(action.key()))
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.IssueChangePostProcessor;
import org.sonar.server.issue.WebIssueStorage;
public SearchResponseData saveIssueAndPreloadSearchResponseData(DbSession dbSession, DefaultIssue issue,
IssueChangeContext context, boolean refreshMeasures) {
- Optional<RuleDefinitionDto> rule = getRuleByKey(dbSession, issue.getRuleKey());
+ Optional<RuleDto> rule = getRuleByKey(dbSession, issue.getRuleKey());
ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, issue.projectUuid());
BranchDto branch = getBranch(dbSession, issue, issue.projectUuid());
ComponentDto component = getComponent(dbSession, issue, issue.componentUuid());
- IssueDto issueDto = doSaveIssue(dbSession, issue, context, rule, project, branch);
+ IssueDto issueDto = doSaveIssue(dbSession, issue, context, rule.orElse(null), project, branch);
SearchResponseData result = new SearchResponseData(issueDto);
rule.ifPresent(r -> result.addRules(singletonList(r)));
}
private IssueDto doSaveIssue(DbSession session, DefaultIssue issue, IssueChangeContext context,
- Optional<RuleDefinitionDto> rule, ComponentDto project, BranchDto branchDto) {
+ @Nullable RuleDto ruleDto, ComponentDto project, BranchDto branchDto) {
IssueDto issueDto = issueStorage.save(session, singletonList(issue)).iterator().next();
if (
// since this method is called after an update of the issue, date should never be null
issue.updateDate() == null
// name of rule is displayed in notification, rule must therefor be present
- || !rule.isPresent()
+ || ruleDto == null
// notification are not supported on PRs
|| !hasNotificationSupport(branchDto)) {
return issueDto;
.setNewResolution(issue.resolution())
.setNewStatus(issue.status())
.setAssignee(assignee.map(assigneeDto -> new User(assigneeDto.getUuid(), assigneeDto.getLogin(), assigneeDto.getName())).orElse(null))
- .setRule(rule.map(r -> new Rule(r.getKey(), RuleType.valueOfNullable(r.getType()), r.getName())).get())
+ .setRule(new Rule(ruleDto.getKey(), RuleType.valueOfNullable(ruleDto.getType()), ruleDto.getName()))
.setProject(new Project.Builder(project.uuid())
.setKey(project.getKey())
.setProjectName(project.name())
return component;
}
- private Optional<RuleDefinitionDto> getRuleByKey(DbSession session, RuleKey ruleKey) {
- Optional<RuleDefinitionDto> rule = dbClient.ruleDao().selectDefinitionByKey(session, ruleKey);
+ private Optional<RuleDto> getRuleByKey(DbSession session, RuleKey ruleKey) {
+ Optional<RuleDto> rule = dbClient.ruleDao().selectByKey(session, ruleKey);
return (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED) ? rule : Optional.empty();
}
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.workflow.Transition;
private Long effortTotal = null;
private final Map<String, UserDto> usersByUuid = new HashMap<>();
- private final List<RuleDefinitionDto> rules = new ArrayList<>();
+ private final List<RuleDto> rules = new ArrayList<>();
private final Map<String, ComponentDto> componentsByUuid = new HashMap<>();
private final ListMultimap<String, IssueChangeDto> commentsByIssueKey = ArrayListMultimap.create();
private final ListMultimap<String, String> actionsByIssueKey = ArrayListMultimap.create();
return new ArrayList<>(usersByUuid.values());
}
- public List<RuleDefinitionDto> getRules() {
+ public List<RuleDto> getRules() {
return rules;
}
}
}
- public void addRules(@Nullable List<RuleDefinitionDto> rules) {
+ public void addRules(@Nullable List<RuleDto> rules) {
if (rules != null) {
this.rules.addAll(rules);
}
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.markdown.Markdown;
import org.sonar.server.es.Facets;
private Common.Rules.Builder formatRules(SearchResponseData data) {
Common.Rules.Builder wsRules = Common.Rules.newBuilder();
- List<RuleDefinitionDto> rules = firstNonNull(data.getRules(), emptyList());
- for (RuleDefinitionDto rule : rules) {
+ List<RuleDto> rules = firstNonNull(data.getRules(), emptyList());
+ for (RuleDto rule : rules) {
wsRules.addRules(formatRule(rule));
}
return wsRules;
}
- private Common.Rule.Builder formatRule(RuleDefinitionDto rule) {
+ private Common.Rule.Builder formatRule(RuleDto rule) {
Common.Rule.Builder builder = Common.Rule.newBuilder()
.setKey(rule.getKey().toString())
.setName(nullToEmpty(rule.getName()))
return;
}
- Map<String, RuleKey> ruleUuidsByRuleKeys = data.getRules().stream().collect(uniqueIndex(RuleDefinitionDto::getUuid, RuleDefinitionDto::getKey));
+ Map<String, RuleKey> ruleUuidsByRuleKeys = data.getRules().stream().collect(uniqueIndex(RuleDto::getUuid, RuleDto::getKey));
Common.Facet.Builder wsFacet = wsFacets.addFacetsBuilder();
wsFacet.setProperty(PARAM_RULES);
facet.forEach((ruleUuid, count) -> wsFacet.addValuesBuilder()
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
-import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
-import org.sonar.db.rule.RuleMetadataDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.Facets;
import org.sonar.server.issue.TransitionService;
}
private void loadRules(SearchResponseData preloadedResponseData, Collector collector, DbSession dbSession, SearchResponseData result) {
- List<RuleDefinitionDto> preloadedRules = firstNonNull(preloadedResponseData.getRules(), emptyList());
+ List<RuleDto> preloadedRules = firstNonNull(preloadedResponseData.getRules(), emptyList());
result.addRules(preloadedRules);
Set<String> ruleUuidsToLoad = collector.getRuleUuids();
- preloadedRules.stream().map(RuleDefinitionDto::getUuid).collect(toList(preloadedRules.size()))
+ preloadedRules.stream().map(RuleDto::getUuid).collect(toList(preloadedRules.size()))
.forEach(ruleUuidsToLoad::remove);
- List<RuleDefinitionDto> rules = dbClient.ruleDao().selectDefinitionByUuids(dbSession, ruleUuidsToLoad);
-
- getRulesMetadata(dbSession, rules);
-
+ List<RuleDto> rules = dbClient.ruleDao().selectByUuids(dbSession, ruleUuidsToLoad);
+ updateNamesOfAdHocRules(rules);
result.addRules(rules);
}
+ private static void updateNamesOfAdHocRules(List<RuleDto> rules) {
+ rules.stream()
+ .filter(RuleDto::isAdHoc)
+ .forEach(r -> r.setName(r.getAdHocName()));
+ }
+
+
private void loadComments(Collector collector, DbSession dbSession, Set<SearchAdditionalField> fields, SearchResponseData result) {
if (fields.contains(COMMENTS)) {
List<IssueChangeDto> comments = dbClient.issueChangeDao().selectByTypeAndIssueKeys(dbSession, collector.getIssueKeys(), IssueChangeDto.TYPE_COMMENT);
}
}
- private void getRulesMetadata(DbSession dbSession, List<RuleDefinitionDto> rules) {
- List<RuleKey> adHocRuleKeys = rules.stream().filter(RuleDefinitionDto::isAdHoc)
- .map(r -> RuleKey.of(r.getRepositoryKey(), r.getRuleKey()))
- .collect(toList());
-
- List<RuleMetadataDto> adHocRulesMetadata = dbClient.ruleDao().selectMetadataByKeys(dbSession, adHocRuleKeys);
-
- rules.forEach(r -> {
- if (r.isAdHoc()) {
- String adHocName = adHocRulesMetadata.stream()
- .filter(m -> m.getRuleUuid().equals(r.getUuid())).findFirst().map(RuleMetadataDto::getAdHocName)
- .orElse(null);
- r.setName(adHocName);
- }
- });
- }
-
}
import org.sonar.db.qualityprofile.ExportRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import org.sonar.server.rule.NewCustomRule;
import org.sonar.server.rule.NewRuleDescriptionSection;
List<ImportedRule> importedRules = qProfile.getRules();
- Map<RuleKey, RuleDefinitionDto> ruleDefinitionsByKey = getImportedRulesDefinitions(dbSession, importedRules);
+ Map<RuleKey, RuleDto> ruleDefinitionsByKey = getImportedRulesDefinitions(dbSession, importedRules);
checkIfRulesFromExternalEngines(ruleDefinitionsByKey.values());
- Map<RuleKey, RuleDefinitionDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleDefinitionsByKey);
+ Map<RuleKey, RuleDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleDefinitionsByKey);
ruleDefinitionsByKey.putAll(customRulesDefinitions);
List<RuleActivation> ruleActivations = toRuleActivations(importedRules, ruleDefinitionsByKey);
/**
* Returns map of rule definition for an imported rule key.
- * The imported rule key may refer to a deprecated rule key, in which case the the RuleDefinitionDto will correspond to a different key (the new key).
+ * The imported rule key may refer to a deprecated rule key, in which case the the RuleDto will correspond to a different key (the new key).
*/
- private Map<RuleKey, RuleDefinitionDto> getImportedRulesDefinitions(DbSession dbSession, List<ImportedRule> rules) {
+ private Map<RuleKey, RuleDto> getImportedRulesDefinitions(DbSession dbSession, List<ImportedRule> rules) {
Set<RuleKey> ruleKeys = rules.stream()
.map(ImportedRule::getRuleKey)
.collect(toSet());
- Map<RuleKey, RuleDefinitionDto> rulesDefinitions = db.ruleDao().selectDefinitionByKeys(dbSession, ruleKeys).stream()
- .collect(Collectors.toMap(RuleDefinitionDto::getKey, identity()));
+ Map<RuleKey, RuleDto> rulesDefinitions = db.ruleDao().selectByKeys(dbSession, ruleKeys).stream()
+ .collect(Collectors.toMap(RuleDto::getKey, identity()));
Set<RuleKey> unrecognizedRuleKeys = ruleKeys.stream()
.filter(r -> !rulesDefinitions.containsKey(r))
.filter(r -> !ruleKeys.contains(RuleKey.of(r.getNewRepositoryKey(), r.getNewRuleKey())))
.collect(Collectors.toMap(DeprecatedRuleKeyDto::getRuleUuid, identity()));
- List<RuleDefinitionDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectDefinitionByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
- for (RuleDefinitionDto rule : rulesBasedOnDeprecatedKeys) {
+ List<RuleDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
+ for (RuleDto rule : rulesBasedOnDeprecatedKeys) {
DeprecatedRuleKeyDto deprecatedRuleKey = deprecatedRuleKeysByUuid.get(rule.getUuid());
RuleKey oldRuleKey = RuleKey.of(deprecatedRuleKey.getOldRepositoryKey(), deprecatedRuleKey.getOldRuleKey());
rulesDefinitions.put(oldRuleKey, rule);
return rulesDefinitions;
}
- private static void checkIfRulesFromExternalEngines(Collection<RuleDefinitionDto> ruleDefinitions) {
- List<RuleDefinitionDto> externalRules = ruleDefinitions.stream()
- .filter(RuleDefinitionDto::isExternal)
+ private static void checkIfRulesFromExternalEngines(Collection<RuleDto> ruleDefinitions) {
+ List<RuleDto> externalRules = ruleDefinitions.stream()
+ .filter(RuleDto::isExternal)
.collect(Collectors.toList());
if (!externalRules.isEmpty()) {
}
}
- private Map<RuleKey, RuleDefinitionDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDefinitionDto> ruleDefinitionsByKey) {
+ private Map<RuleKey, RuleDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
List<NewCustomRule> customRulesToCreate = rules.stream()
.filter(r -> ruleDefinitionsByKey.get(r.getRuleKey()) == null && r.isCustomRule())
.map(QProfileBackuperImpl::importedRuleToNewCustomRule)
.collect(Collectors.toList());
if (!customRulesToCreate.isEmpty()) {
- return db.ruleDao().selectDefinitionByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate))
+ return db.ruleDao().selectByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate))
.stream()
- .collect(Collectors.toMap(RuleDefinitionDto::getKey, identity()));
+ .collect(Collectors.toMap(RuleDto::getKey, identity()));
}
return Collections.emptyMap();
}
.setParameters(r.getParameters());
}
- private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDefinitionDto> ruleDefinitionsByKey) {
+ private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
List<RuleActivation> activatedRule = new ArrayList<>();
for (ImportedRule r : rules) {
- RuleDefinitionDto ruleDefinition = ruleDefinitionsByKey.get(r.getRuleKey());
- if (ruleDefinition == null) {
+ RuleDto ruleDto = ruleDefinitionsByKey.get(r.getRuleKey());
+ if (ruleDto == null) {
continue;
}
- activatedRule.add(RuleActivation.create(ruleDefinition.getUuid(), r.getSeverity(), r.getParameters()));
+ activatedRule.add(RuleActivation.create(ruleDto.getUuid(), r.getSeverity(), r.getParameters()));
}
return activatedRule;
}
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
}
private List<ActiveRuleChange> importProfile(QProfileDto profile, RulesProfile definition, DbSession dbSession) {
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey = dbClient.ruleDao().selectAllDefinitions(dbSession)
+ Map<RuleKey, RuleDto> rulesByRuleKey = dbClient.ruleDao().selectAll(dbSession)
.stream()
- .collect(MoreCollectors.uniqueIndex(RuleDefinitionDto::getKey));
+ .collect(MoreCollectors.uniqueIndex(RuleDto::getKey));
List<ActiveRule> activeRules = definition.getActiveRules();
List<RuleActivation> activations = activeRules.stream()
.map(activeRule -> toRuleActivation(activeRule, rulesByRuleKey))
}
@CheckForNull
- private static RuleActivation toRuleActivation(ActiveRule activeRule, Map<RuleKey, RuleDefinitionDto> rulesByRuleKey) {
+ private static RuleActivation toRuleActivation(ActiveRule activeRule, Map<RuleKey, RuleDto> rulesByRuleKey) {
RuleKey ruleKey = activeRule.getRule().ruleKey();
- RuleDefinitionDto ruleDefinition = rulesByRuleKey.get(ruleKey);
- if (ruleDefinition == null) {
+ RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
+ if (ruleDto == null) {
return null;
}
String severity = activeRule.getSeverity().name();
Map<String, String> params = activeRule.getActiveRuleParams().stream()
.collect(MoreCollectors.uniqueIndex(ActiveRuleParam::getKey, ActiveRuleParam::getValue));
- return RuleActivation.create(ruleDefinition.getUuid(), severity, params);
+ return RuleActivation.create(ruleDto.getUuid(), severity, params);
}
}
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.RuleActivationContext;
@Override
public BulkChangeResult bulkActivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, @Nullable String severity) {
verifyNotBuiltIn(profile);
- BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDefinition) -> {
- RuleActivation activation = RuleActivation.create(ruleDefinition.getUuid(), severity, null);
+ BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDto) -> {
+ RuleActivation activation = RuleActivation.create(ruleDto.getUuid(), severity, null);
return ruleActivator.activate(dbSession, activation, context);
});
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), bulkChangeResult.getChanges(), profile.getLanguage());
@Override
public BulkChangeResult bulkDeactivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery) {
verifyNotBuiltIn(profile);
- BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDefinition) ->
- ruleActivator.deactivate(dbSession, context, ruleDefinition.getUuid(), false));
+ BulkChangeResult bulkChangeResult = doBulk(dbSession, profile, ruleQuery, (context, ruleDto) ->
+ ruleActivator.deactivate(dbSession, context, ruleDto.getUuid(), false));
qualityProfileChangeEventService.distributeRuleChangeEvent(List.of(profile), bulkChangeResult.getChanges(), profile.getLanguage());
}
@Override
- public List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDefinitionDto rule) {
+ public List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDto rule) {
List<ActiveRuleChange> changes = new ArrayList<>();
List<String> activeRuleUuids = new ArrayList<>();
db.activeRuleDao().selectByRuleUuid(dbSession, rule.getUuid()).forEach(ar -> {
checkArgument(!profile.isBuiltIn(), "The built-in profile %s is read-only and can't be updated", profile.getName());
}
- private BulkChangeResult doBulk(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, BiFunction<RuleActivationContext, RuleDefinitionDto, List<ActiveRuleChange>> fn) {
+ private BulkChangeResult doBulk(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, BiFunction<RuleActivationContext, RuleDto, List<ActiveRuleChange>> fn) {
BulkChangeResult result = new BulkChangeResult();
Collection<String> ruleUuids = Sets.newHashSet(ruleIndex.searchAll(ruleQuery));
RuleActivationContext context = ruleActivator.createContextForUserProfile(dbSession, profile, ruleUuids);
for (String ruleUuid : ruleUuids) {
try {
context.reset(ruleUuid);
- RuleDefinitionDto ruleDefinition = context.getRule().get();
- List<ActiveRuleChange> changes = fn.apply(context, ruleDefinition);
+ RuleDto ruleDto = context.getRule().get();
+ List<ActiveRuleChange> changes = fn.apply(context, ruleDto);
result.addChanges(changes);
if (!changes.isEmpty()) {
result.incrementSucceeded();
import org.sonar.db.qualityprofile.DefaultQProfileDto;
import org.sonar.db.qualityprofile.OrgQProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
private ActiveRuleChange insertActiveRule(DbSession batchDbSession, RulesProfileDto rulesProfileDto, BuiltInQProfile.ActiveRule activeRule, long now) {
RuleKey ruleKey = activeRule.getRuleKey();
- RuleDefinitionDto ruleDefinitionDto = ruleRepository.getDefinition(ruleKey)
+ RuleDto ruleDefinitionDto = ruleRepository.getDefinition(ruleKey)
.orElseThrow(() -> new IllegalStateException("RuleDefinition not found for key " + ruleKey));
ActiveRuleDto dto = new ActiveRuleDto();
}
}
- private Optional<RuleDefinitionDto> getDefinition(RuleKey ruleKey) {
+ private Optional<RuleDto> getDefinition(RuleKey ruleKey) {
return ruleFinder.findDtoByKey(requireNonNull(ruleKey, "RuleKey can't be null"));
}
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.rule.ServerRuleFinder;
import org.springframework.beans.factory.annotation.Autowired;
if (rulesProfilesByLanguage.isEmpty()) {
return Collections.emptyList();
}
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey = loadRuleDefinitionsByRuleKey();
+ Map<RuleKey, RuleDto> rulesByRuleKey = loadRuleDefinitionsByRuleKey();
Map<String, List<BuiltInQProfile.Builder>> buildersByLanguage = rulesProfilesByLanguage
.entrySet()
.stream()
.collect(MoreCollectors.toList());
}
- private Map<RuleKey, RuleDefinitionDto> loadRuleDefinitionsByRuleKey() {
+ private Map<RuleKey, RuleDto> loadRuleDefinitionsByRuleKey() {
try (DbSession dbSession = dbClient.openSession(false)) {
- Collection<RuleDefinitionDto> ruleDefinitions = ruleFinder.findAll();
+ Collection<RuleDto> ruleDefinitions = ruleFinder.findAll();
Multimap<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByRuleId = dbClient.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
.collect(MoreCollectors.index(DeprecatedRuleKeyDto::getRuleUuid));
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey = new HashMap<>();
- for (RuleDefinitionDto ruleDefinition : ruleDefinitions) {
- rulesByRuleKey.put(ruleDefinition.getKey(), ruleDefinition);
- deprecatedRuleKeysByRuleId.get(ruleDefinition.getUuid()).forEach(t -> rulesByRuleKey.put(RuleKey.of(t.getOldRepositoryKey(), t.getOldRuleKey()), ruleDefinition));
+ Map<RuleKey, RuleDto> rulesByRuleKey = new HashMap<>();
+ for (RuleDto ruleDto : ruleDefinitions) {
+ rulesByRuleKey.put(ruleDto.getKey(), ruleDto);
+ deprecatedRuleKeysByRuleId.get(ruleDto.getUuid()).forEach(t -> rulesByRuleKey.put(RuleKey.of(t.getOldRepositoryKey(), t.getOldRuleKey()), ruleDto));
}
return rulesByRuleKey;
}
* </ul>
*/
private static List<BuiltInQProfile.Builder> toQualityProfileBuilders(Map.Entry<String, Map<String, BuiltInQualityProfile>> rulesProfilesByLanguageAndName,
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey) {
+ Map<RuleKey, RuleDto> rulesByRuleKey) {
String language = rulesProfilesByLanguageAndName.getKey();
// use a LinkedHashMap to keep order of insertion of RulesProfiles
Map<String, BuiltInQProfile.Builder> qualityProfileBuildersByName = new LinkedHashMap<>();
}
private static BuiltInQProfile.Builder updateOrCreateBuilder(String language, @Nullable BuiltInQProfile.Builder existingBuilder, BuiltInQualityProfile builtInProfile,
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey) {
+ Map<RuleKey, RuleDto> rulesByRuleKey) {
BuiltInQProfile.Builder builder = createOrReuseBuilder(existingBuilder, language, builtInProfile);
builder.setDeclaredDefault(builtInProfile.isDefault());
builtInProfile.rules().forEach(builtInActiveRule -> {
RuleKey ruleKey = RuleKey.of(builtInActiveRule.repoKey(), builtInActiveRule.ruleKey());
- RuleDefinitionDto ruleDefinition = rulesByRuleKey.get(ruleKey);
- checkState(ruleDefinition != null, "Rule with key '%s' not found", ruleKey);
- builder.addRule(new BuiltInQProfile.ActiveRule(ruleDefinition.getUuid(), ruleDefinition.getKey(),
+ RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
+ checkState(ruleDto != null, "Rule with key '%s' not found", ruleKey);
+ builder.addRule(new BuiltInQProfile.ActiveRule(ruleDto.getUuid(), ruleDto.getKey(),
builtInActiveRule.overriddenSeverity(), builtInActiveRule.overriddenParams()));
});
return builder;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.RuleActivation;
this.descendantProfilesSupplier = builder.descendantProfilesSupplier;
ListMultimap<String, RuleParamDto> paramsByRuleId = builder.ruleParams.stream().collect(index(RuleParamDto::getRuleUuid));
- for (RuleDefinitionDto rule : builder.rules) {
+ for (RuleDto rule : builder.rules) {
RuleWrapper wrapper = new RuleWrapper(rule, paramsByRuleId.get(rule.getUuid()));
rulesByUuid.put(rule.getUuid(), wrapper);
}
static final class Builder {
private long date = System.currentTimeMillis();
private RulesProfileDto baseRulesProfile;
- private Collection<RuleDefinitionDto> rules;
+ private Collection<RuleDto> rules;
private Collection<RuleParamDto> ruleParams;
private Collection<QProfileDto> profiles;
private Collection<ActiveRuleDto> activeRules;
return this;
}
- Builder setRules(Collection<RuleDefinitionDto> rules) {
+ Builder setRules(Collection<RuleDto> rules) {
this.rules = rules;
return this;
}
}
public static final class RuleWrapper {
- private final RuleDefinitionDto rule;
+ private final RuleDto rule;
private final Map<String, RuleParamDto> paramsByKey;
- private RuleWrapper(RuleDefinitionDto rule, Collection<RuleParamDto> params) {
+ private RuleWrapper(RuleDto rule, Collection<RuleParamDto> params) {
this.rule = rule;
this.paramsByKey = params.stream().collect(uniqueIndex(RuleParamDto::getName));
}
- public RuleDefinitionDto get() {
+ public RuleDto get() {
return rule;
}
import org.sonar.db.qualityprofile.OrgQProfileDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
}
private List<ActiveRuleChange> doActivate(DbSession dbSession, RuleActivation activation, RuleActivationContext context) {
- RuleDefinitionDto rule = context.getRule().get();
+ RuleDto rule = context.getRule().get();
checkRequest(RuleStatus.REMOVED != rule.getStatus(), "Rule was removed: %s", rule.getKey());
checkRequest(!rule.isTemplate(), "Rule template can't be activated on a Quality profile: %s", rule.getKey());
checkRequest(context.getRulesProfile().getLanguage().equals(rule.getLanguage()),
return stopCascading;
}
- private ActiveRuleChange handleNewRuleActivation(RuleActivation activation, RuleActivationContext context, RuleDefinitionDto rule, ActiveRuleKey activeRuleKey) {
+ private ActiveRuleChange handleNewRuleActivation(RuleActivation activation, RuleActivationContext context, RuleDto rule, ActiveRuleKey activeRuleKey) {
ActiveRuleChange change = new ActiveRuleChange(ActiveRuleChange.Type.ACTIVATED, activeRuleKey, rule);
applySeverityAndParamToChange(activation, context, change);
if (context.isCascading() || isSameAsParent(change, context)) {
}
private void completeWithRules(DbSession dbSession, RuleActivationContext.Builder builder, Collection<String> ruleUuids) {
- List<RuleDefinitionDto> rules = db.ruleDao().selectDefinitionByUuids(dbSession, ruleUuids);
+ List<RuleDto> rules = db.ruleDao().selectByUuids(dbSession, ruleUuids);
builder.setRules(rules);
builder.setRuleParams(db.ruleDao().selectRuleParamsByRuleUuids(dbSession, ruleUuids));
}
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.user.UserSession;
private RuleActivation readActivation(DbSession dbSession, Request request) {
RuleKey ruleKey = RuleKey.parse(request.mandatoryParam(PARAM_RULE));
- RuleDefinitionDto ruleDefinition = wsSupport.getRule(dbSession, ruleKey);
+ RuleDto ruleDto = wsSupport.getRule(dbSession, ruleKey);
boolean reset = Boolean.TRUE.equals(request.paramAsBoolean(PARAM_RESET));
if (reset) {
- return RuleActivation.createReset(ruleDefinition.getUuid());
+ return RuleActivation.createReset(ruleDto.getUuid());
}
String severity = request.param(PARAM_SEVERITY);
Map<String, String> params = null;
if (paramsAsString != null) {
params = KeyValueFormat.parse(paramsAsString);
}
- return RuleActivation.create(ruleDefinition.getUuid(), severity, params);
+ return RuleActivation.create(ruleDto.getUuid(), severity, params);
}
}
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileChangeQuery;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
List<Change> changelogs = load(dbSession, query);
Map<String, UserDto> usersByUuid = getUsersByUserUuid(dbSession, changelogs);
- Map<String, RuleDefinitionDto> rulesByRuleIds = getRulesByRuleUuids(dbSession, changelogs);
+ Map<String, RuleDto> rulesByRuleIds = getRulesByRuleUuids(dbSession, changelogs);
writeResponse(response.newJsonWriter(), total, page, pageSize, changelogs, usersByUuid, rulesByRuleIds);
}
}
.collect(uniqueIndex(UserDto::getUuid));
}
- private Map<String, RuleDefinitionDto> getRulesByRuleUuids(DbSession dbSession, List<Change> changes) {
+ private Map<String, RuleDto> getRulesByRuleUuids(DbSession dbSession, List<Change> changes) {
Set<String> ruleUuids = changes.stream()
.map(c -> c.ruleUuid)
.filter(Objects::nonNull)
.collect(toSet());
return dbClient.ruleDao()
- .selectDefinitionByUuids(dbSession, Lists.newArrayList(ruleUuids))
+ .selectByUuids(dbSession, Lists.newArrayList(ruleUuids))
.stream()
- .collect(uniqueIndex(RuleDefinitionDto::getUuid));
+ .collect(uniqueIndex(RuleDto::getUuid));
}
private static void writeResponse(JsonWriter json, int total, int page, int pageSize, List<Change> changelogs,
- Map<String, UserDto> usersByUuid, Map<String, RuleDefinitionDto> rulesByRuleUuids) {
+ Map<String, UserDto> usersByUuid, Map<String, RuleDto> rulesByRuleUuids) {
json.beginObject();
json.prop("total", total);
json.prop(Param.PAGE, page);
.prop("authorLogin", user.getLogin())
.prop("authorName", user.getName());
}
- RuleDefinitionDto rule = rulesByRuleUuids.get(change.getRuleUuid());
+ RuleDto rule = rulesByRuleUuids.get(change.getRuleUuid());
if (rule != null) {
changeWriter
.prop("ruleKey", rule.getKey().toString())
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleRepositoryDto;
import org.sonar.server.qualityprofile.QProfileComparison;
import org.sonar.server.qualityprofile.QProfileComparison.ActiveRuleDiff;
QProfileComparisonResult result = comparator.compare(dbSession, left, right);
- List<RuleDefinitionDto> referencedRules = dbClient.ruleDao().selectDefinitionByKeys(dbSession, new ArrayList<>(result.collectRuleKeys()));
- Map<RuleKey, RuleDefinitionDto> rulesByKey = Maps.uniqueIndex(referencedRules, RuleDefinitionDto::getKey);
+ List<RuleDto> referencedRules = dbClient.ruleDao().selectByKeys(dbSession, new ArrayList<>(result.collectRuleKeys()));
+ Map<RuleKey, RuleDto> rulesByKey = Maps.uniqueIndex(referencedRules, RuleDto::getKey);
Map<String, RuleRepositoryDto> repositoriesByKey = Maps.uniqueIndex(dbClient.ruleRepositoryDao().selectAll(dbSession), RuleRepositoryDto::getKey);
writeResult(response.newJsonWriter(), result, rulesByKey, repositoriesByKey);
}
}
- private void writeResult(JsonWriter json, QProfileComparisonResult result, Map<RuleKey, RuleDefinitionDto> rulesByKey, Map<String, RuleRepositoryDto> repositoriesByKey) {
+ private void writeResult(JsonWriter json, QProfileComparisonResult result, Map<RuleKey, RuleDto> rulesByKey, Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginObject();
json.name(ATTRIBUTE_LEFT).beginObject();
.prop(ATTRIBUTE_NAME, profile.getName());
}
- private void writeRules(JsonWriter json, Map<RuleKey, ActiveRuleDto> activeRules, Map<RuleKey, RuleDefinitionDto> rulesByKey,
+ private void writeRules(JsonWriter json, Map<RuleKey, ActiveRuleDto> activeRules, Map<RuleKey, RuleDto> rulesByKey,
Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginArray();
for (Entry<RuleKey, ActiveRuleDto> activeRule : activeRules.entrySet()) {
ActiveRuleDto value = activeRule.getValue();
json.beginObject();
- RuleDefinitionDto rule = rulesByKey.get(key);
+ RuleDto rule = rulesByKey.get(key);
writeRule(json, rule, repositoriesByKey.get(rule.getRepositoryKey()));
json.prop(ATTRIBUTE_SEVERITY, value.getSeverityString());
json.endObject();
json.endArray();
}
- private void writeRule(JsonWriter json, RuleDefinitionDto rule, @Nullable RuleRepositoryDto repository) {
+ private void writeRule(JsonWriter json, RuleDto rule, @Nullable RuleRepositoryDto repository) {
String repositoryKey = rule.getRepositoryKey();
json.prop(ATTRIBUTE_KEY, rule.getKey().toString())
.prop(ATTRIBUTE_NAME, rule.getName())
}
}
- private void writeDifferences(JsonWriter json, Map<RuleKey, ActiveRuleDiff> modified, Map<RuleKey, RuleDefinitionDto> rulesByKey,
+ private void writeDifferences(JsonWriter json, Map<RuleKey, ActiveRuleDiff> modified, Map<RuleKey, RuleDto> rulesByKey,
Map<String, RuleRepositoryDto> repositoriesByKey) {
json.beginArray();
for (Entry<RuleKey, ActiveRuleDiff> diffEntry : modified.entrySet()) {
RuleKey key = diffEntry.getKey();
ActiveRuleDiff value = diffEntry.getValue();
json.beginObject();
- RuleDefinitionDto rule = rulesByKey.get(key);
+ RuleDto rule = rulesByKey.get(key);
writeRule(json, rule, repositoriesByKey.get(rule.getRepositoryKey()));
json.name(ATTRIBUTE_LEFT).beginObject();
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.user.UserSession;
String qualityProfileKey = request.mandatoryParam(PARAM_KEY);
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
- RuleDefinitionDto rule = wsSupport.getRule(dbSession, ruleKey);
+ RuleDto rule = wsSupport.getRule(dbSession, ruleKey);
QProfileDto profile = wsSupport.getProfile(dbSession, QProfileReference.fromKey(qualityProfileKey));
wsSupport.checkCanEdit(dbSession, profile);
ruleActivator.deactivateAndCommit(dbSession, profile, singletonList(rule.getUuid()));
import org.sonar.db.DbSession;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
this.userSession = userSession;
}
- public RuleDefinitionDto getRule(DbSession dbSession, RuleKey ruleKey) {
- Optional<RuleDefinitionDto> ruleDefinitionDto = dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey);
- RuleDefinitionDto rule = checkFoundWithOptional(ruleDefinitionDto, "Rule with key '%s' not found", ruleKey);
+ public RuleDto getRule(DbSession dbSession, RuleKey ruleKey) {
+ Optional<RuleDto> ruleDefinitionDto = dbClient.ruleDao().selectByKey(dbSession, ruleKey);
+ RuleDto rule = checkFoundWithOptional(ruleDefinitionDto, "Rule with key '%s' not found", ruleKey);
checkRequest(!rule.isExternal(), "Operation forbidden for rule '%s' imported from an external rule engine.", ruleKey);
return rule;
}
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Format;
-import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.rule.index.RuleIndexer;
validateCustomRule(newRule, dbSession, templateKey);
RuleKey customRuleKey = RuleKey.of(templateRule.getRepositoryKey(), newRule.ruleKey());
- Optional<RuleDefinitionDto> definition = loadRule(dbSession, customRuleKey);
+ Optional<RuleDto> definition = loadRule(dbSession, customRuleKey);
String customRuleUuid = definition.map(d -> updateExistingRule(d, newRule, dbSession))
.orElseGet(() -> createCustomRule(customRuleKey, newRule, templateRule, dbSession));
}
}
- private Optional<RuleDefinitionDto> loadRule(DbSession dbSession, RuleKey ruleKey) {
- return dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey);
+ private Optional<RuleDto> loadRule(DbSession dbSession, RuleKey ruleKey) {
+ return dbClient.ruleDao().selectByKey(dbSession, ruleKey);
}
private String createCustomRule(RuleKey ruleKey, NewCustomRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
- RuleDefinitionDto ruleDefinition = new RuleDefinitionDto()
+ RuleDto ruleDto = new RuleDto()
.setUuid(uuidFactory.create())
.setRuleKey(ruleKey)
.setPluginKey(templateRuleDto.getPluginKey())
.setCreatedAt(system2.now())
.setUpdatedAt(system2.now());
- ruleDefinition.setDescriptionFormat(Format.MARKDOWN);
+ ruleDto.setDescriptionFormat(Format.MARKDOWN);
if (newRule.getRuleDescriptionSections().isEmpty() && newRule.markdownDescription() != null) {
RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), newRule.markdownDescription());
- ruleDefinition.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
+ ruleDto.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
} else {
for (NewRuleDescriptionSection ruleDescriptionSection : newRule.getRuleDescriptionSections()) {
RuleDescriptionSectionDto ruleDescriptionSectionDto = RuleDescriptionSectionDto.builder()
.key(ruleDescriptionSection.getKey())
.content(ruleDescriptionSection.getContent())
.build();
- ruleDefinition.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
+ ruleDto.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
}
}
- dbClient.ruleDao().insert(dbSession, ruleDefinition);
-
Set<String> tags = templateRuleDto.getTags();
if (!tags.isEmpty()) {
- RuleMetadataDto ruleMetadata = new RuleMetadataDto()
- .setRuleUuid(ruleDefinition.getUuid())
- .setTags(tags)
- .setCreatedAt(system2.now())
- .setUpdatedAt(system2.now());
- dbClient.ruleDao().insertOrUpdate(dbSession, ruleMetadata);
+ ruleDto.setTags(tags);
}
+ dbClient.ruleDao().insert(dbSession, ruleDto);
for (RuleParamDto templateRuleParamDto : dbClient.ruleDao().selectRuleParamsByRuleKey(dbSession, templateRuleDto.getKey())) {
String customRuleParamValue = Strings.emptyToNull(newRule.parameter(templateRuleParamDto.getName()));
- createCustomRuleParams(customRuleParamValue, ruleDefinition, templateRuleParamDto, dbSession);
+ createCustomRuleParams(customRuleParamValue, ruleDto, templateRuleParamDto, dbSession);
}
- return ruleDefinition.getUuid();
+ return ruleDto.getUuid();
}
- private void createCustomRuleParams(@Nullable String paramValue, RuleDefinitionDto ruleDto, RuleParamDto templateRuleParam, DbSession dbSession) {
+ private void createCustomRuleParams(@Nullable String paramValue, RuleDto ruleDto, RuleParamDto templateRuleParam, DbSession dbSession) {
RuleParamDto ruleParamDto = RuleParamDto.createFor(ruleDto)
.setName(templateRuleParam.getName())
.setType(templateRuleParam.getType())
dbClient.ruleDao().insertRuleParam(dbSession, ruleDto, ruleParamDto);
}
- private String updateExistingRule(RuleDefinitionDto ruleDto, NewCustomRule newRule, DbSession dbSession) {
+ private String updateExistingRule(RuleDto ruleDto, NewCustomRule newRule, DbSession dbSession) {
if (ruleDto.getStatus().equals(RuleStatus.REMOVED)) {
if (newRule.isPreventReactivation()) {
throw new ReactivationException(format("A removed rule with the key '%s' already exists", ruleDto.getKey().rule()), ruleDto.getKey());
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
RuleDto customRule = rule;
String templateUuid = customRule.getTemplateUuid();
checkNotNull(templateUuid, "Rule '%s' has no persisted template!", customRule);
- Optional<RuleDefinitionDto> templateRule = dbClient.ruleDao().selectDefinitionByUuid(templateUuid, dbSession);
+ Optional<RuleDto> templateRule = dbClient.ruleDao().selectByUuid(templateUuid, dbSession);
if (!templateRule.isPresent()) {
throw new IllegalStateException(String.format("Template %s of rule %s does not exist",
customRule.getTemplateUuid(), customRule.getKey()));
// Update rule param
ruleParamDto.setDefaultValue(value);
- dbClient.ruleDao().updateRuleParam(dbSession, customRule.getDefinition(), ruleParamDto);
+ dbClient.ruleDao().updateRuleParam(dbSession, customRule, ruleParamDto);
if (value != null) {
// Update linked active rule params or create new one
private void update(DbSession session, RuleDto rule) {
rule.setUpdatedAt(system.now());
- dbClient.ruleDao().update(session, rule.getDefinition());
- dbClient.ruleDao().insertOrUpdate(session, rule.getMetadata());
+ dbClient.ruleDao().update(session, rule);
}
}
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
import org.sonar.server.rule.index.RuleQuery;
return activeRuleParamsByActiveRuleKey;
}
- List<Rules.Active> completeShow(DbSession dbSession, RuleDefinitionDto rule) {
+ List<Rules.Active> completeShow(DbSession dbSession, RuleDto rule) {
List<OrgActiveRuleDto> activeRules = dbClient.activeRuleDao().selectByOrgRuleUuid(dbSession, rule.getUuid());
Map<String, ActiveRuleKey> activeRuleUuidsByKey = new HashMap<>();
for (OrgActiveRuleDto activeRuleDto : activeRules) {
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.rule.NewCustomRule;
import org.sonar.server.rule.ReactivationException;
}
private Rules.CreateResponse createResponse(DbSession dbSession, RuleKey ruleKey) {
- RuleDefinitionDto rule = dbClient.ruleDao().selectDefinitionByKey(dbSession, ruleKey)
+ RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, ruleKey)
.orElseThrow(() -> new IllegalStateException(String.format("Cannot load rule, that has just been created '%s'", ruleKey)));
- List<RuleDefinitionDto> templateRules = new ArrayList<>();
+ List<RuleDto> templateRules = new ArrayList<>();
if (rule.isCustomRule()) {
- Optional<RuleDefinitionDto> templateRule = dbClient.ruleDao().selectDefinitionByUuid(rule.getTemplateUuid(), dbSession);
+ Optional<RuleDto> templateRule = dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession);
templateRule.ifPresent(templateRules::add);
}
List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid()));
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.index.RuleIndexer;
public void delete(RuleKey ruleKey) {
try (DbSession dbSession = dbClient.openSession(false)) {
- RuleDefinitionDto rule = dbClient.ruleDao().selectOrFailDefinitionByKey(dbSession, ruleKey);
+ RuleDto rule = dbClient.ruleDao().selectOrFailByKey(dbSession, ruleKey);
checkArgument(rule.isCustomRule(), "Rule '%s' cannot be deleted because it is not a custom rule", rule.getKey().toString());
qProfileRules.deleteRule(dbSession, rule);
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Rules.ListResponse;
listResponseBuilder.build().writeTo(wsResponse.stream().output());
}
- private static ListResponse.Rule toRule(ListResponse.Rule.Builder ruleBuilder, RuleDefinitionDto dto) {
+ private static ListResponse.Rule toRule(ListResponse.Rule.Builder ruleBuilder, RuleDto dto) {
return ruleBuilder
.clear()
.setRepository(dto.getRepositoryKey())
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
this.macroInterpreter = macroInterpreter;
}
- public Rules.Rule toWsRule(RuleDefinitionDto ruleDefinitionDto, SearchResult result, Set<String> fieldsToReturn) {
+ public Rules.Rule toWsRule(RuleDto ruleDefinitionDto, SearchResult result, Set<String> fieldsToReturn) {
Rules.Rule.Builder ruleResponse = Rules.Rule.newBuilder();
applyRuleDefinition(ruleResponse, ruleDefinitionDto, result, fieldsToReturn, Collections.emptyMap());
return ruleResponse.build();
}
- public Rules.Rule toWsRule(RuleDefinitionDto ruleDefinition, SearchResult result, Set<String> fieldsToReturn, RuleMetadataDto metadata,
+ public Rules.Rule toWsRule(RuleDto ruleDto, SearchResult result, Set<String> fieldsToReturn, RuleMetadataDto metadata,
Map<String, UserDto> usersByUuid, Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) {
Rules.Rule.Builder ruleResponse = Rules.Rule.newBuilder();
- applyRuleDefinition(ruleResponse, ruleDefinition, result, fieldsToReturn, deprecatedRuleKeysByRuleUuid);
- applyRuleMetadata(ruleResponse, ruleDefinition, metadata, usersByUuid, fieldsToReturn);
- setDebtRemediationFunctionFields(ruleResponse, ruleDefinition, metadata, fieldsToReturn);
+ applyRuleDefinition(ruleResponse, ruleDto, result, fieldsToReturn, deprecatedRuleKeysByRuleUuid);
+ applyRuleMetadata(ruleResponse, ruleDto, metadata, usersByUuid, fieldsToReturn);
+ setDebtRemediationFunctionFields(ruleResponse, ruleDto, metadata, fieldsToReturn);
return ruleResponse.build();
}
- private Rules.Rule.Builder applyRuleDefinition(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDefinitionDto, SearchResult result,
+ private Rules.Rule.Builder applyRuleDefinition(Rules.Rule.Builder ruleResponse, RuleDto ruleDefinitionDto, SearchResult result,
Set<String> fieldsToReturn, Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) {
// Mandatory fields
return ruleResponse;
}
- private void applyRuleMetadata(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDefinition, RuleMetadataDto metadata, Map<String, UserDto> usersByUuid,
+ private void applyRuleMetadata(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, RuleMetadataDto metadata, Map<String, UserDto> usersByUuid,
Set<String> fieldsToReturn) {
setTags(ruleResponse, metadata, fieldsToReturn);
setNotesFields(ruleResponse, metadata, usersByUuid, fieldsToReturn);
setIsRemediationFunctionOverloaded(ruleResponse, metadata, fieldsToReturn);
- if (ruleDefinition.isAdHoc()) {
+ if (ruleDto.isAdHoc()) {
setAdHocName(ruleResponse, metadata, fieldsToReturn);
setAdHocDescription(ruleResponse, metadata, fieldsToReturn);
setAdHocSeverity(ruleResponse, metadata, fieldsToReturn);
}
}
- private static void setRepository(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setRepository(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_REPO)) {
ruleResponse.setRepo(ruleDto.getKey().repository());
}
}
- private static void setScope(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setScope(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_SCOPE)) {
ruleResponse.setScope(toWsRuleScope(ruleDto.getScope()));
}
}
- private static void setDeprecatedKeys(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn,
+ private static void setDeprecatedKeys(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn,
Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid) {
if (shouldReturnField(fieldsToReturn, FIELD_DEPRECATED_KEYS)) {
List<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = deprecatedRuleKeysByRuleUuid.get(ruleDto.getUuid());
}
}
- private static void setEffortToFixDescription(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setEffortToFixDescription(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
String gapDescription = ruleDto.getGapDescription();
if ((shouldReturnField(fieldsToReturn, FIELD_EFFORT_TO_FIX_DESCRIPTION) || shouldReturnField(fieldsToReturn, FIELD_GAP_DESCRIPTION))
&& gapDescription != null) {
}
}
- private static void setDefaultDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setDefaultDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_DEFAULT_DEBT_REM_FUNCTION) || shouldReturnField(fieldsToReturn, FIELD_DEFAULT_REM_FUNCTION)) {
DebtRemediationFunction defaultDebtRemediationFunction = defaultDebtRemediationFunction(ruleDto);
if (defaultDebtRemediationFunction != null) {
}
}
- private static void setDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDefinitionDto, RuleMetadataDto ruleMetadataDto,
+ private static void setDebtRemediationFunctionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDefinitionDto, RuleMetadataDto ruleMetadataDto,
Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_DEBT_REM_FUNCTION) || shouldReturnField(fieldsToReturn, FIELD_REM_FUNCTION)) {
DebtRemediationFunction debtRemediationFunction = debtRemediationFunction(ruleDefinitionDto, ruleMetadataDto);
}
}
- private static void setName(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setName(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_NAME) && ruleDto.getName() != null) {
ruleResponse.setName(ruleDto.getName());
}
}
- private static void setStatus(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setStatus(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_STATUS) && ruleDto.getStatus() != null) {
ruleResponse.setStatus(Common.RuleStatus.valueOf(ruleDto.getStatus().toString()));
}
}
}
- private static void setSysTags(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setSysTags(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_SYSTEM_TAGS)) {
ruleResponse.getSysTagsBuilder().addAllSysTags(ruleDto.getSystemTags());
}
}
- private static void setParams(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, SearchResult searchResult, Set<String> fieldsToReturn) {
+ private static void setParams(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, SearchResult searchResult, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_PARAMS)) {
List<RuleParamDto> ruleParameters = searchResult.getRuleParamsByRuleUuid().get(ruleDto.getUuid());
ruleResponse.getParamsBuilder().addAllParams(ruleParameters.stream().map(RuleParamDtoToWsRuleParam.INSTANCE).collect(toList()));
}
}
- private static void setCreatedAt(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setCreatedAt(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_CREATED_AT)) {
ruleResponse.setCreatedAt(formatDateTime(ruleDto.getCreatedAt()));
}
}
- private void setDescriptionFields(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private void setDescriptionFields(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_HTML_DESCRIPTION)) {
String htmlDescription = RuleDescriptionFormatter.getDescriptionAsHtml(ruleDto);
if (htmlDescription != null) {
}
}
- private static String concatenateSectionTemporaryForSonar16302(RuleDefinitionDto ruleDto) {
+ private static String concatenateSectionTemporaryForSonar16302(RuleDto ruleDto) {
return ruleDto.getRuleDescriptionSectionDtos().stream()
.map(RuleDescriptionSectionDto::getContent)
.collect(joining());
}
}
- private static void setSeverity(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setSeverity(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
String severity = ruleDto.getSeverityString();
if (shouldReturnField(fieldsToReturn, FIELD_SEVERITY) && severity != null) {
ruleResponse.setSeverity(severity);
}
}
- private static void setInternalKey(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setInternalKey(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_INTERNAL_KEY) && ruleDto.getConfigKey() != null) {
ruleResponse.setInternalKey(ruleDto.getConfigKey());
}
}
- private static void setLanguage(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setLanguage(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
String language = ruleDto.getLanguage();
if (shouldReturnField(fieldsToReturn, FIELD_LANGUAGE) && language != null) {
ruleResponse.setLang(language);
}
}
- private void setLanguageName(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private void setLanguageName(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
String languageKey = ruleDto.getLanguage();
if (shouldReturnField(fieldsToReturn, FIELD_LANGUAGE_NAME) && languageKey != null) {
Language language = languages.get(languageKey);
}
}
- private static void setIsTemplate(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setIsTemplate(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_IS_TEMPLATE)) {
ruleResponse.setIsTemplate(ruleDto.isTemplate());
}
}
- private static void setIsExternal(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, Set<String> fieldsToReturn) {
+ private static void setIsExternal(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_IS_EXTERNAL)) {
ruleResponse.setIsExternal(ruleDto.isExternal());
}
}
- private static void setTemplateKey(Rules.Rule.Builder ruleResponse, RuleDefinitionDto ruleDto, SearchResult result, Set<String> fieldsToReturn) {
+ private static void setTemplateKey(Rules.Rule.Builder ruleResponse, RuleDto ruleDto, SearchResult result, Set<String> fieldsToReturn) {
if (shouldReturnField(fieldsToReturn, FIELD_TEMPLATE_KEY) && ruleDto.isCustomRule()) {
- RuleDefinitionDto templateRule = result.getTemplateRulesByRuleUuid().get(ruleDto.getTemplateUuid());
+ RuleDto templateRule = result.getTemplateRulesByRuleUuid().get(ruleDto.getTemplateUuid());
if (templateRule != null) {
ruleResponse.setTemplateKey(templateRule.getKey().toString());
}
}
@CheckForNull
- private static DebtRemediationFunction defaultDebtRemediationFunction(final RuleDefinitionDto ruleDto) {
+ private static DebtRemediationFunction defaultDebtRemediationFunction(final RuleDto ruleDto) {
final String function = ruleDto.getDefRemediationFunction();
if (function == null || function.isEmpty()) {
return null;
}
@CheckForNull
- private static DebtRemediationFunction debtRemediationFunction(RuleDefinitionDto ruleDefinitionDto, RuleMetadataDto ruleMetadataDto) {
+ private static DebtRemediationFunction debtRemediationFunction(RuleDto ruleDefinitionDto, RuleMetadataDto ruleMetadataDto) {
final String function = ruleMetadataDto.getRemediationFunction();
if (function == null || function.isEmpty()) {
return defaultDebtRemediationFunction(ruleDefinitionDto);
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.user.UserDto;
private void writeRules(DbSession dbSession, SearchResponse.Builder response, SearchResult result, SearchOptions context) {
Map<String, UserDto> usersByUuid = ruleWsSupport.getUsersByUuid(dbSession, result.rules);
Map<String, List<DeprecatedRuleKeyDto>> deprecatedRuleKeysByRuleUuid = getDeprecatedRuleKeysByRuleUuid(dbSession, result.rules, context);
- result.rules.forEach(rule -> response.addRules(mapper.toWsRule(rule.getDefinition(), result, context.getFields(), rule.getMetadata(), usersByUuid,
+ result.rules.forEach(rule -> response.addRules(mapper.toWsRule(rule, result, context.getFields(), rule.getMetadata(), usersByUuid,
deprecatedRuleKeysByRuleUuid)));
}
.map(RuleDto::getTemplateUuid)
.filter(Objects::nonNull)
.collect(MoreCollectors.toList());
- List<RuleDefinitionDto> templateRules = dbClient.ruleDao().selectDefinitionByUuids(dbSession, templateRuleUuids);
+ List<RuleDto> templateRules = dbClient.ruleDao().selectByUuids(dbSession, templateRuleUuids);
List<RuleParamDto> ruleParamDtos = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, ruleUuids);
return new SearchResult()
.setRules(rules)
static class SearchResult {
private List<RuleDto> rules;
private final ListMultimap<String, RuleParamDto> ruleParamsByRuleUuid;
- private final Map<String, RuleDefinitionDto> templateRulesByRuleUuid;
+ private final Map<String, RuleDto> templateRulesByRuleUuid;
private Long total;
private Facets facets;
return this;
}
- public Map<String, RuleDefinitionDto> getTemplateRulesByRuleUuid() {
+ public Map<String, RuleDto> getTemplateRulesByRuleUuid() {
return templateRulesByRuleUuid;
}
- public SearchResult setTemplateRules(List<RuleDefinitionDto> templateRules) {
+ public SearchResult setTemplateRules(List<RuleDto> templateRules) {
templateRulesByRuleUuid.clear();
- for (RuleDefinitionDto templateRule : templateRules) {
+ for (RuleDto templateRule : templateRules) {
templateRulesByRuleUuid.put(templateRule.getUuid(), templateRule);
}
return this;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.NotFoundException;
RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key)
.orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key)));
- List<RuleDefinitionDto> templateRules = ofNullable(rule.getTemplateUuid())
- .flatMap(templateUuid -> dbClient.ruleDao().selectDefinitionByUuid(rule.getTemplateUuid(), dbSession))
+ List<RuleDto> templateRules = ofNullable(rule.getTemplateUuid())
+ .flatMap(templateUuid -> dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession))
.map(Collections::singletonList).orElseGet(Collections::emptyList);
List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid()));
private ShowResponse buildResponse(DbSession dbSession, Request request, SearchAction.SearchResult searchResult) {
ShowResponse.Builder responseBuilder = ShowResponse.newBuilder();
RuleDto rule = searchResult.getRules().get(0);
- responseBuilder.setRule(mapper.toWsRule(rule.getDefinition(), searchResult, Collections.emptySet(), rule.getMetadata(),
+ responseBuilder.setRule(mapper.toWsRule(rule, searchResult, Collections.emptySet(), rule.getMetadata(),
ruleWsSupport.getUsersByUuid(dbSession, searchResult.getRules()), emptyMap()));
if (request.mandatoryParamAsBoolean(PARAM_ACTIVES)) {
- activeRuleCompleter.completeShow(dbSession, rule.getDefinition()).forEach(responseBuilder::addActives);
+ activeRuleCompleter.completeShow(dbSession, rule).forEach(responseBuilder::addActives);
}
return responseBuilder.build();
}
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.NotFoundException;
private UpdateResponse buildResponse(DbSession dbSession, RuleKey key) {
RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, key)
.orElseThrow(() -> new NotFoundException(format("Rule not found: %s", key)));
- List<RuleDefinitionDto> templateRules = new ArrayList<>(1);
- if (rule.getDefinition().isCustomRule()) {
- dbClient.ruleDao().selectDefinitionByUuid(rule.getTemplateUuid(), dbSession).ifPresent(templateRules::add);
+ List<RuleDto> templateRules = new ArrayList<>(1);
+ if (rule.isCustomRule()) {
+ dbClient.ruleDao().selectByUuid(rule.getTemplateUuid(), dbSession).ifPresent(templateRules::add);
}
List<RuleParamDto> ruleParameters = dbClient.ruleDao().selectRuleParamsByRuleUuids(dbSession, singletonList(rule.getUuid()));
UpdateResponse.Builder responseBuilder = UpdateResponse.newBuilder();
.setRuleParameters(ruleParameters)
.setTotal(1L);
responseBuilder
- .setRule(mapper.toWsRule(rule.getDefinition(), searchResult, Collections.emptySet(), rule.getMetadata(),
+ .setRule(mapper.toWsRule(rule, searchResult, Collections.emptySet(), rule.getMetadata(),
ruleWsSupport.getUsersByUuid(dbSession, singletonList(rule)), emptyMap()));
return responseBuilder.build();
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.input.ScannerInput.ServerIssue;
@Test
public void test_nullable_fields() throws Exception {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null).setPath(null));
@Test
public void test_fields_with_non_null_values() throws Exception {
UserDto user = db.users().insertUser(u -> u.setLogin("simon").setName("Simon").setEmail("simon@email.com"));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null));
@Test
public void return_issues_of_project() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null));
@Test
public void does_not_return_issues_from_external_rules() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null));
IssueDto issueOnModule = db.issues().insert(rule, project, module, i -> i.setKee("ON_MODULE").setType(randomRuleTypeExceptHotspot()));
IssueDto issueOnFile = db.issues().insert(rule, project, file, i -> i.setKee("ON_FILE").setType(randomRuleTypeExceptHotspot()));
- RuleDefinitionDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
+ RuleDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true));
IssueDto issueFromExteralruleOnFile = db.issues().insert(external, project, file, i -> i.setKee("ON_FILE_FROM_EXTERNAL").setType(randomRuleTypeExceptHotspot()));
- RuleDefinitionDto migrated = db.rules().insert();
+ RuleDto migrated = db.rules().insert();
db.executeUpdateSql("update rules set is_external=? where rules.uuid = ?", false, migrated.getUuid());
IssueDto issueFromMigratedRule = db.issues().insert(migrated, project, file, i -> i.setKee("MIGRATED").setType(randomRuleTypeExceptHotspot()));
@Test
public void return_issues_of_module() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null));
@Test
public void return_issues_of_file() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null));
@Test
public void return_issues_by_project_and_branch() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
addPermissionTo(project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
@Test
public void return_issues_by_module_and_branch() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
addPermissionTo(project);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
@Test
public void issues_on_disabled_modules_are_returned() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project).setEnabled(false));
ComponentDto file = db.components().insertComponent(newFileDto(module, null).setEnabled(false));
import org.sonar.db.metric.MetricDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.protobuf.DbProjectBranches;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
.setMergeBranchUuid(nonMainBranch.uuid())
.setPullRequestData(DbProjectBranches.PullRequestData.newBuilder().setBranch("feature/bar").build()));
db.measures().insertLiveMeasure(pullRequest, qualityGateStatus, m -> m.setData("ERROR"));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.issues().insert(rule, pullRequest, pullRequest, i -> i.setType(BUG).setResolution(null));
db.issues().insert(rule, pullRequest, pullRequest, i -> i.setType(BUG).setResolution(RESOLUTION_FIXED));
db.issues().insert(rule, pullRequest, pullRequest, i -> i.setType(VULNERABILITY).setResolution(null));
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.db.metric.MetricDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
newAnalysis(branch).setLast(true).setCreatedAt(parseDateTime("2017-04-03T13:37:00+0100").getTime()));
db.measures().insertLiveMeasure(branch, qualityGateStatus, m -> m.setData("OK"));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.issues().insert(rule, branch, branch, i -> i.setType(BUG).setResolution(null));
indexIssues();
newAnalysis(branch).setLast(true).setCreatedAt(parseDateTime("2017-04-03T13:37:00+0100").getTime()));
db.measures().insertLiveMeasure(branch, qualityGateStatus, m -> m.setData("OK"));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.issues().insert(rule, branch, branch, i -> i.setType(BUG).setResolution(null));
indexIssues();
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.webhook.WebhookDto;
import org.sonar.server.es.TestProjectIndexers;
ProjectDto project = dbClient.projectDao().selectByUuid(dbSession, componentDto.uuid()).get();
BranchDto branch = dbClient.branchDao().selectByUuid(dbSession, project.getUuid()).get();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, componentDto);
SnapshotDto analysis = db.components().insertSnapshot(componentDto);
mockResourceTypeAsValidProject();
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.index.IssueIndex;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
}
private void insertIssue(ComponentDto component, SnapshotDto analysis) {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setType(randomRuleTypeExceptHotspot()));
+ RuleDto rule = db.rules().insert(r -> r.setType(randomRuleTypeExceptHotspot()));
db.issues().insert(rule, component, component,
i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt()))
.setAssigneeUuid(userSession.getUuid())
}
private void insertSecurityHotspot(ComponentDto component, SnapshotDto analysis) {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setType(RuleType.SECURITY_HOTSPOT));
+ RuleDto rule = db.rules().insert(r -> r.setType(RuleType.SECURITY_HOTSPOT));
db.issues().insert(rule, component, component,
i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt()))
.setAssigneeUuid(userSession.getUuid())
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
public void fails_with_NotFoundException_if_issue_is_not_a_hotspot(RuleType ruleType) {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insert(t -> t.setType(ruleType));
+ RuleDto rule = dbTester.rules().insert(t -> t.setType(ruleType));
IssueDto notAHotspot = dbTester.issues().insertIssue(rule, project, file, i -> i.setType(ruleType));
userSessionRule.logIn();
TestRequest request = newRequest(notAHotspot, randomAlphabetic(12));
public void fails_with_NotFoundException_if_hotspot_is_closed() {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insertHotspotRule();
+ RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED));
userSessionRule.logIn();
TestRequest request = newRequest(hotspot, randomAlphabetic(12));
ComponentDto project = dbTester.components().insertPrivateProject();
userSessionRule.logIn().registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insertHotspotRule();
+ RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
String comment = randomAlphabetic(12);
TestRequest request = newRequest(hotspot, comment);
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.logIn().registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insertHotspotRule();
+ RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
String comment = randomAlphabetic(12);
ComponentDto project = dbTester.components().insertPrivateProject();
userSessionRule.logIn().registerComponents(project).addProjectPermission(UserRole.USER, project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insertHotspotRule();
+ RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
String comment = randomAlphabetic(12);
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.logIn().registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = dbTester.rules().insertHotspotRule();
+ RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(currentStatus).setResolution(currentResolution));
String comment = randomAlphabetic(12);
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
public void fail_if_trying_to_assign_issue(RuleType ruleType, String status) {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(ruleType);
+ RuleDto rule = newRule(ruleType);
IssueDto issue = dbTester.issues().insertIssue(rule, project, file, i -> i
.setStatus(status)
.setType(ruleType));
public void fail_with_NotFoundException_if_hotspot_is_closed() {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto issue = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED));
UserDto me = insertUser(randomAlphanumeric(10));
userSessionRule.logIn().registerComponents(project);
request.execute().assertNoContent();
}
- private RuleDefinitionDto newRule(RuleType ruleType) {
- RuleDefinitionDto ruleDefinition = RuleTesting.newRule()
+ private RuleDto newRule(RuleType ruleType) {
+ RuleDto ruleDto = RuleTesting.newRule()
.setType(ruleType);
- dbTester.rules().insert(ruleDefinition);
- return ruleDefinition;
+ dbTester.rules().insert(ruleDto);
+ return ruleDto;
}
private UserDto insertUser(String login) {
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
public void fails_with_NotFoundException_if_hotspot_is_closed(String status, @Nullable String resolution) {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto closedHotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED));
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
public void fails_with_NotFoundException_if_issue_is_not_a_hotspot(String status, @Nullable String resolution, RuleType ruleType) {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(ruleType);
+ RuleDto rule = newRule(ruleType);
IssueDto notAHotspot = dbTester.issues().insert(IssueTesting.newIssue(rule, project, file).setType(ruleType));
userSessionRule.logIn();
TestRequest request = newRequest(notAHotspot, status, resolution, NO_COMMENT);
return res;
}
- private RuleDefinitionDto newRule(RuleType ruleType) {
+ private RuleDto newRule(RuleType ruleType) {
return newRule(ruleType, t -> {
});
}
- private RuleDefinitionDto newRule(RuleType ruleType, Consumer<RuleDefinitionDto> populate) {
- RuleDefinitionDto ruleDefinition = RuleTesting.newRule()
+ private RuleDto newRule(RuleType ruleType, Consumer<RuleDto> populate) {
+ RuleDto ruleDto = RuleTesting.newRule()
.setType(ruleType);
- populate.accept(ruleDefinition);
- dbTester.rules().insert(ruleDefinition);
- return ruleDefinition;
+ populate.accept(ruleDto);
+ dbTester.rules().insert(ruleDto);
+ return ruleDto;
}
private static void verifyAllSame3Objects(List<DefaultIssue> allValues) {
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
indexPermissions();
IssueDto[] hotspots = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(project, file, rule);
})
.toArray(IssueDto[]::new);
Arrays.stream(RuleType.values())
.filter(t -> t != SECURITY_HOTSPOT)
.forEach(ruleType -> {
- RuleDefinitionDto rule = newRule(ruleType);
+ RuleDto rule = newRule(ruleType);
dbTester.issues().insert(rule, project, file, t -> t.setType(ruleType));
});
indexIssues();
Arrays.stream(RuleType.values())
.filter(t -> t != SECURITY_HOTSPOT)
.forEach(ruleType -> {
- RuleDefinitionDto rule = newRule(ruleType);
+ RuleDto rule = newRule(ruleType);
dbTester.issues().insert(rule, project, file, t -> t.setType(ruleType));
});
IssueDto[] hotspots = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(project, fileWithHotspot, rule);
})
.toArray(IssueDto[]::new);
indexPermissions();
IssueDto[] hotspots = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(project, project, rule);
})
.toArray(IssueDto[]::new);
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project2));
IssueDto[] hotspots2 = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
insertHotspot(project1, file1, rule);
return insertHotspot(project2, file2, rule);
})
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto[] hotspots = STATUSES.stream()
.map(status -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(rule, project, file, t -> t.setStatus(status));
})
.toArray(IssueDto[]::new);
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project2));
IssueDto[] hotspots2 = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
insertHotspot(project1, file1, rule);
return insertHotspot(project2, file2, rule);
})
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project2));
IssueDto[] hotspots2 = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
insertHotspot(project1, file1, rule);
return insertHotspot(project2, file2, rule);
})
ComponentDto filePR = dbTester.components().insertComponent(newFileDto(pullRequest));
IssueDto[] hotspotProject = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(project, fileProject, rule);
})
.toArray(IssueDto[]::new);
IssueDto[] hotspotBranch = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(branch, fileBranch, rule);
})
.toArray(IssueDto[]::new);
IssueDto[] hotspotPR = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
return insertHotspot(pullRequest, filePR, rule);
})
.toArray(IssueDto[]::new);
ComponentDto file1 = dbTester.components().insertComponent(newFileDto(project1));
IssueDto[] assigneeHotspots = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
insertHotspot(rule, project1, file1, randomAlphabetic(5));
return insertHotspot(rule, project1, file1, assigneeUuid);
})
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto unresolvedHotspot = insertHotspot(rule, project, file, t -> t.setResolution(null));
// unrealistic case since a resolution must be set, but shows a limit of current implementation (resolution is enough)
IssueDto badlyResolved = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_TO_REVIEW).setResolution(randomAlphabetic(5)));
}
private Stream<IssueDto> insertRandomNumberOfHotspotsOfAllSupportedStatusesAndResolutions(ComponentDto project, ComponentDto file) {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
List<IssueDto> hotspots = Arrays.stream(validStatusesAndResolutions())
.flatMap(objects -> {
String status = (String) objects[0];
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = insertHotspot(rule, project, file,
t -> t
.setStatus(randomAlphabetic(11))
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT, t -> t.setSecurityStandards(securityStandards));
+ RuleDto rule = newRule(SECURITY_HOTSPOT, t -> t.setSecurityStandards(securityStandards));
IssueDto hotspot = insertHotspot(project, file, rule);
indexIssues();
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
insertHotspot(rule, project, file,
t -> t.setResolution(null)
.setLine(null)
ComponentDto directory2 = dbTester.components().insertComponent(newDirectory(project, "foo/bar"));
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto fileHotspot = insertHotspot(project, file, rule);
IssueDto dirHotspot = insertHotspot(project, directory, rule);
IssueDto projectHotspot = insertHotspot(project, project, rule);
indexPermissions();
ComponentDto directory = dbTester.components().insertComponent(newDirectory(branch, "donut/acme"));
ComponentDto file = dbTester.components().insertComponent(newFileDto(branch));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto fileHotspot = insertHotspot(branch, file, rule);
IssueDto dirHotspot = insertHotspot(branch, directory, rule);
IssueDto projectHotspot = insertHotspot(branch, branch, rule);
indexPermissions();
ComponentDto directory = dbTester.components().insertComponent(newDirectory(pullRequest, "donut/acme"));
ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto fileHotspot = insertHotspot(pullRequest, file, rule);
IssueDto dirHotspot = insertHotspot(pullRequest, directory, rule);
IssueDto projectHotspot = insertHotspot(pullRequest, pullRequest, rule);
.flatMap(sqCategory -> {
Set<String> cwes = SecurityStandards.CWES_BY_SQ_CATEGORY.get(sqCategory);
Set<String> securityStandards = singleton("cwe:" + (cwes == null ? "unknown" : cwes.iterator().next()));
- RuleDefinitionDto rule1 = newRule(
+ RuleDto rule1 = newRule(
SECURITY_HOTSPOT,
t -> t.setUuid(sqCategory.name() + "_a").setName("rule_" + sqCategory.name() + "_a").setSecurityStandards(securityStandards));
- RuleDefinitionDto rule2 = newRule(
+ RuleDto rule2 = newRule(
SECURITY_HOTSPOT,
t -> t.setUuid(sqCategory.name() + "_b").setName("rule_" + sqCategory.name() + "_b").setSecurityStandards(securityStandards));
return Stream.of(
ComponentDto file1 = dbTester.components().insertComponent(newFileDto(project).setPath("b/c/a"));
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project).setPath("b/c/b"));
ComponentDto file3 = dbTester.components().insertComponent(newFileDto(project).setPath("a/a/d"));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
List<IssueDto> hotspots = Stream.of(
newHotspot(rule, project, file3).setLine(8),
newHotspot(rule, project, file3).setLine(10),
DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder().addFlow(DbIssues.Flow.newBuilder().addAllLocation(hotspotLocations));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
dbTester.issues().insertHotspot(rule, project, file, h -> h.setLocations(locations.build()));
indexIssues();
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
int total = 436;
List<IssueDto> hotspots = IntStream.range(0, total)
.mapToObj(i -> dbTester.issues().insertHotspot(rule, project, file, t -> t.setLine(i)))
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
verifyPaging(project, file, rule, 336, 100);
}
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
int total = 336;
int pageSize = 1 + new Random().nextInt(100);
verifyPaging(project, file, rule, total, pageSize);
}
- private void verifyPaging(ComponentDto project, ComponentDto file, RuleDefinitionDto rule, int total, int pageSize) {
+ private void verifyPaging(ComponentDto project, ComponentDto file, RuleDto rule, int total, int pageSize) {
List<IssueDto> hotspots = IntStream.range(0, total)
.mapToObj(i -> dbTester.issues().insertHotspot(rule, project, file, t -> t.setLine(i).setKee("issue_" + i)))
.collect(toList());
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
List<IssueDto> hotspots = IntStream.range(0, 1 + RANDOM.nextInt(15))
.mapToObj(i -> dbTester.issues().insertHotspot(rule, project, file, t -> t.setLine(i)))
.collect(toList());
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
int total = 1 + RANDOM.nextInt(20);
List<IssueDto> hotspots = IntStream.range(0, total)
.mapToObj(i -> dbTester.issues().insertHotspot(rule, project, file, t -> t.setLine(i)))
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = newRule(SECURITY_HOTSPOT);
- RuleDefinitionDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
- RuleDefinitionDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
+ RuleDto rule1 = newRule(SECURITY_HOTSPOT);
+ RuleDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
+ RuleDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
insertHotspot(project, file, rule1);
IssueDto hotspot2 = insertHotspot(project, file, rule2);
insertHotspot(project, file, rule3);
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = newRule(SECURITY_HOTSPOT);
- RuleDefinitionDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
- RuleDefinitionDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
+ RuleDto rule1 = newRule(SECURITY_HOTSPOT);
+ RuleDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
+ RuleDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
insertHotspot(project, file, rule1);
IssueDto hotspot2 = insertHotspot(project, file, rule2);
insertHotspot(project, file, rule3);
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = newRule(SECURITY_HOTSPOT);
- RuleDefinitionDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
- RuleDefinitionDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
+ RuleDto rule1 = newRule(SECURITY_HOTSPOT);
+ RuleDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
+ RuleDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
insertHotspot(project, file, rule1);
insertHotspot(project, file, rule2);
IssueDto hotspot3 = insertHotspot(project, file, rule3);
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = newRule(SECURITY_HOTSPOT);
- RuleDefinitionDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
- RuleDefinitionDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10-2021:a5", "cwe:489")));
+ RuleDto rule1 = newRule(SECURITY_HOTSPOT);
+ RuleDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
+ RuleDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10-2021:a5", "cwe:489")));
insertHotspot(project, file, rule1);
insertHotspot(project, file, rule2);
IssueDto hotspot3 = insertHotspot(project, file, rule3);
userSessionRule.registerComponents(project);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule1 = newRule(SECURITY_HOTSPOT);
- RuleDefinitionDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
- RuleDefinitionDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
+ RuleDto rule1 = newRule(SECURITY_HOTSPOT);
+ RuleDto rule2 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("cwe:117", "cwe:190")));
+ RuleDto rule3 = newRule(SECURITY_HOTSPOT, r -> r.setSecurityStandards(of("owaspTop10:a1", "cwe:601")));
insertHotspot(project, file, rule1);
insertHotspot(project, file, rule2);
IssueDto hotspot3 = insertHotspot(project, file, rule3);
indexPermissions();
ComponentDto file1 = dbTester.components().insertComponent(newFileDto(project));
ComponentDto file2 = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
final IssueDto hotspot = insertHotspot(project, file1, rule);
insertHotspot(project, file2, rule);
long periodDate = 800_996_999_332L;
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(periodDate).setLast(false));
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(periodDate - 1_500).setLast(true));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
List<IssueDto> hotspotsInLeakPeriod = IntStream.range(0, 1 + RANDOM.nextInt(20))
.mapToObj(i -> {
long issueCreationDate = periodDate + ONE_MINUTE + (RANDOM.nextInt(300) * ONE_MINUTE);
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
dbTester.components().insertSnapshot(project, t -> t.setPeriodMode(REFERENCE_BRANCH.name()).setPeriodParam("master"));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
List<IssueDto> hotspotsInLeakPeriod = IntStream.range(0, 1 + RANDOM.nextInt(20))
.mapToObj(i -> dbTester.issues().insertHotspot(rule, project, file, t -> t.setLine(i)))
.collect(toList());
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(referenceDate).setLast(false));
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(null).setLast(true));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto afterRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setIssueCreationTime(referenceDate + 1000));
IssueDto atRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setType(SECURITY_HOTSPOT).setIssueCreationTime(referenceDate));
IssueDto beforeRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setIssueCreationTime(referenceDate - 1000));
ComponentDto file = dbTester.components().insertComponent(newFileDto(pr));
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(referenceDate).setLast(true));
dbTester.components().insertSnapshot(pr, t -> t.setPeriodDate(null).setLast(true));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto afterRef = dbTester.issues().insertHotspot(rule, pr, file, t -> t.setIssueCreationTime(referenceDate + 1000));
IssueDto atRef = dbTester.issues().insertHotspot(rule, pr, file, t -> t.setType(SECURITY_HOTSPOT).setIssueCreationTime(referenceDate));
IssueDto beforeRef = dbTester.issues().insertHotspot(rule, pr, file, t -> t.setIssueCreationTime(referenceDate - 1000));
indexPermissions();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
dbTester.components().insertSnapshot(project, t -> t.setPeriodDate(referenceDate).setLast(true));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto afterRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setIssueCreationTime(referenceDate + 1000));
IssueDto atRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setType(SECURITY_HOTSPOT).setIssueCreationTime(referenceDate));
IssueDto beforeRef = dbTester.issues().insertHotspot(rule, project, file, t -> t.setIssueCreationTime(referenceDate - 1000));
ComponentDto file = dbTester.components().insertComponent(newFileDto(projectBranchComponentDto));
dbTester.components().insertSnapshot(projectBranch, t -> t.setPeriodDate(referenceDate).setLast(true));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto afterRef = dbTester.issues().insertHotspot(rule, projectBranchComponentDto, file, t -> t.setIssueCreationTime(referenceDate + 1000));
IssueDto atRef = dbTester.issues().insertHotspot(rule, projectBranchComponentDto, file, t -> t.setType(SECURITY_HOTSPOT).setIssueCreationTime(referenceDate));
IssueDto beforeRef = dbTester.issues().insertHotspot(rule, projectBranchComponentDto, file, t -> t.setIssueCreationTime(referenceDate - 1000));
IssueDto[] hotspots = IntStream.range(0, 3)
.mapToObj(i -> {
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT)
+ RuleDto rule = newRule(SECURITY_HOTSPOT)
.setSecurityStandards(Sets.newHashSet(SQCategory.WEAK_CRYPTOGRAPHY.getKey()));
return insertHotspot(rule, project, fileWithHotspot, issueDto -> issueDto.setKee("hotspot-" + i)
.setAssigneeUuid("assignee-uuid")
.assertJson(actionTester.getDef().responseExampleAsString());
}
- private IssueDto insertHotspot(ComponentDto project, ComponentDto file, RuleDefinitionDto rule) {
+ private IssueDto insertHotspot(ComponentDto project, ComponentDto file, RuleDto rule) {
return insertHotspot(rule, project, file, t -> {
});
}
- private IssueDto insertHotspot(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, @Nullable String assigneeUuid) {
+ private IssueDto insertHotspot(RuleDto rule, ComponentDto project, ComponentDto file, @Nullable String assigneeUuid) {
return insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assigneeUuid));
}
- private IssueDto insertHotspot(RuleDefinitionDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto> consumer) {
+ private IssueDto insertHotspot(RuleDto rule, ComponentDto project, ComponentDto file, Consumer<IssueDto> consumer) {
return dbTester.issues().insertHotspot(rule, project, file, consumer);
}
- private static IssueDto newHotspot(RuleDefinitionDto rule, ComponentDto project, ComponentDto component) {
+ private static IssueDto newHotspot(RuleDto rule, ComponentDto project, ComponentDto component) {
return newHotspot(rule, project, component, t -> {
});
}
- private static IssueDto newHotspot(RuleDefinitionDto rule, ComponentDto project, ComponentDto component, Consumer<IssueDto> consumer) {
+ private static IssueDto newHotspot(RuleDto rule, ComponentDto project, ComponentDto component, Consumer<IssueDto> consumer) {
IssueDto res = newIssue(rule, project, component)
.setStatus(STATUS_TO_REVIEW);
consumer.accept(res);
viewIndexer.indexAll();
}
- private RuleDefinitionDto newRule(RuleType ruleType) {
+ private RuleDto newRule(RuleType ruleType) {
return newRule(ruleType, t -> {
});
}
- private RuleDefinitionDto newRule(RuleType ruleType, Consumer<RuleDefinitionDto> populate) {
- RuleDefinitionDto ruleDefinition = RuleTesting.newRule()
+ private RuleDto newRule(RuleType ruleType, Consumer<RuleDto> populate) {
+ RuleDto ruleDto = RuleTesting.newRule()
.setType(ruleType);
- populate.accept(ruleDefinition);
- dbTester.rules().insert(ruleDefinition);
- return ruleDefinition;
+ populate.accept(ruleDto);
+ dbTester.rules().insert(ruleDto);
+ return ruleDto;
}
}
import org.sonar.db.issue.IssueDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
public void fails_with_NotFoundException_if_issue_is_not_a_hotspot(RuleType ruleType) {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(ruleType);
+ RuleDto rule = newRule(ruleType);
IssueDto notAHotspot = dbTester.issues().insertIssue(rule, project, file, i -> i.setType(ruleType));
TestRequest request = newRequest(notAHotspot);
public void fails_with_NotFoundException_if_issue_is_hotspot_is_closed() {
ComponentDto project = dbTester.components().insertPublicProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(Issue.STATUS_CLOSED));
TestRequest request = newRequest(hotspot);
ComponentDto project = dbTester.components().insertPrivateProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
TestRequest request = newRequest(hotspot);
.setEndOffset(12)
.build())
.build())));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
var hotspot = dbTester.issues().insertHotspot(rule, project, file, i -> i.setLocations(locations.build()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.registerComponents(project);
userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.addProjectPermission(permission, project);
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.addProjectPermission(permission, project);
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.addProjectPermission(permission, project);
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.addProjectPermission(permission, project);
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
userSessionRule.registerComponents(project);
userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(status).setResolution(resolution));
mockChangelogAndCommentsFormattingContext();
String description = "== Title\n<div>line1\nline2</div>";
- RuleDefinitionDto rule = newRuleWithoutSection(SECURITY_HOTSPOT,
+ RuleDto rule = newRuleWithoutSection(SECURITY_HOTSPOT,
r -> r.setTemplateUuid("123")
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), description))
.setDescriptionFormat(MARKDOWN));
userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRuleWithoutSection(SECURITY_HOTSPOT, r -> r.setTemplateUuid("123"));
+ RuleDto rule = newRuleWithoutSection(SECURITY_HOTSPOT, r -> r.setTemplateUuid("123"));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
t -> t.setLocations(DbIssues.Locations.newBuilder().build()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder()
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(randomAlphabetic(10)));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto assignee = dbTester.users().insertUser();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto assignee = dbTester.users().insertUser(t -> t.setEmail(null));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto assignee = dbTester.users().insertUser(t -> t.setActive(false));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAssigneeUuid(assignee.getUuid()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
String authorLogin = randomAlphabetic(10);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(authorLogin));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto author = dbTester.users().insertUser();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto author = dbTester.users().insertUser(t -> t.setEmail(null));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
UserDto author = dbTester.users().insertUser(t -> t.setActive(false));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setAuthorLogin(author.getLogin()));
mockChangelogAndCommentsFormattingContext();
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT, t -> t.setSecurityStandards(standards));
+ RuleDto rule = newRule(SECURITY_HOTSPOT, t -> t.setSecurityStandards(standards));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
public void returns_project_twice_when_hotspot_on_project() {
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, project,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
ComponentDto branch = dbTester.components().insertProjectBranch(project);
ComponentDto file = dbTester.components().insertComponent(newFileDto(branch));
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, branch, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
t -> t.setBranchType(BranchType.PULL_REQUEST));
ComponentDto file = dbTester.components().insertComponent(newFileDto(pullRequest));
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, pullRequest, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().build())
public void returns_hotspot_changelog_and_comments() {
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
t -> t.setLocations(DbIssues.Locations.newBuilder()
public void returns_user_details_of_users_from_ChangelogAndComments() {
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
FormattingContext formattingContext = mockChangelogAndCommentsFormattingContext();
public void returns_user_of_users_from_ChangelogAndComments_and_assignee_and_author() {
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
UserDto author = dbTester.users().insertUser();
UserDto assignee = dbTester.users().insertUser();
public void do_not_duplicate_user_if_author_assignee_ChangeLogComment_user() {
ComponentDto project = dbTester.components().insertPublicProject();
userSessionRule.registerComponents(project);
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT);
+ RuleDto rule = newRule(SECURITY_HOTSPOT);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
UserDto author = dbTester.users().insertUser();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file,
.setName("Joe"));
long time = 1577976190000L;
- RuleDefinitionDto rule = newRule(SECURITY_HOTSPOT, r -> r.setRuleKey("S4787")
+ RuleDto rule = newRule(SECURITY_HOTSPOT, r -> r.setRuleKey("S4787")
.setRepositoryKey("java")
.setName("rule-name")
.setSecurityStandards(Sets.newHashSet(SQCategory.WEAK_CRYPTOGRAPHY.getKey())));
return formattingContext;
}
- private void verifyRule(Hotspots.Rule wsRule, RuleDefinitionDto dto) {
+ private void verifyRule(Hotspots.Rule wsRule, RuleDto dto) {
assertThat(wsRule.getKey()).isEqualTo(dto.getKey().toString());
assertThat(wsRule.getName()).isEqualTo(dto.getName());
assertThat(wsRule.getSecurityCategory()).isEqualTo(SQCategory.OTHERS.getKey());
.setParam("hotspot", hotspot.getKey());
}
- private RuleDefinitionDto newRule(RuleType ruleType) {
+ private RuleDto newRule(RuleType ruleType) {
return newRule(ruleType, t -> {
});
}
- private RuleDefinitionDto newRule(RuleType ruleType, Consumer<RuleDefinitionDto> populate) {
+ private RuleDto newRule(RuleType ruleType, Consumer<RuleDto> populate) {
return newRule(ruleType, RuleTesting::newRule, populate);
}
- private RuleDefinitionDto newRuleWithoutSection(RuleType ruleType, Consumer<RuleDefinitionDto> populate) {
+ private RuleDto newRuleWithoutSection(RuleType ruleType, Consumer<RuleDto> populate) {
return newRule(ruleType, RuleTesting::newRuleWithoutDescriptionSection, populate);
}
- private RuleDefinitionDto newRule(RuleType ruleType, Supplier<RuleDefinitionDto> ruleDefinitionDtoSupplier, Consumer<RuleDefinitionDto> populate) {
- RuleDefinitionDto ruleDefinitionDto = ruleDefinitionDtoSupplier.get().setType(ruleType);
+ private RuleDto newRule(RuleType ruleType, Supplier<RuleDto> ruleDefinitionDtoSupplier, Consumer<RuleDto> populate) {
+ RuleDto ruleDefinitionDto = ruleDefinitionDtoSupplier.get().setType(ruleType);
populate.accept(ruleDefinitionDto);
dbTester.rules().insert(ruleDefinitionDto);
return ruleDefinitionDto;
import com.google.common.collect.Multiset;
import java.util.Collection;
import org.sonar.api.rule.RuleKey;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
public class RulesAggregation {
this.rules = HashMultiset.create();
}
- public RulesAggregation add(RuleDefinitionDto ruleDto) {
+ public RulesAggregation add(RuleDto ruleDto) {
rules.add(new Rule(ruleDto.getKey(), ruleDto.getName()));
return this;
}
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import static org.assertj.core.api.Assertions.assertThat;
public void count_rules() {
RulesAggregation rulesAggregation = new RulesAggregation();
RuleKey ruleKey = RuleKey.of("xoo", "S001");
- RuleDefinitionDto ruleDto = RuleTesting.newRule(ruleKey).setName("Rule name");
+ RuleDto ruleDto = RuleTesting.newRule(ruleKey).setName("Rule name");
rulesAggregation.add(ruleDto);
rulesAggregation.add(ruleDto);
public void count_rules_with_different_rules() {
RulesAggregation rulesAggregation = new RulesAggregation();
- RuleDefinitionDto ruleDto = RuleTesting.newRule(RuleKey.of("xoo", "S001")).setName("Rule name 1");
+ RuleDto ruleDto = RuleTesting.newRule(RuleKey.of("xoo", "S001")).setName("Rule name 1");
rulesAggregation.add(ruleDto);
rulesAggregation.add(ruleDto);
rulesAggregation.add(RuleTesting.newRule(RuleKey.of("xoo", "S002")).setName("Rule name 2"));
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.workflow.FunctionExecutor;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.tester.UserSessionRule;
}
private IssueDto newIssue() {
- RuleDefinitionDto rule = newRule().setUuid(Uuids.createFast());
+ RuleDto rule = newRule().setUuid(Uuids.createFast());
ComponentDto project = ComponentTesting.newPrivateProjectDto();
ComponentDto file = (newFileDto(project));
return IssueTesting.newIssue(rule, project, file);
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.workflow.FunctionExecutor;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.issue.workflow.Transition;
public void list_transitions() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(ISSUE_ADMIN, project);
public void list_transitions_returns_empty_list_on_external_issue() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto externalRule = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto externalRule = db.rules().insert(r -> r.setIsExternal(true));
IssueDto externalIssue = db.issues().insert(externalRule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(ISSUE_ADMIN, project);
public void list_transitions_returns_only_transitions_that_do_not_requires_issue_admin_permission() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn();
public void list_transitions_returns_nothing_when_not_logged() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
List<Transition> result = underTest.listTransitions(issue.toDefaultIssue());
public void do_transition() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
DefaultIssue defaultIssue = issue.toDefaultIssue();
public void do_transition_fail_on_external_issue() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto externalRule = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto externalRule = db.rules().insert(r -> r.setIsExternal(true));
IssueDto externalIssue = db.issues().insert(externalRule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
DefaultIssue defaultIssue = externalIssue.toDefaultIssue();
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.index.IssueIndexer;
import org.sonar.server.rule.DefaultRuleFinder;
@Test
public void insert_new_issues() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module));
@Test
public void update_issues() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module));
@Test
public void rule_uuid_is_set_on_updated_issue() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module));
@Test
public void rule_uuid_is_not_set_on_updated_issue_when_rule_is_removed() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setStatus(REMOVED));
+ RuleDto rule = db.rules().insert(r -> r.setStatus(REMOVED));
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module));
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDbTester;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
.extracting(IssueDto::getKey)
.containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ResourceTypesRule;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
String luke = "luke.skywalker";
ComponentDto project = db.components().insertPrivateProject();
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
indexIssues();
String luke = "luke.skywalker";
ComponentDto project = db.components().insertPrivateProject();
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
indexIssues();
ComponentDto project1 = db.components().insertPrivateProject();
ComponentDto project2 = db.components().insertPrivateProject();
permissionIndexer.allowOnlyAnyone(project1, project2);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project1, project1, issue -> issue.setAuthorLogin(leia));
db.issues().insertIssue(rule, project2, project2, issue -> issue.setAuthorLogin(luke));
indexIssues();
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, portfolio));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
indexIssues();
viewIndexer.indexAll();
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, application));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
indexIssues();
viewIndexer.indexAll();
String luke = "luke.skywalker";
ComponentDto project = db.components().insertPrivateProject();
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(han));
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(leia));
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin(luke));
public void json_example() {
ComponentDto project = db.components().insertPrivateProject();
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin("luke.skywalker"));
db.issues().insertIssue(rule, project, project, issue -> issue.setAuthorLogin("leia.organa"));
indexIssues();
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.UnauthorizedException;
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setSeverity(MAJOR).setType(CODE_SMELL)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setTags(asList("tag1", "tag2"))
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
UserDto assignee = db.users().insertUser();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setAssigneeUuid(assignee.getUuid())
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
UserDto oldAssignee = db.users().insertUser();
UserDto userToAssign = db.users().insertUser();
IssueDto issue1 = db.issues().insertIssue(rule, project, file,
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature").setBranchType(BranchType.BRANCH));
ComponentDto fileOnBranch = db.components().insertComponent(newFileDto(branch));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, branch, fileOnBranch, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("feature").setBranchType(branchType));
ComponentDto fileOnBranch = db.components().insertComponent(newFileDto(branch));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, branch, fileOnBranch, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
IssueDto issue2 = db.issues().insertIssue(rule, project, file, i -> i.setType(BUG)
ComponentDto file1 = db.components().insertComponent(newFileDto(project));
ComponentDto file2 = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file1, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
// These 2 issues will be ignored as they are resolved, changing type is not possible
ComponentDto file1 = db.components().insertComponent(newFileDto(project));
ComponentDto file2 = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file1, i -> i.setType(BUG).setSeverity(MINOR)
.setStatus(STATUS_OPEN).setResolution(null));
// These 2 issues will be ignored as there's nothing to do
ComponentDto file1 = db.components().insertComponent(newFileDto(project));
ComponentDto file2 = db.components().insertComponent(newFileDto(project));
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file1, i -> i.setType(BUG).setSeverity(MINOR)
.setStatus(STATUS_OPEN).setResolution(null));
// These 2 issues will be ignored as there's nothing to do
userSession.logIn(user);
ComponentDto project = db.components().insertPrivateProject();
addUserProjectPermissions(user, project, USER, ISSUE_ADMIN);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, project, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
- RuleDefinitionDto externalRule = db.rules().insertIssueRule(r -> r.setIsExternal(true));
+ RuleDto externalRule = db.rules().insertIssueRule(r -> r.setIsExternal(true));
IssueDto externalIssue = db.issues().insertIssue(externalRule, project, project, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
BulkChangeWsResponse response = call(builder()
ComponentDto project1 = db.components().insertPrivateProject();
addUserProjectPermissions(user, project1, USER, ISSUE_ADMIN);
ComponentDto project2 = db.components().insertPrivateProject();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto authorizedIssue = db.issues().insertIssue(rule, project1, project1, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
// User has not browse permission on these 2 issues
addUserProjectPermissions(user, project1, USER, ISSUE_ADMIN);
ComponentDto project2 = db.components().insertPrivateProject();
addUserProjectPermissions(user, project2, USER);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto authorizedIssue1 = db.issues().insertIssue(rule, project1, project1, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
// User has not issue admin permission on these 2 issues
addUserProjectPermissions(user, project1, USER, ISSUE_ADMIN);
ComponentDto project2 = db.components().insertPrivateProject();
addUserProjectPermissions(user, project2, USER);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto authorizedIssue1 = db.issues().insertIssue(rule, project1, project1, i -> i.setSeverity(MAJOR)
.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
// User has not issue admin permission on these 2 issues
userSession.logIn(user);
ComponentDto project = db.components().insertPrivateProject();
addUserProjectPermissions(user, project, USER);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, project, i -> i.setType(BUG)
.setStatus(STATUS_OPEN).setResolution(null));
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
}
private IssueDto insertNewIssue() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
return db.issues().insertIssue(rule, project, file);
}
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
public void do_transition() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn(db.users().insertUser()).addProjectPermission(USER, project, file);
public void fail_if_external_issue() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto externalRule = db.rules().insertIssueRule(r -> r.setIsExternal(true));
+ RuleDto externalRule = db.rules().insertIssueRule(r -> r.setIsExternal(true));
IssueDto externalIssue = db.issues().insertIssue(externalRule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(USER, project, file);
public void fail_if_hotspot() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertHotspotRule();
+ RuleDto rule = db.rules().insertHotspotRule();
IssueDto hotspot = db.issues().insertHotspot(rule, project, file, i -> i.setType(RuleType.SECURITY_HOTSPOT));
userSession.logIn().addProjectPermission(USER, project, file);
public void fail_if_no_transition_param() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(USER, project, file);
public void fail_if_not_enough_permission_to_access_issue() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(CODEVIEWER, project, file);
public void fail_if_not_enough_permission_to_apply_transition() {
ComponentDto project = db.components().insertPrivateProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL));
userSession.logIn().addProjectPermission(USER, project, file);
.extracting(IssueDto::getKey)
.containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.IssueFieldsSetter;
@Test
public void verify_notification_without_resolution() {
UserDto assignee = db.users().insertUser();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
DefaultIssue issue = db.issues().insertIssue(rule, project, file,
@Test
public void verify_notification_with_resolution() {
UserDto assignee = db.users().insertUser();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
DefaultIssue issue = db.issues().insertIssue(rule, project, file,
@Test
public void verify_notification_on_branch() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project, t -> t.setBranchType(BRANCH));
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void verify_no_notification_on_pr() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST));
ComponentDto file = db.components().insertComponent(newFileDto(branch));
@Test
public void verify_notification_when_issue_is_linked_on_removed_rule() {
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setStatus(RuleStatus.REMOVED));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setStatus(RuleStatus.REMOVED));
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
DefaultIssue issue = db.issues().insertIssue(rule, project, file, t -> t.setSeverity(MAJOR)).toDefaultIssue();
@Test
public void verify_notification_when_assignee_has_changed() {
UserDto oldAssignee = db.users().insertUser();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
DefaultIssue issue = db.issues().insertIssue(rule, project, file, t -> t.setAssigneeUuid(oldAssignee.getUuid()))
@Test
public void saveIssue_populates_specified_SearchResponseData_with_rule_project_and_component_retrieved_from_DB() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issueDto = db.issues().insertIssue(rule, project, file);
assertThat(preloadedSearchResponseData.getIssues().iterator().next())
.isNotSameAs(issueDto);
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(rule.getKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
@Test
public void saveIssue_populates_specified_SearchResponseData_with_no_rule_but_with_project_and_component_if_rule_is_removed() {
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setStatus(RuleStatus.REMOVED));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setStatus(RuleStatus.REMOVED));
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issueDto = db.issues().insertIssue(rule, project, file);
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.issue.IssueFieldsSetter;
@Test
public void search_all_issues_when_no_parameter() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insertIssue(rule, project, projectFile);
@Test
public void issues_on_different_projects() {
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue1 = db.issues().insertIssue(rule, project, file);
ComponentDto file1 = db.components().insertComponent(newFileDto(module1));
ComponentDto module2 = db.components().insertComponent(newModuleDto(project));
ComponentDto file2 = db.components().insertComponent(newFileDto(module2));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file1);
IssueDto issue2 = db.issues().insertIssue(rule, project, file2);
allowAnyoneOnProjects(project);
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto module = db.components().insertComponent(newModuleDto("M1", project).setDbKey("MK1"));
ComponentDto file = db.components().insertComponent(newFileDto(module, null, "F1").setDbKey("FK1"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file, i -> i.setKee("ISSUE_IN_MODULE"));
db.issues().insertIssue(rule, project, project, i -> i.setKee("ISSUE_IN_ROOT_MODULE"));
allowAnyoneOnProjects(project);
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
db.components().insertSnapshot(project, a -> a.setPeriodDate(parseDateTime("2015-09-03T00:00:00+0100").getTime()));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
IssueDto issueAfterLeak = db.issues().insertIssue(rule, project, file, i -> i.setKee(UUID_EXAMPLE_01)
.setIssueCreationDate(parseDateTime("2015-09-04T00:00:00+0100"))
.setIssueUpdateDate(parseDateTime("2015-10-04T00:00:00+0100")));
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module, null, "F1").setDbKey("FK1"));
db.components().insertSnapshot(project, a -> a.setPeriodDate(parseDateTime("2015-09-03T00:00:00+0100").getTime()));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
IssueDto issueAfterLeak = db.issues().insertIssue(rule, project, file, i -> i.setKee(UUID_EXAMPLE_01)
.setIssueCreationDate(parseDateTime("2015-09-04T00:00:00+0100"))
.setIssueUpdateDate(parseDateTime("2015-10-04T00:00:00+0100")));
public void search_by_file_uuid() {
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
allowAnyoneOnProjects(project);
indexIssues();
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
ComponentDto unitTest = db.components().insertComponent(newFileDto(project, null, "F2").setQualifier(Qualifiers.UNIT_TEST_FILE).setDbKey("FK2"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
IssueDto issueOnFile = db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
IssueDto issueOnTest = db.issues().insertIssue(rule, project, unitTest, i -> i.setKee("2bd4eac2-b650-4037-80bc-7b1182fd47d4"));
allowAnyoneOnProjects(project);
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto directory = db.components().insertComponent(newDirectory(project, "D1", "src/main/java/dir"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1").setPath(directory.path() + "/MyComponent.java"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
allowAnyoneOnProjects(project);
indexIssues();
ComponentDto directory2 = db.components().insertComponent(newDirectory(module2, "D2", "src/main/java/dir"));
ComponentDto file1 = db.components().insertComponent(newFileDto(module1, directory1, "F1").setDbKey("FK1").setPath(directory1.path() + "/MyComponent.java"));
db.components().insertComponent(newFileDto(module2, directory2, "F2").setDbKey("FK2").setPath(directory2.path() + "/MyComponent.java"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file1, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
allowAnyoneOnProjects(project);
indexIssues();
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("V1").setDbKey("MyView"));
db.components().insertComponent(newProjectCopy(project, view));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
allowAnyoneOnProjects(project, view);
indexIssuesAndViews();
public void search_by_sub_view_uuid() {
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("V1").setDbKey("MyView"));
ComponentDto subView = db.components().insertComponent(ComponentTesting.newSubPortfolio(view, "SV1", "MySubView"));
public void search_by_sub_view_uuid_return_only_authorized_view() {
ComponentDto project = db.components().insertPublicProject(p -> p.setDbKey("PK1"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "F1").setDbKey("FK1"));
- RuleDefinitionDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
+ RuleDto rule = db.rules().insertIssueRule(r -> r.setRuleKey(RuleKey.of("xoo", "x1")));
db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
ComponentDto view = db.components().insertComponent(ComponentTesting.newPortfolio("V1").setDbKey("MyView"));
ComponentDto subView = db.components().insertComponent(ComponentTesting.newSubPortfolio(view, "SV1", "MySubView"));
ComponentDto project2 = db.components().insertPrivateProject();
db.components().insertComponents(newProjectCopy(project1, application));
db.components().insertComponents(newProjectCopy(project2, application));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project1, project1);
IssueDto issue2 = db.issues().insertIssue(rule, project2, project2);
allowAnyoneOnApplication(application, project1, project2);
db.components().insertComponents(newProjectCopy(project2, applicationBranch1));
db.components().insertComponents(newProjectCopy(project1Branch2, applicationBranch2));
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
IssueDto issueOnProject1 = db.issues().insertIssue(issueRule, project1, project1);
IssueDto issueOnProject1Branch1 = db.issues().insertIssue(issueRule, project1Branch1, project1Branch1);
db.issues().insertHotspot(hotspotRule, project1Branch1, project1Branch1);
ComponentDto project = db.components().insertPublicProject();
ComponentDto application = db.components().insertPublicApplication();
db.components().insertComponents(newProjectCopy("PC1", project, application));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project);
allowAnyoneOnProjects(project);
indexIssuesAndViews();
public void search_application_without_projects() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto application = db.components().insertPublicApplication();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project);
allowAnyoneOnProjects(project, application);
indexIssuesAndViews();
@Test
public void search_by_application_and_by_leak() {
Date now = new Date();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto application = db.components().insertPublicApplication();
// Project 1
ComponentDto project1 = db.components().insertPublicProject();
ComponentDto application = db.components().insertPublicApplication();
db.components().insertComponents(newProjectCopy("PC1", project1, application));
db.components().insertComponents(newProjectCopy("PC2", project2, application));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project1, project1);
IssueDto issue2 = db.issues().insertIssue(rule, project2, project2);
allowAnyoneOnApplication(application, project1, project2);
@Test
public void search_by_application_and_project_and_leak() {
Date now = new Date();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto application = db.components().insertPublicApplication();
// Project 1
ComponentDto project1 = db.components().insertPublicProject();
@Test
public void search_by_application_and_by_leak_when_one_project_has_no_leak() {
Date now = new Date();
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto application = db.components().insertPublicApplication();
// Project 1
ComponentDto project1 = db.components().insertPublicProject();
@Test
public void search_by_branch() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insertIssue(rule, project, file);
@Test
public void return_branch_in_component_list() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
@Test
public void search_by_pull_request() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
@Test
public void search_using_main_branch_name() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
@Test
public void does_not_return_branch_issues_on_not_contextualized_search() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
@Test
public void does_not_return_branch_issues_when_using_db_key() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.AvatarResolverImpl;
ComponentDto project = db.components().insertPublicProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
ComponentDto file = db.components().insertComponent(newFileDto(module));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
UserDto user = db.users().insertUser();
db.issues().insertIssue(rule, project, file, i -> i
.setSeverity("MAJOR")
public void display_projects_facet() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file);
indexPermissions();
indexIssues();
ComponentDto file1 = db.components().insertComponent(newFileDto(project1));
ComponentDto file2 = db.components().insertComponent(newFileDto(project2));
ComponentDto file3 = db.components().insertComponent(newFileDto(project3));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project1, file1);
db.issues().insertIssue(rule, project2, file2);
db.issues().insertIssue(rule, project3, file3);
ComponentDto project = db.components().insertPublicProject();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src/main/java/dir"));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file);
indexPermissions();
indexIssues();
ComponentDto project = db.components().insertPublicProject();
ComponentDto directory = db.components().insertComponent(newDirectory(project, "src"));
ComponentDto file = db.components().insertComponent(newFileDto(project, directory));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file);
indexPermissions();
indexIssues();
ComponentDto file1 = db.components().insertComponent(newFileDto(project));
ComponentDto file2 = db.components().insertComponent(newFileDto(project));
ComponentDto file3 = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file1);
db.issues().insertIssue(rule, project, file2);
indexPermissions();
public void fail_to_display_fileUuids_facet_when_no_project_is_set() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file);
indexPermissions();
indexIssues();
ComponentDto directory = db.components().insertComponent(newDirectory(module, "dir" + index));
ComponentDto file = db.components().insertComponent(newFileDto(directory));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file, i -> i.setAssigneeUuid(user.getUuid())
.setStatus(ISSUE_STATUSES[random.nextInt(ISSUE_STATUSES.length)])
.setType(rule.getType()));
@Test
public void check_projects_facet_max_size() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IntStream.rangeClosed(1, 110)
.forEach(i -> {
ComponentDto project = db.components().insertPublicProject();
ComponentDto project2 = db.components().insertPublicProject();
ComponentDto file1 = db.components().insertComponent(newFileDto(module1));
ComponentDto file2 = db.components().insertComponent(newFileDto(module1));
- RuleDefinitionDto rule1 = db.rules().insertIssueRule();
- RuleDefinitionDto rule2 = db.rules().insertIssueRule();
+ RuleDto rule1 = db.rules().insertIssueRule();
+ RuleDto rule2 = db.rules().insertIssueRule();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.issues().insertIssue(rule1, project1, file1, i -> i
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
UserDto john = db.users().insertUser();
UserDto alice = db.users().insertUser();
db.issues().insertIssue(rule, project, file, i -> i.setAssigneeUuid(john.getUuid()));
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.rule.RuleTesting;
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
UserDto simon = db.users().insertUser();
- RuleDefinitionDto rule = newIssueRule().getDefinition();
+ RuleDto rule = newIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i
.setEffort(10L)
.setLine(42)
public void issue_on_external_rule() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo"));
+ RuleDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo"));
IssueDto issue = db.issues().insertIssue(rule, project, file);
indexPermissionsAndIssues();
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo").setIsAdHoc(true));
+ RuleDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo").setIsAdHoc(true));
IssueDto issue = db.issues().insertIssue(rule, project, file);
indexIssues();
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo").setIsAdHoc(true));
+ RuleDto rule = db.rules().insertIssueRule(RuleTesting.EXTERNAL_XOO, r -> r.setIsExternal(true).setLanguage("xoo").setIsAdHoc(true));
RuleMetadataDto ruleMetadata = db.rules().insertOrUpdateMetadata(rule, m -> m.setAdHocName("different_rule_name"));
IssueDto issue = db.issues().insertIssue(rule, project, file);
indexIssues();
.setEndOffset(12)
.build())
.build())));
- RuleDefinitionDto rule = newIssueRule().getDefinition();
+ RuleDto rule = newIssueRule();
db.issues().insertIssue(rule, project, file, i -> i.setLocations(locations.build()));
indexIssues();
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newIssueRule().getDefinition();
+ RuleDto rule = newIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
dbClient.issueChangeDao().insert(session,
new IssueChangeDto()
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newIssueRule().getDefinition();
+ RuleDto rule = newIssueRule();
IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setKee("82fd47d4-b650-4037-80bc-7b112bd4eac2"));
dbClient.issueChangeDao().insert(session,
new IssueChangeDto()
ComponentDto project = db.components().insertPublicProject();
indexPermissions();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = newIssueRule().getDefinition();
+ RuleDto rule = newIssueRule();
db.issues().insertIssue(rule, project, file, i -> i.setAssigneeUuid(simon.getUuid()).setType(CODE_SMELL));
indexIssues();
userSession.logIn("john");
ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setDbKey("PROJECT_KEY").setLanguage("java"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setDbKey("FILE_KEY").setLanguage("java"));
- db.issues().insertIssue(rule.getDefinition(), project, file);
+ db.issues().insertIssue(rule, project, file);
session.commit();
indexIssues();
ComponentDto project = db.components().insertComponent(ComponentTesting.newPublicProjectDto("PROJECT_ID").setDbKey("PROJECT_KEY").setLanguage("java"));
ComponentDto file = db.components().insertComponent(newFileDto(project, null, "FILE_ID").setDbKey("FILE_KEY").setLanguage("java"));
- db.issues().insertIssue(rule.getDefinition(), project, file);
+ db.issues().insertIssue(rule, project, file);
session.commit();
indexIssues();
public void search_by_author() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project, null));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
IssueDto issue1 = db.issues().insertIssue(rule, project, file, i -> i.setAuthorLogin("leia"));
IssueDto issue2 = db.issues().insertIssue(rule, project, file, i -> i.setAuthorLogin("luke"));
IssueDto issue3 = db.issues().insertIssue(rule, project, file, i -> i.setAuthorLogin("han, solo"));
public void only_vulnerabilities_are_returned_by_cwe() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:20", "cwe:564", "cwe:89", "cwe:943", "owaspTop10:a1"))
.setSystemTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(CODE_SMELL));
public void only_vulnerabilities_are_returned_by_owasp() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:20", "cwe:564", "cwe:89", "cwe:943", "owaspTop10:a1", "owaspTop10-2021:a2"))
.setSystemTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(CODE_SMELL));
public void only_vulnerabilities_are_returned_by_owasp_2021() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:20", "cwe:564", "cwe:89", "cwe:943", "owaspTop10:a1", "owaspTop10-2021:a2"))
.setSystemTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(CODE_SMELL));
public void only_vulnerabilities_are_returned_by_sansTop25() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:266", "cwe:732", "owaspTop10:a5"))
.setSystemTags(Sets.newHashSet("cert", "cwe", "owasp-a5", "sans-top25-porous"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("cert", "cwe", "owasp-a5", "sans-top25-porous"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(CODE_SMELL));
public void only_vulnerabilities_are_returned_by_sonarsource_security() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:20", "cwe:564", "cwe:89", "cwe:943", "owaspTop10:a1"))
.setSystemTags(Sets.newHashSet("cwe", "owasp-a1", "sans-top25-insecure", "sql"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("cwe", "owasp-a1", "sans-top25-insecure", "sql"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(CODE_SMELL));
public void security_hotspots_are_not_returned_by_default() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, file, i -> i.setType(RuleType.BUG));
db.issues().insertIssue(rule, project, file, i -> i.setType(RuleType.VULNERABILITY));
db.issues().insertIssue(rule, project, file, i -> i.setType(CODE_SMELL));
public void security_hotspots_are_not_returned_by_issues_param() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
IssueDto bugIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(RuleType.BUG));
IssueDto vulnerabilityIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(RuleType.VULNERABILITY));
IssueDto codeSmellIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(CODE_SMELL));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
IssueDto hotspot = db.issues().insertHotspot(hotspotRule, project, file);
indexPermissionsAndIssues();
public void security_hotspots_are_not_returned_by_cwe() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- Consumer<RuleDefinitionDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
+ Consumer<RuleDto> ruleConsumer = ruleDefinitionDto -> ruleDefinitionDto
.setSecurityStandards(Sets.newHashSet("cwe:20", "cwe:564", "cwe:89", "cwe:943", "owaspTop10:a1"))
.setSystemTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
Consumer<IssueDto> issueConsumer = issueDto -> issueDto.setTags(Sets.newHashSet("bad-practice", "cwe", "owasp-a1", "sans-top25-insecure", "sql"));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
+ RuleDto hotspotRule = db.rules().insertHotspotRule(ruleConsumer);
db.issues().insertHotspot(hotspotRule, project, file, issueConsumer);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule(ruleConsumer);
+ RuleDto issueRule = db.rules().insertIssueRule(ruleConsumer);
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueConsumer, issueDto -> issueDto.setType(RuleType.VULNERABILITY));
indexPermissions();
UserDto user = db.users().insertUser();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
db.issues().insertHotspot(hotspotRule, project, file, issueDto -> issueDto.setAssigneeUuid(user.getUuid()));
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
IssueDto issueDto1 = db.issues().insertIssue(issueRule, project, file, issueDto -> issueDto.setAssigneeUuid(user.getUuid()));
IssueDto issueDto2 = db.issues().insertIssue(issueRule, project, file, issueDto -> issueDto.setAssigneeUuid(user.getUuid()));
IssueDto issueDto3 = db.issues().insertIssue(issueRule, project, file, issueDto -> issueDto.setAssigneeUuid(user.getUuid()));
public void security_hotspots_are_not_returned_by_rule() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
db.issues().insertHotspot(hotspotRule, project, file);
indexPermissionsAndIssues();
public void security_hotspots_are_not_returned_by_issues_param_only() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto rule = db.rules().insertHotspotRule();
+ RuleDto rule = db.rules().insertHotspotRule();
List<IssueDto> hotspots = IntStream.range(1, 2 + new Random().nextInt(10))
.mapToObj(value -> db.issues().insertHotspot(rule, project, file))
.collect(Collectors.toList());
public void fail_if_trying_to_filter_issues_by_hotspots() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto hotspotRule = newHotspotRule().getDefinition();
+ RuleDto hotspotRule = newHotspotRule();
db.issues().insertHotspot(hotspotRule, project, file);
insertIssues(i -> i.setType(RuleType.BUG), i -> i.setType(RuleType.VULNERABILITY),
i -> i.setType(RuleType.CODE_SMELL));
public void security_hotspot_are_ignored_when_filtering_by_severities() {
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
IssueDto bugIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(RuleType.BUG).setSeverity(Severity.MAJOR.name()));
IssueDto vulnerabilityIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(RuleType.VULNERABILITY).setSeverity(Severity.MAJOR.name()));
IssueDto codeSmellIssue = db.issues().insertIssue(issueRule, project, file, i -> i.setType(CODE_SMELL).setSeverity(Severity.MAJOR.name()));
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
db.issues().insertHotspot(hotspotRule, project, file, i -> i.setSeverity(Severity.MAJOR.name()));
indexPermissions();
indexIssues();
.setName("Rule name")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc"))
.setStatus(RuleStatus.READY);
- db.rules().insert(rule.getDefinition());
+ db.rules().insert(rule);
return rule;
}
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc"))
.setStatus(RuleStatus.READY)
.setType(SECURITY_HOTSPOT_VALUE);
- db.rules().insert(rule.getDefinition());
+ db.rules().insert(rule);
return rule;
}
private void insertIssues(Consumer<IssueDto>... populators) {
UserDto john = db.users().insertUser();
userSession.logIn(john);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject();
ComponentDto file = db.components().insertComponent(newFileDto(project));
for (Consumer<IssueDto> populator : populators) {
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDbTester;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
.extracting(IssueDto::getKey)
.containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
@Test
public void fail_when_security_hotspot() {
- RuleDefinitionDto rule = db.rules().insertHotspotRule();
+ RuleDto rule = db.rules().insertHotspotRule();
ComponentDto project = db.components().insertPublicProject(newPublicProjectDto());
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issueDto = db.issues().insertHotspot(rule, project, file);
@SafeVarargs
private final IssueDto insertIssueForPublicProject(Consumer<IssueDto>... consumers) {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPublicProject(newPublicProjectDto());
ComponentDto file = db.components().insertComponent(newFileDto(project));
return db.issues().insertIssue(rule, project, file, consumers);
.extracting(IssueDto::getKey)
.containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDbTester;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
}
private IssueDto newIssueWithProject(RuleType type) {
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
ComponentDto project = dbTester.components().insertPrivateProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
return issueDbTester.insert(rule, project, file, i -> i.setType(type));
.extracting(IssueDto::getKey)
.containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
+ .extracting(RuleDto::getKey)
.containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
.extracting(ComponentDto::uuid)
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.db.issue.IssueDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.index.IssueIndex;
@Test
public void search_tags() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag3", "tag4", "tag5")));
@Test
public void search_tags_ignores_hotspots() {
ComponentDto project = db.components().insertPrivateProject();
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
Consumer<IssueDto> setTags = issue -> issue.setTags(asList("tag1", "tag2"));
db.issues().insertIssue(issueRule, project, project, setTags);
db.issues().insertHotspot(hotspotRule, project, project, setTags);
@Test
public void search_tags_by_query() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag12", "tag4", "tag5")));
@Test
public void search_tags_by_query_ignores_hotspots() {
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
ComponentDto project = db.components().insertPrivateProject();
db.issues().insertIssue(issueRule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
db.issues().insertHotspot(hotspotRule, project, project, issue -> issue.setTags(asList("tag1", "tag12", "tag4", "tag5")));
@Test
public void search_tags_by_project() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project1 = db.components().insertPrivateProject();
ComponentDto project2 = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project1, project1, issue -> issue.setTags(singletonList("tag1")));
@Test
public void search_tags_by_branch_equals_main_branch() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
@Test
public void search_tags_by_branch() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
@Test
public void search_tags_by_branch_not_exist_fall_back_to_main_branch() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
@Test
public void search_all_tags_by_query() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
@Test
public void search_tags_by_project_ignores_hotspots() {
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
ComponentDto project1 = db.components().insertPrivateProject();
ComponentDto project2 = db.components().insertPrivateProject();
db.issues().insertHotspot(hotspotRule, project1, project1, issue -> issue.setTags(singletonList("tag1")));
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, portfolio));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(singletonList("cwe")));
indexIssues();
viewIndexer.indexAll();
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, portfolio));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
db.issues().insertHotspot(hotspotRule, project, project, issue -> issue.setTags(singletonList("cwe")));
db.issues().insertIssue(issueRule, project, project, issue -> issue.setTags(singletonList("foo")));
indexIssues();
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, application));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(singletonList("cwe")));
indexIssues();
viewIndexer.indexAll();
ComponentDto project = db.components().insertPrivateProject();
db.components().insertComponent(newProjectCopy(project, application));
permissionIndexer.allowOnlyAnyone(project);
- RuleDefinitionDto issueRule = db.rules().insertIssueRule();
- RuleDefinitionDto hotspotRule = db.rules().insertHotspotRule();
+ RuleDto issueRule = db.rules().insertIssueRule();
+ RuleDto hotspotRule = db.rules().insertHotspotRule();
db.issues().insertIssue(issueRule, project, project, issue -> issue.setTags(singletonList("cwe")));
db.issues().insertHotspot(hotspotRule, project, project, issue -> issue.setTags(singletonList("foo")));
indexIssues();
@Test
public void return_limited_size() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag1", "tag2")));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("tag3", "tag4", "tag5")));
@Test
public void do_not_return_issues_without_permission() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project1 = db.components().insertPrivateProject();
ComponentDto project2 = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project1, project1, issue -> issue.setTags(asList("tag1", "tag2")));
@Test
public void json_example() {
- RuleDefinitionDto rule = db.rules().insertIssueRule();
+ RuleDto rule = db.rules().insertIssueRule();
ComponentDto project = db.components().insertPrivateProject();
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(asList("convention", "security")));
db.issues().insertIssue(rule, project, project, issue -> issue.setTags(singletonList("cwe")));
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.builtin.QProfileName;
import org.sonar.server.rule.RuleCreator;
@Test
public void backup_generates_xml_file() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule.getLanguage());
ActiveRuleDto activeRule = activate(profile, rule);
@Test
public void backup_rules_having_parameters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto profile = createProfile(rule.getLanguage());
ActiveRuleDto activeRule = activate(profile, rule, param);
@Test
public void backup_empty_profile() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule.getLanguage());
StringWriter writer = new StringWriter();
@Test
public void backup_custom_rules_with_params() {
- RuleDefinitionDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
+ RuleDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
.setIsTemplate(true));
- RuleDefinitionDto rule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
+ RuleDto rule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description"))
.setName("custom rule name")
.setStatus(RuleStatus.READY)
"<priority>" + activeRule.getSeverityString() + "</priority>" +
"<name>" + rule.getName() + "</name>" +
"<templateKey>" + templateRule.getKey().rule() + "</templateKey>" +
- "<description>" + rule.getDefaultRuleDescriptionSectionDto().getContent() + "</description>" +
- "<descriptionSections><descriptionSection><key>default</key><content>" + rule.getDefaultRuleDescriptionSectionDto().getContent() + "</content></descriptionSection></descriptionSections>" +
+ "<description>" + rule.getDefaultRuleDescriptionSection().getContent() + "</description>" +
+ "<descriptionSections><descriptionSection><key>default</key><content>" + rule.getDefaultRuleDescriptionSection().getContent() + "</content></descriptionSection></descriptionSections>" +
"<parameters><parameter>" +
"<key>" + param.getName() + "</key>" +
"<value>20</value>" +
@Test
public void copy_profile() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto from = createProfile(rule.getLanguage());
ActiveRuleDto activeRule = activate(from, rule, param);
.hasMessage("The quality profile cannot be restored as it contains rules from external rule engines: sonarjs:s001");
}
- private RuleDefinitionDto createRule() {
+ private RuleDto createRule() {
return db.rules().insert();
}
return db.qualityProfiles().insert(p -> p.setLanguage(language));
}
- private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule) {
+ private ActiveRuleDto activate(QProfileDto profile, RuleDto rule) {
return db.qualityProfiles().activateRule(profile, rule);
}
- private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule, RuleParamDto param) {
+ private ActiveRuleDto activate(QProfileDto profile, RuleDto rule, RuleParamDto param) {
ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile, rule);
ActiveRuleParamDto dto = ActiveRuleParamDto.createFor(param)
.setValue("20")
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
private QProfileRules qProfileRules;
private QProfileComparison comparison;
- private RuleDefinitionDto xooRule1;
- private RuleDefinitionDto xooRule2;
+ private RuleDto xooRule1;
+ private RuleDto xooRule2;
private QProfileDto left;
private QProfileDto right;
qProfileRules = new QProfileRulesImpl(db, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService);
comparison = new QProfileComparison(db);
- xooRule1 = RuleTesting.newXooX1().setSeverity("MINOR").getDefinition();
- xooRule2 = RuleTesting.newXooX2().setSeverity("MAJOR").getDefinition();
+ xooRule1 = RuleTesting.newXooX1().setSeverity("MINOR");
+ xooRule2 = RuleTesting.newXooX2().setSeverity("MAJOR");
db.ruleDao().insert(dbSession, xooRule1);
db.ruleDao().insert(dbSession, xooRule2);
db.ruleDao().insertRuleParam(dbSession, xooRule1, RuleParamDto.createFor(xooRule1)
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.rule.DefaultRuleFinder;
new StandardExporter(), new XooExporter()};
private final ProfileImporter[] importers = new ProfileImporter[] {
new XooProfileImporter(), new XooProfileImporterWithMessages(), new XooProfileImporterWithError()};
- private RuleDefinitionDto rule;
+ private RuleDto rule;
private final QProfileRules qProfileRules = mock(QProfileRules.class);
private final QProfileExporters underTest = new QProfileExporters(db.getDbClient(), ruleFinder, qProfileRules, exporters, importers);
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
private DbSession dbSession = db.getSession();
private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private QProfileFactory underTest = new QProfileFactoryImpl(db.getDbClient(), new SequenceUuidFactory(), system2, activeRuleIndexer);
- private RuleDefinitionDto rule;
+ private RuleDto rule;
private RuleParamDto ruleParam;
@Before
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
@Test
public void reset() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE));
- RuleDefinitionDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
qProfileRules.activateAndCommit(db.getSession(), profile, singleton(RuleActivation.create(existingRule.getUuid())));
- RuleDefinitionDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
BulkChangeResult result = underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(newRule.getUuid())));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE));
QProfileDto childProfile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE));
qProfileTree.setParentAndCommit(db.getSession(), childProfile, parentProfile);
- RuleDefinitionDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
qProfileRules.activateAndCommit(db.getSession(), parentProfile, singleton(RuleActivation.create(existingRule.getUuid())));
qProfileRules.activateAndCommit(db.getSession(), childProfile, singleton(RuleActivation.create(existingRule.getUuid())));
- RuleDefinitionDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
underTest.reset(db.getSession(), childProfile, singletonList(RuleActivation.create(newRule.getUuid())));
@Test
public void fail_when_profile_is_built_in() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE).setIsBuiltIn(true));
- RuleDefinitionDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
assertThatThrownBy(() -> {
underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid())));
@Test
public void fail_when_profile_is_not_persisted() {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto().setRulesProfileUuid(null).setLanguage(LANGUAGE);
- RuleDefinitionDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
+ RuleDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE));
assertThatThrownBy(() -> {
underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid())));
package org.sonar.server.qualityprofile;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.es.EsTester;
@Test
public void system_activates_rule_without_parameters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null);
List<ActiveRuleChange> changes = activate(profile, activation);
@Test
public void user_activates_rule_without_parameters() {
userSession.logIn();
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null);
List<ActiveRuleChange> changes = activate(profile, activation);
@Test
public void activate_rule_with_default_severity_and_parameters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void activate_rule_with_parameters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void activate_rule_with_default_severity() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
*/
@Test
public void activate_rule_with_empty_parameter_having_no_default_value() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
*/
@Test
public void activate_rule_with_negative_integer_value_on_parameter_having_no_default_value() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null));
RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void activation_ignores_unsupported_parameters() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void update_an_already_activated_rule() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void update_activation_with_parameter_without_default_value() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null));
RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void reset_parameter_to_default_value() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void update_activation_removes_parameter_without_default_value() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null));
RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void update_activation_with_new_parameter() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void ignore_activation_without_changes() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
// initial activation
@Test
public void do_not_change_severity_and_params_if_unset_and_already_activated() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10"));
QProfileDto profile = createProfile(rule);
@Test
public void fail_to_activate_rule_if_profile_is_on_different_languages() {
- RuleDefinitionDto rule = createJavaRule();
+ RuleDto rule = createJavaRule();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("js"));
RuleActivation activation = RuleActivation.create(rule.getUuid());
@Test
public void fail_to_activate_rule_if_rule_has_REMOVED_status() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
+ RuleDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
@Test
public void fail_to_activate_if_template() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setIsTemplate(true));
+ RuleDto rule = db.rules().insert(r -> r.setIsTemplate(true));
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
@Test
public void fail_to_activate_if_invalid_parameter() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10").setType(PropertyType.INTEGER.name()));
QProfileDto profile = createProfile(rule);
@Test
public void ignore_parameters_when_activating_custom_rule() {
- RuleDefinitionDto templateRule = db.rules().insert(r -> r.setIsTemplate(true));
+ RuleDto templateRule = db.rules().insert(r -> r.setIsTemplate(true));
RuleParamDto templateParam = db.rules().insertRuleParam(templateRule, p -> p.setName("format"));
- RuleDefinitionDto customRule = db.rules().insert(newCustomRule(templateRule));
+ RuleDto customRule = db.rules().insert(newCustomRule(templateRule));
RuleParamDto customParam = db.rules().insertRuleParam(customRule, p -> p.setName("format").setDefaultValue("txt"));
QProfileDto profile = createProfile(customRule);
@Test
public void user_deactivates_a_rule() {
userSession.logIn();
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
List<ActiveRuleChange> changes = activate(profile, activation);
@Test
public void system_deactivates_a_rule() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
List<ActiveRuleChange> changes = activate(profile, activation);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage()));
}
- private void assertThatChangeIsDeactivation(List<ActiveRuleChange> changes, RuleDefinitionDto rule) {
+ private void assertThatChangeIsDeactivation(List<ActiveRuleChange> changes, RuleDto rule) {
assertThat(changes).hasSize(1);
ActiveRuleChange change = changes.get(0);
assertThat(change.getType()).isEqualTo(ActiveRuleChange.Type.DEACTIVATED);
@Test
public void ignore_deactivation_if_rule_is_not_activated() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
List<ActiveRuleChange> changes = deactivate(profile, rule);
@Test
public void deactivate_rule_that_has_REMOVED_status() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
RuleActivation activation = RuleActivation.create(rule.getUuid());
List<ActiveRuleChange> changes = activate(profile, activation);
@Test
public void activation_on_child_profile_is_propagated_to_descendants() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
QProfileDto grandChildProfile = createChildProfile(childProfile);
@Test
public void update_on_child_profile_is_propagated_to_descendants() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void override_activation_of_inherited_profile() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void updated_activation_on_parent_is_not_propagated_to_overridden_profiles() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void reset_on_parent_is_not_propagated_to_overridden_profiles() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
RuleActivation updateActivation = RuleActivation.createReset(rule.getUuid());
changes = activate(parentProfile, updateActivation);
- assertThatRuleIsUpdated(parentProfile, rule, rule.getSeverityString(), null, of(param.getName(), param.getDefaultValue()));
+ Map<String, String> test = new HashMap<>();
+ test.put(param.getName(), param.getDefaultValue());
+ assertThatRuleIsUpdated(parentProfile, rule, rule.getSeverityString(), null, test);
assertThatRuleIsUpdated(childProfile, rule, rule.getSeverityString(), INHERITED, of(param.getName(), param.getDefaultValue()));
assertThatRuleIsUpdated(grandChildProfile, rule, CRITICAL, ActiveRuleInheritance.OVERRIDES, of(param.getName(), "bar"));
assertThat(changes).hasSize(2);
@Test
public void active_on_parent_a_rule_already_activated_on_child() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void do_not_mark_as_overridden_if_same_values_than_parent() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
RuleParamDto param = db.rules().insertRuleParam(rule);
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void propagate_deactivation_on_children() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void propagate_deactivation_on_children_even_when_overridden() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void cannot_deactivate_rule_inherited() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void reset_child_profile_do_not_change_parent() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void reset_parent_is_not_propagated_when_child_overrides() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto baseProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(baseProfile);
QProfileDto grandChildProfile = createChildProfile(childProfile);
@Test
public void ignore_reset_if_not_activated() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
createChildProfile(parentProfile);
assertThat(bulkChangeResult.countSucceeded()).isEqualTo(bulkSize);
assertThat(bulkChangeResult.getChanges()).hasSize(bulkSize);
assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)).hasSize(bulkSize);
- rules.stream().forEach(
- r -> assertThatRuleIsActivated(profile, r.getDefinition(), null, MINOR, null, emptyMap()));
+ rules.forEach(r -> assertThatRuleIsActivated(profile, r, null, MINOR, null, emptyMap()));
}
@Test
assertThat(bulkChangeResult.countSucceeded()).isEqualTo(bulkSize);
assertThat(bulkChangeResult.getChanges()).hasSize(bulkSize);
assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)).isEmpty();
- rules.stream().forEach(
- r -> assertThatRuleIsNotPresent(profile, r.getDefinition()));
+ rules.forEach(r -> assertThatRuleIsNotPresent(profile, r));
}
@Test
public void bulk_deactivation_ignores_errors() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void bulk_change_severity() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
QProfileDto parentProfile = createProfile(rule1);
QProfileDto childProfile = createChildProfile(parentProfile);
QProfileDto grandchildProfile = createChildProfile(childProfile);
@Test
public void delete_rule_from_all_profiles() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
QProfileDto grandChildProfile = createChildProfile(childProfile);
@Test
public void activation_fails_when_profile_is_built_in() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto builtInProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
assertThatThrownBy(() -> {
assertThat(activeRules).isEmpty();
}
- private List<ActiveRuleChange> deactivate(QProfileDto profile, RuleDefinitionDto rule) {
+ private List<ActiveRuleChange> deactivate(QProfileDto profile, RuleDto rule) {
return underTest.deactivateAndCommit(db.getSession(), profile, singleton(rule.getUuid()));
}
return underTest.activateAndCommit(db.getSession(), profile, singleton(activation));
}
- private QProfileDto createProfile(RuleDefinitionDto rule) {
+ private QProfileDto createProfile(RuleDto rule) {
return db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()));
}
assertThat(loaded.getRulesUpdatedAt()).isNotEmpty();
}
- private void assertThatRuleIsActivated(QProfileDto profile, RuleDefinitionDto rule, @Nullable List<ActiveRuleChange> changes,
+ private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
}
}
- private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDefinitionDto rule) {
+ private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDto rule) {
Optional<OrgActiveRuleDto> activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
.filter(ar -> ar.getRuleKey().equals(rule.getKey()))
assertThat(activeRule).isEmpty();
}
- private void assertThatRuleIsUpdated(QProfileDto profile, RuleDefinitionDto rule,
+ private void assertThatRuleIsUpdated(QProfileDto profile, RuleDto rule,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
assertThat(db.countRowsOfTable(db.getSession(), "active_rules")).isZero();
}
- private RuleDefinitionDto createRule() {
+ private RuleDto createRule() {
return db.rules().insert(r -> r.setSeverity(Severity.MAJOR));
}
- private RuleDefinitionDto createJavaRule() {
+ private RuleDto createJavaRule() {
return db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("java"));
}
}
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileChangeQuery;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
@Test
public void activate_one_rule() {
QProfileDto qProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage()));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage()));
RuleActivation ruleActivation = RuleActivation.create(rule.getUuid(), Severity.CRITICAL, Collections.emptyMap());
qProfileRules.activateAndCommit(db.getSession(), qProfile, singleton(ruleActivation));
UserDto user = db.users().insertUser();
userSession.logIn(user);
QProfileDto qProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage()));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage()));
RuleActivation ruleActivation = RuleActivation.create(rule.getUuid(), Severity.CRITICAL, Collections.emptyMap());
qProfileRules.activateAndCommit(db.getSession(), qProfile, singleton(ruleActivation));
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
@Test
public void set_itself_as_parent_fails() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto profile = createProfile(rule);
assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), profile, profile))
@Test
public void set_child_as_parent_fails() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
@Test
public void set_grandchild_as_parent_fails() {
- RuleDefinitionDto rule = createRule();
+ RuleDto rule = createRule();
QProfileDto parentProfile = createProfile(rule);
QProfileDto childProfile = createChildProfile(parentProfile);
QProfileDto grandchildProfile = createChildProfile(childProfile);
@Test
public void cannot_set_parent_if_language_is_different() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("foo"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("bar"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("foo"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("bar"));
QProfileDto parentProfile = createProfile(rule1);
List<ActiveRuleChange> changes = activate(parentProfile, RuleActivation.create(rule1.getUuid()));
@Test
public void set_then_unset_parent() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
QProfileDto profile1 = createProfile(rule1);
List<ActiveRuleChange> changes = activate(profile1, RuleActivation.create(rule1.getUuid()));
@Test
public void set_then_unset_parent_keep_overridden_rules() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
QProfileDto profile1 = createProfile(rule1);
List<ActiveRuleChange> changes = activate(profile1, RuleActivation.create(rule1.getUuid()));
assertThat(changes).hasSize(1);
@Test
public void activation_errors_are_ignored_when_setting_a_parent() {
- RuleDefinitionDto rule1 = createJavaRule();
- RuleDefinitionDto rule2 = createJavaRule();
+ RuleDto rule1 = createJavaRule();
+ RuleDto rule2 = createJavaRule();
QProfileDto parentProfile = createProfile(rule1);
activate(parentProfile, RuleActivation.create(rule1.getUuid()));
activate(parentProfile, RuleActivation.create(rule2.getUuid()));
return qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
}
- private QProfileDto createProfile(RuleDefinitionDto rule) {
+ private QProfileDto createProfile(RuleDto rule) {
return db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()));
}
.setName("Child of " + parent.getName()));
}
- private void assertThatRuleIsActivated(QProfileDto profile, RuleDefinitionDto rule, @Nullable List<ActiveRuleChange> changes,
+ private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
}
}
- private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDefinitionDto rule) {
+ private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDto rule) {
Optional<OrgActiveRuleDto> activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
.filter(ar -> ar.getRuleKey().equals(rule.getKey()))
assertThat(activeRule).isEmpty();
}
- private void assertThatRuleIsUpdated(QProfileDto profile, RuleDefinitionDto rule,
+ private void assertThatRuleIsUpdated(QProfileDto profile, RuleDto rule,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
assertThat(params).hasSize(expectedParams.size());
}
- private RuleDefinitionDto createRule() {
+ private RuleDto createRule() {
return db.rules().insert(r -> r.setSeverity(Severity.MAJOR));
}
- private RuleDefinitionDto createJavaRule() {
+ private RuleDto createJavaRule() {
return db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("java"));
}
}
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfile;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsert;
@Test
public void do_not_send_notification_when_profile_is_not_updated() {
String language = newLanguageKey();
- RuleDefinitionDto dbRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto dbRule = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile = insertBuiltInProfile(language);
activateRuleInDb(dbProfile, dbRule, MAJOR);
addPluginProfile(dbProfile, dbRule);
@Test
public void send_notification_when_a_new_rule_is_activated() {
String language = newLanguageKey();
- RuleDefinitionDto existingRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile = insertBuiltInProfile(language);
activateRuleInDb(dbProfile, existingRule, MAJOR);
- RuleDefinitionDto newRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto newRule = db.rules().insert(r -> r.setLanguage(language));
addPluginProfile(dbProfile, existingRule, newRule);
builtInQProfileRepositoryRule.initialize();
@Test
public void send_notification_when_a_rule_is_deactivated() {
String language = newLanguageKey();
- RuleDefinitionDto existingRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile = insertBuiltInProfile(language);
activateRuleInDb(dbProfile, existingRule, MAJOR);
addPluginProfile(dbProfile);
public void send_a_single_notification_when_multiple_rules_are_activated() {
String language = newLanguageKey();
- RuleDefinitionDto existingRule1 = db.rules().insert(r -> r.setLanguage(language));
- RuleDefinitionDto newRule1 = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto existingRule1 = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto newRule1 = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile1 = insertBuiltInProfile(language);
activateRuleInDb(dbProfile1, existingRule1, MAJOR);
addPluginProfile(dbProfile1, existingRule1, newRule1);
- RuleDefinitionDto existingRule2 = db.rules().insert(r -> r.setLanguage(language));
- RuleDefinitionDto newRule2 = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto existingRule2 = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto newRule2 = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile2 = insertBuiltInProfile(language);
activateRuleInDb(dbProfile2, existingRule2, MAJOR);
addPluginProfile(dbProfile2, existingRule2, newRule2);
@Test
public void notification_does_not_include_inherited_profiles_when_rule_is_added() {
String language = newLanguageKey();
- RuleDefinitionDto newRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto newRule = db.rules().insert(r -> r.setLanguage(language));
QProfileDto builtInQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language));
QProfileDto childQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(false).setLanguage(language).setParentKee(builtInQProfileDto.getKee()));
@Test
public void notification_does_not_include_inherited_profiled_when_rule_is_changed() {
String language = newLanguageKey();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR));
QProfileDto builtInProfile = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language));
db.qualityProfiles().activateRule(builtInProfile, rule, ar -> ar.setSeverity(Severity.MINOR));
@Test
public void notification_does_not_include_inherited_profiles_when_rule_is_deactivated() {
String language = newLanguageKey();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR));
QProfileDto builtInQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language));
db.qualityProfiles().activateRule(builtInQProfileDto, rule);
@Test
public void notification_contains_send_start_and_end_date() {
String language = newLanguageKey();
- RuleDefinitionDto existingRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language));
RulesProfileDto dbProfile = insertBuiltInProfile(language);
activateRuleInDb(dbProfile, existingRule, MAJOR);
- RuleDefinitionDto newRule = db.rules().insert(r -> r.setLanguage(language));
+ RuleDto newRule = db.rules().insert(r -> r.setLanguage(language));
addPluginProfile(dbProfile, existingRule, newRule);
builtInQProfileRepositoryRule.initialize();
long startDate = RANDOM.nextInt(5000);
verify(builtInQualityProfilesNotification).onChange(any(), eq(startDate), eq(endDate));
}
- private void addPluginProfile(RulesProfileDto dbProfile, RuleDefinitionDto... dbRules) {
+ private void addPluginProfile(RulesProfileDto dbProfile, RuleDto... dbRules) {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(dbProfile.getName(), dbProfile.getLanguage());
builtInQProfileRepositoryRule.add(newLanguage(dbProfile.getLanguage()), dbProfile.getName(), false, activeRules);
}
- private static BuiltInQProfile.ActiveRule[] toActiveRules(List<BuiltInActiveRule> rules, RuleDefinitionDto[] dbRules) {
- Map<RuleKey, RuleDefinitionDto> dbRulesByRuleKey = Arrays.stream(dbRules)
- .collect(MoreCollectors.uniqueIndex(RuleDefinitionDto::getKey));
+ private static BuiltInQProfile.ActiveRule[] toActiveRules(List<BuiltInActiveRule> rules, RuleDto[] dbRules) {
+ Map<RuleKey, RuleDto> dbRulesByRuleKey = Arrays.stream(dbRules)
+ .collect(MoreCollectors.uniqueIndex(RuleDto::getKey));
return rules.stream()
.map(r -> {
RuleKey ruleKey = RuleKey.of(r.repoKey(), r.ruleKey());
- RuleDefinitionDto ruleDefinitionDto = dbRulesByRuleKey.get(ruleKey);
+ RuleDto ruleDefinitionDto = dbRulesByRuleKey.get(ruleKey);
checkState(ruleDefinitionDto != null, "Rule '%s' not found", ruleKey);
return new BuiltInQProfile.ActiveRule(ruleDefinitionDto.getUuid(), r);
}).toArray(BuiltInQProfile.ActiveRule[]::new);
}
- private void addPluginProfile(QProfileDto profile, RuleDefinitionDto... dbRules) {
+ private void addPluginProfile(QProfileDto profile, RuleDto... dbRules) {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage());
return ruleProfileDto;
}
- private void activateRuleInDb(RulesProfileDto profile, RuleDefinitionDto rule, RulePriority severity) {
+ private void activateRuleInDb(RulesProfileDto profile, RuleDto rule, RulePriority severity) {
ActiveRuleDto dto = new ActiveRuleDto()
.setProfileUuid(profile.getUuid())
.setSeverity(severity.name())
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfile;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsert;
db.qualityProfiles().insert(qProfileWithoutRule, qProfileWithOneRule);
db.qualityProfiles().setAsDefault(qProfileWithoutRule);
- RuleDefinitionDto ruleDefinition = db.rules().insert();
- db.qualityProfiles().activateRule(qProfileWithOneRule, ruleDefinition);
+ RuleDto ruleDto = db.rules().insert();
+ db.qualityProfiles().activateRule(qProfileWithOneRule, ruleDto);
db.commit();
builtInQProfileRepositoryRule.add(FOO_LANGUAGE, ruleProfileWithoutRule.getName(), true);
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileChangeQuery;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
@Test
public void insert_active_rules_and_changelog() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo");
@Test
public void insert_active_rules_with_params() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleParamDto param1 = db.rules().insertRuleParam(rule1, p -> p.setType(PropertyType.STRING.name()));
RuleParamDto param2 = db.rules().insertRuleParam(rule1, p -> p.setType(PropertyType.STRING.name()));
// TODO test lot of active_rules, params, orgas
- private void verifyActiveRuleInDb(QProfileDto profile, RuleDefinitionDto rule, String expectedSeverity, RuleParamDto... paramDtos) {
+ private void verifyActiveRuleInDb(QProfileDto profile, RuleDto rule, String expectedSeverity, RuleParamDto... paramDtos) {
ActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByKey(dbSession, ActiveRuleKey.of(profile, rule.getKey())).get();
assertThat(activeRule.getUuid()).isNotNull();
assertThat(activeRule.getInheritance()).isNull();
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfile.ActiveRule;
import org.sonar.server.rule.DefaultRuleFinder;
@Test
public void create_qprofile_with_rule() {
- RuleDefinitionDto rule1 = db.rules().insert();
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
db.rules().insert();
DummyProfileDefinition definition = new DummyProfileDefinition("foo", "foo", false, asList(rule1.getKey(), rule2.getKey()));
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definition);
@Test
public void create_qprofile_with_deprecated_rule() {
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insertDeprecatedKey(d -> d.setRuleUuid(rule1.getUuid()).setOldRepositoryKey("oldRepo").setOldRuleKey("oldKey"));
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
DummyProfileDefinition definition = new DummyProfileDefinition("foo", "foo", false,
asList(RuleKey.of("oldRepo", "oldKey"), rule2.getKey()));
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definition);
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.core.util.stream.MoreCollectors;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkState;
return builder.build();
}
- public BuiltInQProfile create(BuiltInQualityProfilesDefinition.BuiltInQualityProfile api, RuleDefinitionDto... rules) {
+ public BuiltInQProfile create(BuiltInQualityProfilesDefinition.BuiltInQualityProfile api, RuleDto... rules) {
BuiltInQProfile.Builder builder = new BuiltInQProfile.Builder()
.setLanguage(api.language())
.setName(api.name())
.setDeclaredDefault(api.isDefault());
- Map<RuleKey, RuleDefinitionDto> rulesByRuleKey = Arrays.stream(rules)
- .collect(MoreCollectors.uniqueIndex(RuleDefinitionDto::getKey));
+ Map<RuleKey, RuleDto> rulesByRuleKey = Arrays.stream(rules)
+ .collect(MoreCollectors.uniqueIndex(RuleDto::getKey));
api.rules().forEach(rule -> {
RuleKey ruleKey = RuleKey.of(rule.repoKey(), rule.ruleKey());
- RuleDefinitionDto ruleDefinition = rulesByRuleKey.get(ruleKey);
- Preconditions.checkState(ruleDefinition != null, "Rule '%s' not found", ruleKey);
- builder.addRule(new BuiltInQProfile.ActiveRule(ruleDefinition.getUuid(), rule));
+ RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
+ Preconditions.checkState(ruleDto != null, "Rule '%s' not found", ruleKey);
+ builder.addRule(new BuiltInQProfile.ActiveRule(ruleDto.getUuid(), rule));
});
return builder
.build();
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.ActiveRuleChange;
@Test
public void activate_new_rules() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule1.getRepositoryKey(), rule1.getRuleKey()).overrideSeverity(Severity.CRITICAL);
@Test
public void already_activated_rule_is_updated_in_case_of_differences() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey()).overrideSeverity(Severity.CRITICAL);
@Test
public void already_activated_rule_is_not_touched_if_no_differences() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey()).overrideSeverity(Severity.CRITICAL);
@Test
public void deactivate_rule_that_is_not_in_built_in_definition_anymore() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule2.getRepositoryKey(), rule2.getRuleKey()).overrideSeverity(Severity.MAJOR);
@Test
public void activate_deactivate_and_update_three_rules_at_the_same_time() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
- RuleDefinitionDto rule3 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule3 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
// SONAR-10473
@Test
public void activate_rule_on_built_in_profile_resets_severity_to_default_if_not_overridden() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
@Test
public void activate_rule_on_built_in_profile_resets_params_to_default_if_not_overridden() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
@Test
public void propagate_activation_to_descendant_profiles() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
// SONAR-14559
@Test
public void propagate_rule_update_to_descendant_active_rule() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
activateRuleInDb(RulesProfileDto.from(parentProfile), rule, RulePriority.valueOf(Severity.MINOR), null);
@Test
public void propagate_rule_param_update_to_descendant_active_rule_params() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
@Test
public void do_not_load_descendants_if_no_changes() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
@Test
public void propagate_deactivation_to_descendant_profiles() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
.setIsBuiltIn(false);
}
- private void assertThatRuleIsActivated(QProfileDto profile, RuleDefinitionDto rule, @Nullable List<ActiveRuleChange> changes,
+ private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
.containsExactlyInAnyOrder(expectedParams);
}
- private static void assertThatRuleIsNewlyActivated(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule, RulePriority severity) {
+ private static void assertThatRuleIsNewlyActivated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
assertThat(activeRule.getInheritance()).isNull();
assertThat(activeRule.getUpdatedAt()).isEqualTo(NOW);
}
- private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
+ private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
if (expectedInheritance != null) {
assertThat(activeRule.getUpdatedAt()).isEqualTo(NOW);
}
- private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule, RulePriority severity) {
+ private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
assertThatRuleIsUpdated(activeRules, rule, severity, null);
}
- private static void assertThatRuleIsUpdated(ActiveRuleDto activeRules, RuleDefinitionDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
+ private static void assertThatRuleIsUpdated(ActiveRuleDto activeRules, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
assertThatRuleIsUpdated(singletonList(activeRules), rule, severity, expectedInheritance);
}
- private static void assertThatRuleIsUntouched(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule, RulePriority severity) {
+ private static void assertThatRuleIsUntouched(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
assertThat(activeRule.getInheritance()).isNull();
assertThat(activeRule.getUpdatedAt()).isEqualTo(PAST);
}
- private void assertThatRuleIsDeactivated(QProfileDto profile, RuleDefinitionDto rule) {
+ private void assertThatRuleIsDeactivated(QProfileDto profile, RuleDto rule) {
Collection<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRulesAndRuleProfileUuids(
db.getSession(), singletonList(rule.getUuid()), singletonList(profile.getRulesProfileUuid()));
assertThat(activeRules).isEmpty();
}
- private static void assertThatRuleIsDeactivated(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule) {
+ private static void assertThatRuleIsDeactivated(List<ActiveRuleDto> activeRules, RuleDto rule) {
assertThat(findRule(activeRules, rule)).isEmpty();
}
assertThat(reloaded.getRulesUpdatedAt()).isNull();
}
- private static Optional<ActiveRuleDto> findRule(List<ActiveRuleDto> activeRules, RuleDefinitionDto rule) {
+ private static Optional<ActiveRuleDto> findRule(List<ActiveRuleDto> activeRules, RuleDto rule) {
return activeRules.stream()
.filter(ar -> ar.getRuleKey().equals(rule.getKey()))
.findFirst();
}
- private ActiveRuleDto activateRuleInDb(RulesProfileDto profile, RuleDefinitionDto rule, RulePriority severity) {
+ private ActiveRuleDto activateRuleInDb(RulesProfileDto profile, RuleDto rule, RulePriority severity) {
return activateRuleInDb(profile, rule, severity, null);
}
- private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDefinitionDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
+ private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
ActiveRuleDto dto = new ActiveRuleDto()
.setKey(ActiveRuleKey.of(ruleProfile, RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())))
.setProfileUuid(ruleProfile.getUuid())
import org.sonar.api.resources.Languages;
import org.sonar.core.util.Uuids;
import org.sonar.db.qualityprofile.ActiveRuleKey;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
profiles.putAll(new QProfileName(language.getKey(), profileName),
asList(new ActiveRuleChange(
type,
- ActiveRuleKey.parse("qp:repo:rule1"), new RuleDefinitionDto().setUuid(ruleUuid1)),
- new ActiveRuleChange(type, ActiveRuleKey.parse("qp:repo:rule2"), new RuleDefinitionDto().setUuid(ruleUuid2))));
+ ActiveRuleKey.parse("qp:repo:rule1"), new RuleDto().setUuid(ruleUuid1)),
+ new ActiveRuleChange(type, ActiveRuleKey.parse("qp:repo:rule2"), new RuleDto().setUuid(ruleUuid2))));
return tuple(profileName, language.getKey(), language.getName(), 2);
}
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
@Test
public void reset_overridden_active_rule() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
@Test
public void request_new_severity_and_param_for_child_rule() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
@Test
public void set_severity_and_param_for_child_rule_when_activating() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
@Test
public void fail_if_rule_language_doesnt_match_qp() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("xoo")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo")
.setRepositoryKey("repo")
.setRuleKey("rule")
.setSeverity(Severity.BLOCKER));
}
- private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDefinitionDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
+ private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
ActiveRuleDto dto = new ActiveRuleDto()
.setKey(ActiveRuleKey.of(ruleProfile, RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())))
.setProfileUuid(ruleProfile.getUuid())
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
public void fail_activate_external_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
public void activate_rule() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(RuleTesting.randomRuleKey());
+ RuleDto rule = db.rules().insert(RuleTesting.randomRuleKey());
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsClient;
QProfileDto parent1 = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
+ RuleDto rule1 = createRule();
createActiveRule(rule1, parent1);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
- RuleDefinitionDto rule2 = createRule();
+ RuleDto rule1 = createRule();
+ RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, asList(rule1.getUuid(), rule2.getUuid()));
QProfileDto parent = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
+ RuleDto rule1 = createRule();
createActiveRule(rule1, parent);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
- RuleDefinitionDto rule2 = createRule();
+ RuleDto rule1 = createRule();
+ RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
QProfileDto parent = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
+ RuleDto rule1 = createRule();
createActiveRule(rule1, parent);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
- RuleDefinitionDto rule1 = createRule();
- RuleDefinitionDto rule2 = createRule();
+ RuleDto rule1 = createRule();
+ RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, asList(rule1.getUuid(), rule2.getUuid()));
return profile;
}
- private RuleDefinitionDto createRule() {
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, randomAlphanumeric(5)))
+ private RuleDto createRule() {
+ RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, randomAlphanumeric(5)))
.setLanguage(language.getKey())
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY);
return rule;
}
- private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+ private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(dbSession, activeRule);
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
public void return_change_with_all_fields() {
QProfileDto profile = db.qualityProfiles().insert();
UserDto user = db.users().insertUser();
- RuleDefinitionDto rule = db.rules().insert(RuleKey.of("java", "S001"));
+ RuleDto rule = db.rules().insert(RuleKey.of("java", "S001"));
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, user, ImmutableMap.of(
"ruleUuid", rule.getUuid(),
"severity", "MINOR",
@Test
public void find_changelog_by_profile_key() {
QProfileDto profile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
@Test
public void find_changelog_by_language_and_name() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(qualityProfile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
public void changelog_filter_by_since() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:42+0100").getTime());
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(qualityProfile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
public void sort_changelog_events_in_reverse_chronological_order() {
QProfileDto profile = db.qualityProfiles().insert();
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:42+0100").getTime());
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, null,
ImmutableMap.of(
"ruleUuid", rule1.getUuid(),
"severity", "MINOR"));
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:43+0100").getTime());
UserDto user = db.users().insertUser();
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
insertChange(profile, ActiveRuleChange.Type.DEACTIVATED, user,
ImmutableMap.of("ruleUuid", rule2.getUuid()));
@Test
public void changelog_on_no_more_existing_user() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
insertChange(c -> c.setRulesProfileUuid(qualityProfile.getRulesProfileUuid())
.setUserUuid("UNKNOWN")
.setChangeType(ActiveRuleChange.Type.ACTIVATED.name())
String profileUuid = profile.getRulesProfileUuid();
system2.setNow(DateUtils.parseDateTime("2015-02-23T17:58:39+0100").getTime());
- RuleDefinitionDto rule1 = db.rules().insert(RuleKey.of("squid", "S2438"), r -> r.setName("\"Threads\" should not be used where \"Runnables\" are expected"));
+ RuleDto rule1 = db.rules().insert(RuleKey.of("squid", "S2438"), r -> r.setName("\"Threads\" should not be used where \"Runnables\" are expected"));
UserDto user1 = db.users().insertUser(u -> u.setLogin("anakin.skywalker").setName("Anakin Skywalker"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user1.getUuid())
.setData(ImmutableMap.of("severity", "CRITICAL", "ruleUuid", rule1.getUuid())));
system2.setNow(DateUtils.parseDateTime("2015-02-23T17:58:18+0100").getTime());
- RuleDefinitionDto rule2 = db.rules().insert(RuleKey.of("squid", "S2162"), r -> r.setName("\"equals\" methods should be symmetric and work for subclasses"));
+ RuleDto rule2 = db.rules().insert(RuleKey.of("squid", "S2162"), r -> r.setName("\"equals\" methods should be symmetric and work for subclasses"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("padme.amidala").setName("Padme Amidala"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user2.getUuid())
.setData(ImmutableMap.of("ruleUuid", rule2.getUuid())));
system2.setNow(DateUtils.parseDateTime("2014-09-12T15:20:46+0200").getTime());
- RuleDefinitionDto rule3 = db.rules().insert(RuleKey.of("squid", "S00101"), r -> r.setName("Class names should comply with a naming convention"));
+ RuleDto rule3 = db.rules().insert(RuleKey.of("squid", "S00101"), r -> r.setName("Class names should comply with a naming convention"));
UserDto user3 = db.users().insertUser(u -> u.setLogin("obiwan.kenobi").setName("Obiwan Kenobi"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user3.getUuid())
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
import org.sonar.db.rule.RuleParamDto;
public void compare_nominal() {
createRepository("blah", "xoo", "Blah");
- RuleDefinitionDto rule1 = createRule("xoo", "rule1");
- RuleDefinitionDto rule2 = createRule("xoo", "rule2");
- RuleDefinitionDto rule3 = createRule("xoo", "rule3");
- RuleDefinitionDto rule4 = createRuleWithParam("xoo", "rule4");
- RuleDefinitionDto rule5 = createRule("xoo", "rule5");
+ RuleDto rule1 = createRule("xoo", "rule1");
+ RuleDto rule2 = createRule("xoo", "rule2");
+ RuleDto rule3 = createRule("xoo", "rule3");
+ RuleDto rule4 = createRuleWithParam("xoo", "rule4");
+ RuleDto rule5 = createRule("xoo", "rule5");
/*
* Profile 1:
@Test
public void compare_param_on_left() {
- RuleDefinitionDto rule1 = createRuleWithParam("xoo", "rule1");
+ RuleDto rule1 = createRuleWithParam("xoo", "rule1");
createRepository("blah", "xoo", "Blah");
QProfileDto profile1 = createProfile("xoo", "Profile 1", "xoo-profile-1-01234");
createActiveRuleWithParam(rule1, profile1, "polop");
@Test
public void compare_param_on_right() {
- RuleDefinitionDto rule1 = createRuleWithParam("xoo", "rule1");
+ RuleDto rule1 = createRuleWithParam("xoo", "rule1");
createRepository("blah", "xoo", "Blah");
QProfileDto profile1 = createProfile("xoo", "Profile 1", "xoo-profile-1-01234");
createActiveRule(rule1, profile1);
return db.qualityProfiles().insert(p -> p.setKee(key).setName(name).setLanguage(lang));
}
- private RuleDefinitionDto createRule(String lang, String id) {
- RuleDto rule = RuleDto.createFor(RuleKey.of("blah", id))
+ private RuleDto createRule(String lang, String id) {
+ RuleDto rule = createFor(RuleKey.of("blah", id))
.setUuid(Uuids.createFast())
.setName(StringUtils.capitalize(id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setScope(Scope.MAIN)
.setStatus(RuleStatus.READY);
- RuleDefinitionDto ruleDefinition = rule.getDefinition();
- dbClient.ruleDao().insert(session, ruleDefinition);
- return ruleDefinition;
+ RuleDto ruleDto = rule;
+ dbClient.ruleDao().insert(session, ruleDto);
+ return ruleDto;
}
- private RuleDefinitionDto createRuleWithParam(String lang, String id) {
- RuleDefinitionDto rule = createRule(lang, id);
+ private static RuleDto createFor(RuleKey key) {
+ return new RuleDto()
+ .setRepositoryKey(key.repository())
+ .setRuleKey(key.rule());
+ }
+
+ private RuleDto createRuleWithParam(String lang, String id) {
+ RuleDto rule = createRule(lang, id);
RuleParamDto param = RuleParamDto.createFor(rule)
.setName("param_" + id)
.setType(RuleParamType.STRING.toString());
return rule;
}
- private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+ private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(session, activeRule);
return activeRule;
}
- private ActiveRuleDto createActiveRuleWithParam(RuleDefinitionDto rule, QProfileDto profile, String value) {
+ private ActiveRuleDto createActiveRuleWithParam(RuleDto rule, QProfileDto profile, String value) {
ActiveRuleDto activeRule = createActiveRule(rule, profile);
RuleParamDto paramDto = dbClient.ruleDao().selectRuleParamsByRuleKey(session, rule.getKey()).get(0);
ActiveRuleParamDto activeRuleParam = ActiveRuleParamDto.createFor(paramDto).setValue(value);
return activeRule;
}
- private ActiveRuleDto createActiveRuleWithSeverity(RuleDefinitionDto rule, QProfileDto profile, String severity) {
+ private ActiveRuleDto createActiveRuleWithSeverity(RuleDto rule, QProfileDto profile, String severity) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(severity);
dbClient.activeRuleDao().insert(session, activeRule);
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.BadRequestException;
public class CreateActionTest {
private static final String XOO_LANGUAGE = "xoo";
- private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
+ private static final RuleDto RULE = RuleTesting.newXooX1()
.setSeverity("MINOR")
- .setLanguage(XOO_LANGUAGE)
- .getDefinition();
+ .setLanguage(XOO_LANGUAGE);
@Rule
public DbTester db = DbTester.create();
assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
}
- private void insertRule(RuleDefinitionDto ruleDto) {
+ private void insertRule(RuleDto ruleDto) {
dbClient.ruleDao().insert(dbSession, ruleDto);
dbSession.commit();
ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
public void deactivate_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(RuleTesting.randomRuleKey());
+ RuleDto rule = db.rules().insert(RuleTesting.randomRuleKey());
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
public void fail_activate_external_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
- RuleDefinitionDto rule = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
@Test
public void fail_deactivate_if_built_in_profile() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert(profile -> profile.setIsBuiltIn(true));
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
@Test
public void inheritance_nominal() {
- RuleDefinitionDto rule1 = createRule("xoo", "rule1");
- RuleDefinitionDto rule2 = createRule("xoo", "rule2");
- RuleDefinitionDto rule3 = createRule("xoo", "rule3");
+ RuleDto rule1 = createRule("xoo", "rule1");
+ RuleDto rule2 = createRule("xoo", "rule2");
+ RuleDto rule3 = createRule("xoo", "rule3");
/*
* sonar way (2) <- companyWide (2) <- buWide (2, 1 overriding) <- (forProject1 (2), forProject2 (2))
@Test
public void inheritance_parent_child() throws Exception {
- RuleDefinitionDto rule1 = db.rules().insert();
- RuleDefinitionDto rule2 = db.rules().insert();
- RuleDefinitionDto rule3 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
+ RuleDto rule3 = db.rules().insert();
ruleIndexer.commitAndIndex(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), rule3.getUuid()));
QProfileDto parent = db.qualityProfiles().insert();
@Test
public void inheritance_ignores_removed_rules() throws Exception {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
+ RuleDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
ruleIndexer.commitAndIndex(db.getSession(), rule.getUuid());
QProfileDto profile = db.qualityProfiles().insert();
qProfileTree.setParentAndCommit(dbSession, parent, profile);
}
- private RuleDefinitionDto createRule(String lang, String id) {
+ private RuleDto createRule(String lang, String id) {
long now = new Date().getTime();
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY)
return rule;
}
- private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+ private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
long now = new Date().getTime();
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString())
return activeRule;
}
- private void overrideActiveRuleSeverity(RuleDefinitionDto rule, QProfileDto profile, String severity) {
+ private void overrideActiveRuleSeverity(RuleDto rule, QProfileDto profile, String severity) {
qProfileRules.activateAndCommit(dbSession, profile, singleton(RuleActivation.create(rule.getUuid(), severity, null)));
}
}
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
@Test
public void getRule_throws_BadRequest_if_rule_is_external() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setIsExternal(true));
+ RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
assertThatThrownBy(() -> underTest.getRule(db.getSession(), rule.getKey()))
.isInstanceOf(BadRequestException.class)
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
@Test
public void deactivate_rule() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+ RuleDto rule = createRule(profile.getLanguage(), "toto");
createActiveRule(rule, profile);
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
activeRuleIndexer.indexAll();
@Test
public void bulk_deactivate_rule() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
- RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
- RuleDefinitionDto rule2 = createRule(profile.getLanguage(), "toto3");
- RuleDefinitionDto rule3 = createRule(profile.getLanguage(), "toto4");
+ RuleDto rule0 = createRule(profile.getLanguage(), "toto1");
+ RuleDto rule1 = createRule(profile.getLanguage(), "toto2");
+ RuleDto rule2 = createRule(profile.getLanguage(), "toto3");
+ RuleDto rule3 = createRule(profile.getLanguage(), "toto4");
createActiveRule(rule0, profile);
createActiveRule(rule2, profile);
createActiveRule(rule3, profile);
public void bulk_deactivate_rule_not_all() {
QProfileDto profile = createProfile("java");
QProfileDto php = createProfile("php");
- RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto1");
- RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "toto2");
+ RuleDto rule0 = createRule(profile.getLanguage(), "toto1");
+ RuleDto rule1 = createRule(profile.getLanguage(), "toto2");
createActiveRule(rule0, profile);
createActiveRule(rule1, profile);
createActiveRule(rule0, php);
@Test
public void bulk_deactivate_rule_by_profile() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "hello");
- RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "world");
+ RuleDto rule0 = createRule(profile.getLanguage(), "hello");
+ RuleDto rule1 = createRule(profile.getLanguage(), "world");
createActiveRule(rule0, profile);
createActiveRule(rule1, profile);
dbSession.commit();
@Test
public void activate_rule() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+ RuleDto rule = createRule(profile.getLanguage(), "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
@Test
public void activate_rule_diff_languages() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule = createRule("php", "toto");
+ RuleDto rule = createRule("php", "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
@Test
public void activate_rule_override_severity() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule = createRule(profile.getLanguage(), "toto");
+ RuleDto rule = createRule(profile.getLanguage(), "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
@Test
public void bulk_activate_rule_by_query_with_severity() {
QProfileDto profile = createProfile("java");
- RuleDefinitionDto rule0 = createRule(profile.getLanguage(), "toto");
- RuleDefinitionDto rule1 = createRule(profile.getLanguage(), "tata");
+ RuleDto rule0 = createRule(profile.getLanguage(), "toto");
+ RuleDto rule1 = createRule(profile.getLanguage(), "tata");
dbSession.commit();
// 0. Assert No Active Rule for profile
QProfileDto childProfile = QualityProfileTesting.newQualityProfileDto().setParentKee(profile.getKee()).setLanguage("java");
dbClient.qualityProfileDao().insert(dbSession, profile, childProfile);
- RuleDefinitionDto rule = createRule(profile.getLanguage(), "rule");
+ RuleDto rule = createRule(profile.getLanguage(), "rule");
ActiveRuleDto active1 = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
ActiveRuleDto active2 = ActiveRuleDto.createFor(childProfile, rule)
return profile;
}
- private RuleDefinitionDto createRule(String lang, String id) {
- RuleDefinitionDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
+ private RuleDto createRule(String lang, String id) {
+ RuleDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY);
return rule;
}
- private ActiveRuleDto createActiveRule(RuleDefinitionDto rule, QProfileDto profile) {
+ private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(dbSession, activeRule);
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileDbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
@Test
public void statistics_on_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
- RuleDefinitionDto rule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto deprecatedRule1 = db.rules().insertRule(r -> r.setStatus(DEPRECATED)).getDefinition();
- RuleDefinitionDto deprecatedRule2 = db.rules().insertRule(r -> r.setStatus(DEPRECATED)).getDefinition();
- RuleDefinitionDto inactiveRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
+ RuleDto rule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto deprecatedRule1 = db.rules().insertRule(r -> r.setStatus(DEPRECATED));
+ RuleDto deprecatedRule2 = db.rules().insertRule(r -> r.setStatus(DEPRECATED));
+ RuleDto inactiveRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, rule);
db.qualityProfiles().activateRule(profile, deprecatedRule1);
db.qualityProfiles().activateRule(profile, deprecatedRule2);
p -> p.setName("Sonar way").setKee("AU-TpxcB-iU5OvuD2FL7").setIsBuiltIn(true).setLanguage(python.getKey()));
db.qualityProfiles().setAsDefault(sonarWayCs, myCompanyProfile, sonarWayPython);
// rules
- List<RuleDefinitionDto> javaRules = range(0, 10).mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey())).getDefinition())
+ List<RuleDto> javaRules = range(0, 10).mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey())))
.collect(MoreCollectors.toList());
- List<RuleDefinitionDto> deprecatedJavaRules = range(0, 5)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey()).setStatus(DEPRECATED)).getDefinition())
+ List<RuleDto> deprecatedJavaRules = range(0, 5)
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey()).setStatus(DEPRECATED)))
.collect(MoreCollectors.toList());
range(0, 7).forEach(i -> db.qualityProfiles().activateRule(myCompanyProfile, javaRules.get(i)));
range(0, 2).forEach(i -> db.qualityProfiles().activateRule(myCompanyProfile, deprecatedJavaRules.get(i)));
range(0, 10).forEach(i -> db.qualityProfiles().activateRule(myBuProfile, javaRules.get(i)));
range(0, 5).forEach(i -> db.qualityProfiles().activateRule(myBuProfile, deprecatedJavaRules.get(i)));
range(0, 2)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(python.getKey())).getDefinition())
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(python.getKey())))
.forEach(rule -> db.qualityProfiles().activateRule(sonarWayPython, rule));
range(0, 3)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())).getDefinition())
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())))
.forEach(rule -> db.qualityProfiles().activateRule(sonarWayCs, rule));
// project
range(0, 7)
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
// Active rules
range(0, 10)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition())
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Deprecated rules
range(0, 3)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()).setStatus(DEPRECATED)).getDefinition())
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()).setStatus(DEPRECATED)))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Projects
range(0, 7)
public void compare_to_sonar_way_profile() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
- RuleDefinitionDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto sonarWayRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto sonarWayRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
- RuleDefinitionDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
+ RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto sonarWayRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto sonarWayRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
+ RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(profile, profileRule1);
db.qualityProfiles().activateRule(profile, profileRule2);
public void compare_to_sonar_way_profile_when_same_active_rules() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
- RuleDefinitionDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())).getDefinition();
+ RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(sonarWayProfile, commonRule);
ruleIndexer.indexAll();
.setParentKee(parentProfile.getKee()));
// Active rules
range(0, 10)
- .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())).getDefinition())
+ .mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Projects
range(0, 7)
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Format;
import org.sonar.db.rule.RuleParamDto;
@Test
public void create_custom_rule_with_no_parameter_value() {
// insert template rule
- RuleDefinitionDto templateRule = createTemplateRuleWithIntArrayParam();
+ RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setRuleDescriptionSections(Set.of(new NewRuleDescriptionSection("default", "some description")))
@Test
public void create_custom_rule_with_multiple_parameter_values() {
// insert template rule
- RuleDefinitionDto templateRule = createTemplateRuleWithIntArrayParam();
+ RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setRuleDescriptionSections(Set.of(new NewRuleDescriptionSection("default", "some description")))
@Test
public void batch_create_custom_rules() {
// insert template rule
- RuleDefinitionDto templateRule = createTemplateRuleWithIntArrayParam();
+ RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule firstRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_1", templateRule.getKey())
.setName("My custom")
@Test
public void fail_to_create_custom_rules_when_wrong_rule_template() {
// insert rule
- RuleDefinitionDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
+ RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
dbTester.rules().insert(rule);
dbSession.commit();
@Test
public void fail_to_create_custom_rule_with_invalid_parameter() {
// insert template rule
- RuleDefinitionDto templateRule = createTemplateRuleWithIntArrayParam();
+ RuleDto templateRule = createTemplateRuleWithIntArrayParam();
assertThatThrownBy(() -> {
// Create custom rule
@Test
public void fail_to_create_custom_rule_with_invalid_parameters() {
// insert template rule
- RuleDefinitionDto templateRule = createTemplateRuleWithTwoIntParams();
+ RuleDto templateRule = createTemplateRuleWithTwoIntParams();
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description"))
.setDescriptionFormat(Format.MARKDOWN)
.setSeverity(Severity.INFO);
- dbTester.rules().insert(rule.getDefinition());
- dbTester.rules().insertRuleParam(rule.getDefinition(), param -> param.setDefaultValue("a.*"));
+ dbTester.rules().insert(rule);
+ dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*"));
dbSession.commit();
// Create custom rule with same key, but with different values
.setParameters(ImmutableMap.of("regex", "c.*"));
RuleKey customRuleKey = underTest.create(dbSession, newRule);
- RuleDefinitionDto result = dbTester.getDbClient().ruleDao().selectOrFailDefinitionByKey(dbSession, customRuleKey);
+ RuleDto result = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey);
assertThat(result.getKey()).isEqualTo(RuleKey.of("java", key));
assertThat(result.getStatus()).isEqualTo(RuleStatus.READY);
// These values should be the same than before
assertThat(result.getName()).isEqualTo("Old name");
- assertThat(result.getDefaultRuleDescriptionSectionDto().getContent()).isEqualTo("Old description");
+ assertThat(result.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Old description");
assertThat(result.getSeverityString()).isEqualTo(Severity.INFO);
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
.setName("Old name")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description"))
.setSeverity(Severity.INFO);
- dbTester.rules().insert(rule.getDefinition());
- dbTester.rules().insertRuleParam(rule.getDefinition(), param -> param.setDefaultValue("a.*"));
+ dbTester.rules().insert(rule);
+ dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*"));
dbSession.commit();
// Create custom rule with same key, but with different values
@Test
public void fail_to_create_custom_rule_when_wrong_rule_template() {
// insert rule
- RuleDefinitionDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
+ RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
dbTester.rules().insert(rule);
dbSession.commit();
.setSecurityStandards(Sets.newHashSet("owaspTop10:a1", "cwe:123"))
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
- dbTester.rules().insert(templateRule.getDefinition());
+ dbTester.rules().insert(templateRule);
dbTester.rules().insertOrUpdateMetadata(templateRule.getMetadata().setRuleUuid(templateRule.getUuid()));
- dbTester.rules().insertRuleParam(templateRule.getDefinition(), param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
- ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getDefinition().getUuid());
+ dbTester.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
+ ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid());
return templateRule;
}
- private RuleDefinitionDto createTemplateRuleWithIntArrayParam() {
- RuleDefinitionDto templateRule = newRule(RuleKey.of("java", "S002"))
+ private RuleDto createTemplateRuleWithIntArrayParam() {
+ RuleDto templateRule = newRule(RuleKey.of("java", "S002"))
.setIsTemplate(true)
.setLanguage("java")
.setConfigKey("S002")
return templateRule;
}
- private RuleDefinitionDto createTemplateRuleWithTwoIntParams() {
- RuleDefinitionDto templateRule = newRule(RuleKey.of("java", "S003"))
+ private RuleDto createTemplateRuleWithTwoIntParams() {
+ RuleDto templateRule = newRule(RuleKey.of("java", "S003"))
.setIsTemplate(true)
.setLanguage("java")
.setConfigKey("S003")
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier("1d")
.setRemediationBaseEffort("5min");
- db.rules().insert(ruleDto.getDefinition());
+ db.rules().insert(ruleDto);
db.rules().insertOrUpdateMetadata(ruleDto.getMetadata().setRuleUuid(ruleDto.getUuid()));
dbSession.commit();
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier("1d")
.setRemediationBaseEffort("5min");
- db.rules().insert(ruleDto.getDefinition());
+ db.rules().insert(ruleDto);
db.rules().insertOrUpdateMetadata(ruleDto.getMetadata().setRuleUuid(ruleDto.getUuid()));
dbSession.commit();
RuleDto ruleDto = RuleTesting.newDto(RULE_KEY)
.setNoteData("my *note*")
.setNoteUserUuid("me");
- db.rules().insert(ruleDto.getDefinition());
+ db.rules().insert(ruleDto);
db.rules().insertOrUpdateMetadata(ruleDto.getMetadata().setRuleUuid(ruleDto.getUuid()));
dbSession.commit();
// insert db
db.rules().insert(RuleTesting.newDto(RULE_KEY)
.setTags(Sets.newHashSet("security"))
- .setSystemTags(Sets.newHashSet("java8", "javadoc")).getDefinition());
+ .setSystemTags(Sets.newHashSet("java8", "javadoc")));
dbSession.commit();
// java8 is a system tag -> ignore
.setUuid("57a3af91-32f8-48b0-9e11-0eac14ffa915")
.setTags(Sets.newHashSet("security"))
.setSystemTags(Sets.newHashSet("java8", "javadoc"));
- db.rules().insert(ruleDto.getDefinition());
+ db.rules().insert(ruleDto);
db.rules().insertOrUpdateMetadata(ruleDto.getMetadata());
dbSession.commit();
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort("1min");
- db.rules().insert(ruleDto.getDefinition());
+ db.rules().insert(ruleDto);
db.rules().insertOrUpdateMetadata(ruleDto.getMetadata().setRuleUuid(ruleDto.getUuid()));
dbSession.commit();
public void update_custom_rule() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
- db.rules().insert(templateRule.getDefinition());
- db.rules().insertRuleParam(templateRule.getDefinition(), param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
- db.rules().insertRuleParam(templateRule.getDefinition(), param -> param.setName("format").setType("STRING").setDescription("Format"));
+ db.rules().insert(templateRule);
+ db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
+ db.rules().insertRuleParam(templateRule, param -> param.setName("format").setType("STRING").setDescription("Format"));
// Create custom rule
- RuleDefinitionDto customRule = newCustomRule(templateRule)
+ RuleDto customRule = newCustomRule(templateRule)
.setName("Old name")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description"))
.setSeverity(Severity.MINOR)
.setStatus(RuleStatus.BETA)
- .getDefinition();
+ ;
db.rules().insert(customRule);
db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*"));
db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("Format").setDefaultValue(null));
public void update_custom_rule_with_empty_parameter() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
- db.rules().insert(templateRule.getDefinition());
- db.rules().insertRuleParam(templateRule.getDefinition(), param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(null));
+ db.rules().insert(templateRule);
+ db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(null));
// Create custom rule
- RuleDefinitionDto customRule = newCustomRule(templateRule.getDefinition())
+ RuleDto customRule = newCustomRule(templateRule)
.setName("Old name")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description"))
.setSeverity(Severity.MINOR)
public void update_active_rule_parameters_when_updating_custom_rule() {
// Create template rule with 3 parameters
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo");
- RuleDefinitionDto templateRuleDefinition = templateRule.getDefinition();
+ RuleDto templateRuleDefinition = templateRule;
db.rules().insert(templateRuleDefinition);
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("format").setType("STRING").setDescription("format").setDefaultValue("csv"));
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("message").setType("STRING").setDescription("message"));
// Create custom rule
- RuleDefinitionDto customRule = newCustomRule(templateRule)
+ RuleDto customRule = newCustomRule(templateRule)
.setSeverity(Severity.MAJOR)
.setLanguage("xoo")
- .getDefinition();
+ ;
db.rules().insert(customRule);
RuleParamDto ruleParam1 = db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*"));
db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("format").setDefaultValue("txt"));
@Test
public void fail_to_update_custom_rule_when_empty_name() {
// Create template rule
- RuleDefinitionDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).getDefinition();
+ RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
// Create custom rule
- RuleDefinitionDto customRule = newCustomRule(templateRule);
+ RuleDto customRule = newCustomRule(templateRule);
db.rules().insert(customRule);
dbSession.commit();
public void fail_to_update_custom_rule_when_empty_description() {
// Create template rule
RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
- db.rules().insert(templateRule.getDefinition());
+ db.rules().insert(templateRule);
// Create custom rule
RuleDto customRule = newCustomRule(templateRule);
- db.rules().insert(customRule.getDefinition());
+ db.rules().insert(customRule);
dbSession.commit();
@Test
public void fail_to_update_plugin_rule_if_name_is_set() {
- RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
+ RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
- createForPluginRule(ruleDefinition.getKey()).setName("New name");
+ createForPluginRule(ruleDto.getKey()).setName("New name");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
@Test
public void fail_to_update_plugin_rule_if_description_is_set() {
- RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
+ RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
- createForPluginRule(ruleDefinition.getKey()).setMarkdownDescription("New description");
+ createForPluginRule(ruleDto.getKey()).setMarkdownDescription("New description");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
@Test
public void fail_to_update_plugin_rule_if_severity_is_set() {
- RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
+ RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("squid", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
- createForPluginRule(ruleDefinition.getKey()).setSeverity(CRITICAL);
+ createForPluginRule(ruleDto.getKey()).setSeverity(CRITICAL);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonarqube.ws.Rules;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void test_completeShow() {
ActiveRuleCompleter underTest = new ActiveRuleCompleter(dbTester.getDbClient(), new Languages());
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
QProfileDto qualityProfile = dbTester.qualityProfiles().insert();
ActiveRuleDto activeRule = dbTester.qualityProfiles().activateRule(qualityProfile, rule);
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
logInAsQProfileAdministrator();
// Template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")).setType(CODE_SMELL);
- db.rules().insert(templateRule.getDefinition());
+ db.rules().insert(templateRule);
db.rules().insertOrUpdateMetadata(templateRule.getMetadata().setRuleUuid(templateRule.getUuid()));
- db.rules().insertRuleParam(templateRule.getDefinition(), param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
+ db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
String result = ws.newRequest()
.setParam("custom_key", "MY_CUSTOM")
@Test
public void create_custom_rule_with_prevent_reactivation_param_to_true() {
logInAsQProfileAdministrator();
- RuleDefinitionDto templateRule = newTemplateRule(RuleKey.of("java", "S001")).getDefinition();
+ RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
// insert a removed rule
- RuleDefinitionDto customRule = newCustomRule(templateRule)
+ RuleDto customRule = newCustomRule(templateRule)
.setRuleKey("MY_CUSTOM")
.setStatus(RuleStatus.REMOVED)
.setName("My custom rule")
public void create_custom_rule_of_removed_template_should_fail() {
logInAsQProfileAdministrator();
- RuleDefinitionDto templateRule = db.rules().insert(r -> r.setIsTemplate(true).setStatus(RuleStatus.REMOVED));
+ RuleDto templateRule = db.rules().insert(r -> r.setIsTemplate(true).setStatus(RuleStatus.REMOVED));
TestRequest request = ws.newRequest()
.setParam("custom_key", "MY_CUSTOM")
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
public void delete_custom_rule() {
logInAsQProfileAdministrator();
- RuleDefinitionDto templateRule = dbTester.rules().insert(
+ RuleDto templateRule = dbTester.rules().insert(
r -> r.setIsTemplate(true),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
- RuleDefinitionDto customRule = dbTester.rules().insert(
+ RuleDto customRule = dbTester.rules().insert(
r -> r.setTemplateUuid(templateRule.getUuid()),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
verify(ruleIndexer).commitAndIndex(any(), eq(customRule.getUuid()));
// Verify custom rule has status REMOVED
- RuleDefinitionDto customRuleReloaded = dbClient.ruleDao().selectOrFailDefinitionByKey(dbSession, customRule.getKey());
+ RuleDto customRuleReloaded = dbClient.ruleDao().selectOrFailByKey(dbSession, customRule.getKey());
assertThat(customRuleReloaded).isNotNull();
assertThat(customRuleReloaded.getStatus()).isEqualTo(RuleStatus.REMOVED);
assertThat(customRuleReloaded.getUpdatedAt()).isNotEqualTo(PAST);
@Test
public void fail_to_delete_if_not_custom() {
logInAsQProfileAdministrator();
- RuleDefinitionDto rule = dbTester.rules().insert();
+ RuleDto rule = dbTester.rules().insert();
assertThatThrownBy(() -> {
tester.newRequest()
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.user.UserDto;
@Test
public void return_all_rules() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java"));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setLanguage("java"));
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setLanguage("java"));
indexRules();
verify(r -> {
@Test
public void return_note_login() {
UserDto user1 = db.users().insertUser();
- RuleDefinitionDto rule1 = db.rules().insert();
+ RuleDto rule1 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule1, user1);
UserDto disableUser = db.users().insertDisabledUser();
- RuleDefinitionDto rule2 = db.rules().insert();
+ RuleDto rule2 = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule2, disableUser);
indexRules();
@Test
public void filter_by_rule_key() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java"));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setLanguage("java"));
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setLanguage("java"));
indexRules();
verify(r -> r.setParam(PARAM_RULE_KEY, rule1.getKey().toString()), rule1);
@Test
public void filter_by_rule_name() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever"));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
indexRules();
verify(r -> r.setParam("q", "Be"), rule1);
@Test
public void filter_by_rule_name_requires_all_words_to_match() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever"));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
indexRules();
verify(r -> r.setParam("q", "Best other"));
@Test
public void filter_by_rule_name_does_not_interpret_query() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule for-ever"));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule for-ever"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
indexRules();
// do not interpret "-" as a "not"
@Test
public void filter_by_rule_description() {
- RuleDefinitionDto rule1 = db.rules()
+ RuleDto rule1 = db.rules()
.insert(r1 -> r1.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is the <bold>best</bold> rule now&for<b>ever</b>")));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff"));
indexRules();
verify(r -> r.setParam("q", "Best "), rule1);
@Test
public void filter_by_rule_name_or_descriptions_requires_all_words_to_match_anywhere() {
- RuleDefinitionDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever")
+ RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is a good rule")));
- RuleDefinitionDto rule2 = db.rules().insert(r1 -> r1.setName("Another thing")
+ RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Another thing")
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another thing")));
indexRules();
@Test
public void return_all_rule_fields_by_default() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
indexRules();
Rules.SearchResponse response = ws.newRequest().executeProtobuf(Rules.SearchResponse.class);
@Test
public void return_subset_of_fields() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
indexRules();
Rules.SearchResponse response = ws.newRequest()
@Test
public void return_deprecatedKeys_in_response_on_demand() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(rule1.getUuid()).setOldRuleKey("oldrulekey").setOldRepositoryKey("oldrepositorykey"));
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(rule1.getUuid()).setOldRuleKey("oldrulekey2").setOldRepositoryKey("oldrepositorykey2"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("javascript"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("javascript"));
indexRules();
@Test
public void should_filter_on_specific_tags() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
RuleMetadataDto metadata1 = insertMetadata(rule1, setTags("tag1", "tag2"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("java"));
RuleMetadataDto metadata2 = insertMetadata(rule2);
indexRules();
@Test
public void when_searching_for_several_tags_combine_them_with_OR() {
- RuleDefinitionDto bothTagsRule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto bothTagsRule = db.rules().insert(r -> r.setLanguage("java"));
insertMetadata(bothTagsRule, setTags("tag1", "tag2"));
- RuleDefinitionDto oneTagRule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto oneTagRule = db.rules().insert(r -> r.setLanguage("java"));
insertMetadata(oneTagRule, setTags("tag1"));
- RuleDefinitionDto otherTagRule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto otherTagRule = db.rules().insert(r -> r.setLanguage("java"));
insertMetadata(otherTagRule, setTags("tag2"));
- RuleDefinitionDto noTagRule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto noTagRule = db.rules().insert(r -> r.setLanguage("java"));
insertMetadata(noTagRule, setTags());
indexRules();
@Test
public void should_list_tags_in_tags_facet() {
String[] tags = get101Tags();
- RuleDefinitionDto rule = db.rules().insert(setSystemTags("x"));
+ RuleDto rule = db.rules().insert(setSystemTags("x"));
insertMetadata(rule, setTags(tags));
indexRules();
@Test
public void should_list_tags_ordered_by_count_then_by_name_in_tags_facet() {
- RuleDefinitionDto rule = db.rules().insert(setSystemTags("tag7", "tag5", "tag3", "tag1", "tag9"));
+ RuleDto rule = db.rules().insert(setSystemTags("tag7", "tag5", "tag3", "tag1", "tag9"));
insertMetadata(rule, setTags("tag2", "tag4", "tag6", "tag8", "tagA"));
db.rules().insert(setSystemTags("tag2"));
indexRules();
@Test
public void should_include_selected_matching_tag_in_facet() {
- RuleDefinitionDto rule = db.rules().insert(setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA", "x"));
+ RuleDto rule = db.rules().insert(setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA", "x"));
indexRules();
SearchResponse result = ws.newRequest()
@Test
public void should_included_selected_non_matching_tag_in_facet() {
- RuleDefinitionDto rule = db.rules().insert(setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA"));
+ RuleDto rule = db.rules().insert(setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA"));
indexRules();
SearchResponse result = ws.newRequest()
@Test
public void should_return_specific_tags() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleMetadataDto metadata = insertMetadata(rule, setTags("tag1", "tag2"));
indexRules();
@Test
public void should_return_specified_fields() {
- RuleDefinitionDto rule = db.rules().insert(r1 -> r1.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r1 -> r1.setLanguage("java"));
indexRules();
checkField(rule, "repo", Rule::getRepo, rule.getRepositoryKey());
@Test
public void return_lang_key_field_when_language_name_is_not_available() {
String unknownLanguage = "unknown_" + randomAlphanumeric(5);
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage(unknownLanguage));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage(unknownLanguage));
indexRules();
@Test
public void search_debt_rules_with_default_and_overridden_debt_values() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min"));
@Test
public void search_debt_rules_with_default_linear_offset_and_overridden_constant_debt() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min"));
@Test
public void search_debt_rules_with_default_linear_offset_and_overridden_linear_debt() {
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min"));
@Test
public void search_template_rules() {
- RuleDefinitionDto templateRule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto templateRule = db.rules().insert(r -> r.setLanguage("java")
.setIsTemplate(true));
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setTemplateUuid(templateRule.getUuid()));
indexRules();
@Test
public void search_custom_rules_from_template_key() {
- RuleDefinitionDto templateRule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto templateRule = db.rules().insert(r -> r.setLanguage("java")
.setIsTemplate(true));
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java")
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setTemplateUuid(templateRule.getUuid()));
indexRules();
@Test
public void search_all_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null);
qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
public void search_profile_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
QProfileDto waterproofProfile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleParamDto ruleParam1 = db.rules().insertRuleParam(rule, p -> p.setDefaultValue("some value")
.setType("STRING")
.setDescription("My small description")
public void search_for_active_rules_when_parameter_value_is_null() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
- RuleDefinitionDto rule = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setDefaultValue("some value")
.setType("STRING")
QProfileDto profile = db.qualityProfiles().insert(q -> q.setLanguage("language1"));
// on same language, not activated => match
- RuleDefinitionDto rule1 = db.rules().insert(r -> r
+ RuleDto rule1 = db.rules().insert(r -> r
.setLanguage(profile.getLanguage())
.setRepositoryKey("repositoryKey1")
.setSystemTags(new HashSet<>(singletonList("tag1")))
.setType(RuleType.CODE_SMELL));
// on same language, activated => no match
- RuleDefinitionDto rule2 = db.rules().insert(r -> r
+ RuleDto rule2 = db.rules().insert(r -> r
.setLanguage(profile.getLanguage())
.setRepositoryKey("repositoryKey2")
.setSystemTags(new HashSet<>(singletonList("tag2")))
qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
// on other language, not activated => no match
- RuleDefinitionDto rule3 = db.rules().insert(r -> r
+ RuleDto rule3 = db.rules().insert(r -> r
.setLanguage("language3")
.setRepositoryKey("repositoryKey3")
.setSystemTags(new HashSet<>(singletonList("tag3")))
@Test
public void statuses_facet_should_be_sticky() {
- RuleDefinitionDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
- RuleDefinitionDto rule2 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.BETA));
- RuleDefinitionDto rule3 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.DEPRECATED));
+ RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
+ RuleDto rule2 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.BETA));
+ RuleDto rule3 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.DEPRECATED));
indexRules();
public void compare_to_another_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(JAVA));
QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setLanguage(JAVA));
- RuleDefinitionDto commonRule = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
- RuleDefinitionDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
- RuleDefinitionDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
- RuleDefinitionDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
- RuleDefinitionDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
- RuleDefinitionDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA)).getDefinition();
+ RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(JAVA));
+ RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA));
+ RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA));
+ RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(JAVA));
+ RuleDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA));
+ RuleDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(profile, profileRule1);
db.qualityProfiles().activateRule(profile, profileRule2);
}
@SafeVarargs
- private final <T> void checkField(RuleDefinitionDto rule, String fieldName, Extractor<Rule, T> responseExtractor, T... expected) {
+ private final <T> void checkField(RuleDto rule, String fieldName, Extractor<Rule, T> responseExtractor, T... expected) {
SearchResponse result = ws.newRequest()
.setParam("f", fieldName)
.executeProtobuf(SearchResponse.class);
}
@SafeVarargs
- private final RuleMetadataDto insertMetadata(RuleDefinitionDto rule, Consumer<RuleMetadataDto>... populaters) {
+ private final RuleMetadataDto insertMetadata(RuleDto rule, Consumer<RuleMetadataDto>... populaters) {
RuleMetadataDto metadata = db.rules().insertOrUpdateMetadata(rule, populaters);
ruleIndexer.commitAndIndex(db.getSession(), rule.getUuid());
return metadata;
verify(requestPopulator);
}
- private void verify(Consumer<TestRequest> requestPopulator, RuleDefinitionDto... expectedRules) {
+ private void verify(Consumer<TestRequest> requestPopulator, RuleDto... expectedRules) {
TestRequest request = ws.newRequest();
requestPopulator.accept(request);
Rules.SearchResponse response = request.executeProtobuf(Rules.SearchResponse.class);
assertThat(response.getP()).isOne();
- RuleKey[] expectedRuleKeys = stream(expectedRules).map(RuleDefinitionDto::getKey).collect(MoreCollectors.toList()).toArray(new RuleKey[0]);
+ RuleKey[] expectedRuleKeys = stream(expectedRules).map(RuleDto::getKey).collect(MoreCollectors.toList()).toArray(new RuleKey[0]);
assertThat(response.getRulesList())
.extracting(r -> RuleKey.parse(r.getKey()))
.containsExactlyInAnyOrder(expectedRuleKeys);
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
-import org.sonar.db.rule.RuleDefinitionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.rule.RuleParamDto;
@Test
public void show_rule_key() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
@Test
public void show_rule_with_basic_info() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
ShowResponse result = ws.newRequest()
@Test
public void show_rule_tags() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleMetadataDto metadata = db.rules().insertOrUpdateMetadata(rule, setTags("tag1", "tag2"), m -> m.setNoteData(null).setNoteUserUuid(null));
ShowResponse result = ws.newRequest()
@Test
public void show_rule_with_note_login() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
db.rules().insertOrUpdateMetadata(rule, user);
@Test
public void show_rule_with_default_debt_infos() {
- RuleDefinitionDto rule = db.rules().insert(r -> r
+ RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h")
@Test
public void show_rule_with_only_overridden_debt() {
- RuleDefinitionDto rule = db.rules().insert(r -> r
+ RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction(null)
.setDefRemediationGapMultiplier(null)
.setDefRemediationBaseEffort(null));
@Test
public void show_rule_with_default_and_overridden_debt_infos() {
- RuleDefinitionDto rule = db.rules().insert(r -> r
+ RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h"));
@Test
public void show_rule_with_no_default_and_no_overridden_debt() {
- RuleDefinitionDto rule = db.rules().insert(r -> r
+ RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction(null)
.setDefRemediationGapMultiplier(null)
.setDefRemediationBaseEffort(null));
@Test
public void show_deprecated_rule_debt_fields() {
- RuleDefinitionDto rule = db.rules().insert(r -> r
+ RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h")
public void encode_html_description_of_custom_rule() {
// Template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
- db.rules().insert(templateRule.getDefinition());
+ db.rules().insert(templateRule);
// Custom rule
- RuleDefinitionDto customRule = newCustomRule(templateRule.getDefinition())
+ RuleDto customRule = newCustomRule(templateRule)
.addOrReplaceRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "<div>line1\nline2</div>"))
.setDescriptionFormat(MARKDOWN);
db.rules().insert(customRule);
@Test
public void show_external_rule() {
- RuleDefinitionDto externalRule = db.rules().insert(r -> r
+ RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setName("ext rule name"));
@Test
public void show_adhoc_rule() {
- RuleDefinitionDto externalRule = db.rules().insert(r -> r
+ RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setIsAdHoc(true));
RuleMetadataDto metadata = db.rules().insertOrUpdateMetadata(externalRule, m -> m
@Test
public void ignore_predefined_info_on_adhoc_rule() {
- RuleDefinitionDto externalRule = db.rules().insert(r -> r
+ RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setIsAdHoc(true)
.setName("predefined name")
@Test
public void adhoc_info_are_empty_when_no_metadata() {
- RuleDefinitionDto externalRule = db.rules().insert(r -> r
+ RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setIsAdHoc(true)
.setName(null)
@Test
public void show_rule_with_activation() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*"));
db.rules().insertOrUpdateMetadata(rule, m -> m.setNoteData(null).setNoteUserUuid(null));
QProfileDto qProfile = db.qualityProfiles().insert();
@Test
public void show_rule_without_activation() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
db.rules().insertOrUpdateMetadata(rule, m -> m.setNoteData(null).setNoteUserUuid(null));
QProfileDto qProfile = db.qualityProfiles().insert();
db.qualityProfiles().activateRule(qProfile, rule);
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
import org.sonar.server.rule.index.RuleIndex;
@Test
public void system_tag() {
- RuleDefinitionDto r = db.rules().insert(setSystemTags("tag"));
+ RuleDto r = db.rules().insert(setSystemTags("tag"));
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
String result = ws.newRequest().execute().getInput();
@Test
public void tag() {
- RuleDefinitionDto r = db.rules().insert(setSystemTags());
+ RuleDto r = db.rules().insert(setSystemTags());
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
db.rules().insertOrUpdateMetadata(r, setTags("tag"));
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleMetadataDto;
import org.sonar.db.user.UserDto;
@Test
public void update_custom_rule() {
logInAsQProfileAdministrator();
- RuleDefinitionDto templateRule = db.rules().insert(
+ RuleDto templateRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "S001")),
r -> r.setIsTemplate(true),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
- RuleDefinitionDto customRule = db.rules().insert(
+ RuleDto customRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "MY_CUSTOM")),
r -> r.setName("Old custom"),
r -> r.addOrReplaceRuleDescriptionSectionDto(createRuleDescriptionSectionDto()),
public void update_tags() {
logInAsQProfileAdministrator();
- RuleDefinitionDto rule = db.rules().insert(setSystemTags("stag1", "stag2"));
+ RuleDto rule = db.rules().insert(setSystemTags("stag1", "stag2"));
db.rules().insertOrUpdateMetadata(rule, setTags("tag1", "tag2"), m -> m.setNoteData(null).setNoteUserUuid(null));
Rules.UpdateResponse result = ws.newRequest().setMethod("POST")
public void update_rule_remediation_function() {
logInAsQProfileAdministrator();
- RuleDefinitionDto rule = db.rules().insert(
+ RuleDto rule = db.rules().insert(
r -> r.setDefRemediationFunction(LINEAR.toString()),
r -> r.setDefRemediationGapMultiplier("10d"),
r -> r.setDefRemediationBaseEffort(null));
@Test
public void update_note() {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
UserDto userHavingUpdatingNote = db.users().insertUser();
db.rules().insertOrUpdateMetadata(rule, userHavingUpdatingNote, m -> m.setNoteData("old data"));
UserDto userAuthenticated = db.users().insertUser();
@Test
public void fail_to_update_custom_when_description_is_empty() {
logInAsQProfileAdministrator();
- RuleDefinitionDto templateRule = db.rules().insert(
+ RuleDto templateRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "S001")),
r -> r.setIsTemplate(true),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
- RuleDefinitionDto customRule = db.rules().insert(
+ RuleDto customRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "MY_CUSTOM")),
r -> r.setName("Old custom"),
r -> r.addOrReplaceRuleDescriptionSectionDto(createRuleDescriptionSectionDto()),
@Test
public void throw_IllegalArgumentException_if_trying_to_update_builtin_rule_description() {
logInAsQProfileAdministrator();
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST")
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.protobuf.DbIssues;
-import org.sonar.db.rule.RuleDefinitionDto;
+import org.sonar.db.rule.RuleDto;
import org.sonar.db.source.FileSourceTester;
import org.sonar.server.component.ws.ComponentViewerJsonWriter;
import org.sonar.server.exceptions.ForbiddenException;
}
private String insertIssue(ComponentDto file, DbIssues.Location... locations) {
- RuleDefinitionDto rule = db.rules().insert();
+ RuleDto rule = db.rules().insert();
DbIssues.Flow flow = DbIssues.Flow.newBuilder().addAllLocation(Arrays.asList(locations)).build();
IssueDto issue = db.issues().insert(rule, project, file, i -> {