import org.sonar.auth.github.security.UserAccessToken;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
private GenericApplicationHttpClient underTest;
- private final AccessToken accessToken = new UserAccessToken(randomAlphabetic(10));
- private final String randomEndPoint = "/" + randomAlphabetic(10);
- private final String randomBody = randomAlphabetic(40);
+ private final AccessToken accessToken = new UserAccessToken(secure().nextAlphabetic(10));
+ private final String randomEndPoint = "/" + secure().nextAlphabetic(10);
+ private final String randomBody = secure().nextAlphabetic(40);
private String appUrl;
@Before
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
@Test
@UseDataProvider("githubServers")
public void createUserAccessToken_from_authorization_code_returns_access_token(String apiUrl, String appUrl) throws IOException {
- String token = randomAlphanumeric(10);
+ String token = secure().nextAlphanumeric(10);
when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
.thenReturn(new OkGetResponse("access_token=" + token + "&status="));
@Test
public void listOrganizations_fail_on_failure() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
when(githubApplicationHttpClient.get(appUrl, accessToken, format("/user/installations?page=%s&per_page=%s", 1, 100)))
.thenThrow(new IOException("OOPS"));
@Test
public void listOrganizations_returns_no_installations() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = """
{
"total_count": 0
@Test
public void listOrganizations_returns_pages_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = """
{
"total_count": 2,
@Test
public void listRepositories_fail_on_failure() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
when(githubApplicationHttpClient.get(appUrl, accessToken, format("/search/repositories?q=%s&page=%s&per_page=%s", "org:test", 1, 100)))
.thenThrow(new IOException("OOPS"));
@Test
public void listRepositories_returns_empty_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = "{\n"
+ " \"total_count\": 0\n"
+ "}";
@Test
public void listRepositories_returns_pages_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = """
{
"total_count": 2,
@Test
public void listRepositories_returns_search_results() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = """
{
"total_count": 2,
@Test
public void getRepository_returns_repository() throws IOException {
String appUrl = "https://github.sonarsource.com";
- AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
+ AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10));
String responseJson = "{\n"
+ " \"id\": 1296269,\n"
+ " \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n"
}
private AppToken mockAppToken() {
- String jwt = randomAlphanumeric(5);
+ String jwt = secure().nextAlphanumeric(5);
when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(new AppToken(jwt));
return new AppToken(jwt);
}
private ExpiringAppInstallationToken mockCreateAccessTokenCallingGithub() throws IOException {
- String token = randomAlphanumeric(5);
+ String token = secure().nextAlphanumeric(5);
Response response = mock(Response.class);
when(response.getContent()).thenReturn(Optional.of(format("""
{
@Test
public void should_serializeIssueKey() {
- String issueKey = RandomStringUtils.randomAlphanumeric(20);
+ String issueKey = RandomStringUtils.secure().nextAlphanumeric(20);
String serialized = SonarQubeIssueKeyFormatter.serialize(issueKey);
@Test
public void should_deserializeIssueKey() {
- String issueKey = RandomStringUtils.randomAlphanumeric(20);
+ String issueKey = RandomStringUtils.secure().nextAlphanumeric(20);
String message = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message");
Optional<String> deserialized = SonarQubeIssueKeyFormatter.deserialize(message);
@Test
public void should_notDeserializeIssueKey_when_messageHasWrongFormat() {
- String issueKey = RandomStringUtils.randomAlphanumeric(20);
+ String issueKey = RandomStringUtils.secure().nextAlphanumeric(20);
String messageWithoutSuffix = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, "a message");
String messageWithoutPrefix = join("", issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message");
String messageWithPrefixSuffixReversed = join("", SONAR_ISSUE_KEY_SUFFIX, issueKey, SONAR_ISSUE_KEY_PREFIX, "a message");
import org.junit.runner.RunWith;
import org.sonar.auth.github.GithubAppConfiguration;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void createAppToken_fails_with_IAE_if_privateKey_content_is_garbage() {
- String garbage = randomAlphanumeric(555);
+ String garbage = secure().nextAlphanumeric(555);
GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(garbage);
assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()))
}
private GithubAppConfiguration createAppConfiguration() {
- return new GithubAppConfiguration(new Random().nextLong(), REAL_PRIVATE_KEY, randomAlphanumeric(5));
+ return new GithubAppConfiguration(new Random().nextLong(), REAL_PRIVATE_KEY, secure().nextAlphanumeric(5));
}
private GithubAppConfiguration createAppConfigurationForPrivateKey(String privateKey) {
long applicationId = new Random().nextInt(654);
- return new GithubAppConfiguration(applicationId, privateKey, randomAlphabetic(8));
+ return new GithubAppConfiguration(applicationId, privateKey, secure().nextAlphabetic(8));
}
private static final String REAL_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" +
import org.junit.Test;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@Test
public void execute_request() throws IOException {
- String body = randomAlphanumeric(10);
+ String body = secure().nextAlphanumeric(10);
mockWebServer.enqueue(new MockResponse().setBody(body));
Response response = executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken);
import org.junit.Test;
import org.junit.runner.RunWith;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DataProvider
public static Object[][] incompleteConfigurationParametersSonarQube() {
long applicationId = new Random().nextLong();
- String privateKey = randomAlphabetic(9);
- String apiEndpoint = randomAlphabetic(11);
+ String privateKey = secure().nextAlphabetic(9);
+ String apiEndpoint = secure().nextAlphabetic(11);
return generateNullCombination(new Object[] {
applicationId,
@Test
public void toString_displays_complete_configuration() {
long id = 34;
- String privateKey = randomAlphabetic(3);
- String apiEndpoint = randomAlphabetic(7);
+ String privateKey = secure().nextAlphabetic(3);
+ String apiEndpoint = secure().nextAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(id, privateKey, apiEndpoint);
@Test
public void toString_displays_privateKey_as_stars() {
- GithubAppConfiguration underTest = new GithubAppConfiguration(null, randomAlphabetic(555), null);
+ GithubAppConfiguration underTest = new GithubAppConfiguration(null, secure().nextAlphabetic(555), null);
assertThat(underTest)
.hasToString(
@Test
public void equals_is_not_implemented() {
long applicationId = new Random().nextLong();
- String privateKey = randomAlphabetic(8);
- String apiEndpoint = randomAlphabetic(7);
+ String privateKey = secure().nextAlphabetic(8);
+ String apiEndpoint = secure().nextAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
@Test
public void hashcode_is_based_on_all_fields() {
long applicationId = new Random().nextLong();
- String privateKey = randomAlphabetic(8);
- String apiEndpoint = randomAlphabetic(7);
+ String privateKey = secure().nextAlphabetic(8);
+ String apiEndpoint = secure().nextAlphabetic(7);
GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint);
}
private GithubAppConfiguration newValidConfiguration(long applicationId) {
- return new GithubAppConfiguration(applicationId, randomAlphabetic(6), randomAlphabetic(6));
+ return new GithubAppConfiguration(applicationId, secure().nextAlphabetic(6), secure().nextAlphabetic(6));
}
private static Object[][] generateNullCombination(Object[] objects) {
import static com.google.common.collect.ImmutableList.of;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
@Test
public void submit_returns_task_populated_from_CeTaskSubmit_and_creates_CeQueue_row() {
- String componentUuid = randomAlphabetic(3);
- String mainComponentUuid = randomAlphabetic(4);
+ String componentUuid = secure().nextAlphabetic(3);
+ String mainComponentUuid = secure().nextAlphabetic(4);
CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, new Component(componentUuid, mainComponentUuid), "submitter uuid");
UserDto userDto = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit.getSubmitterUuid());
@Test
public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_a_pending_task_for_another_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
- String otherMainComponentUuid = randomAlphabetic(6);
+ String mainComponentUuid = secure().nextAlphabetic(5);
+ String otherMainComponentUuid = secure().nextAlphabetic(6);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid));
@Test
public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_one_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid));
@Test
public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_many_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid)))
@Test
public void submit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_one_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid));
@Test
public void submit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_many_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid)))
@Test
public void submit_with_UNIQUE_QUEUE_PER_TASK_TYPE_does_not_create_task_when_there_is_a_task_with_the_same_type() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("some type", newComponent(mainComponentUuid), null);
String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid)))
@Test
public void massSubmit_returns_tasks_for_each_CeTaskSubmit_populated_from_CeTaskSubmit_and_creates_CeQueue_row_for_each() {
- String mainComponentUuid = randomAlphabetic(10);
+ String mainComponentUuid = secure().nextAlphabetic(10);
CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, newComponent(mainComponentUuid), "submitter uuid");
CeTaskSubmit taskSubmit2 = createTaskSubmit("some type");
UserDto userDto1 = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit1.getSubmitterUuid());
public void massSubmit_populates_component_name_and_key_of_CeTask_if_project_exists() {
ProjectData projectData = db.components().insertPrivateProject("PROJECT_1");
CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, Component.fromDto(projectData.getMainBranchDto()), null);
- CeTaskSubmit taskSubmit2 = createTaskSubmit("something", newComponent(randomAlphabetic(12)), null);
+ CeTaskSubmit taskSubmit2 = createTaskSubmit("something", newComponent(secure().nextAlphabetic(12)), null);
List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2));
@Test
public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_a_pending_task_for_another_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
- String otherMainComponentUuid = randomAlphabetic(6);
+ String mainComponentUuid = secure().nextAlphabetic(5);
+ String otherMainComponentUuid = secure().nextAlphabetic(6);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid));
@Test
public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_one_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid));
@Test
public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_many_pending_task_for_same_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
String[] uuids = IntStream.range(0, 7)
.mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid)))
@Test
public void massSubmit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_one_pending_task_for_other_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid));
@Test
public void massSubmit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_many_pending_task_for_other_main_component() {
- String mainComponentUuid = randomAlphabetic(5);
+ String mainComponentUuid = secure().nextAlphabetic(5);
CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null);
String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid)))
@Test
public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_tasks_depending_on_whether_there_is_pending_task_for_same_main_component() {
- String mainComponentUuid1 = randomAlphabetic(5);
- String mainComponentUuid2 = randomAlphabetic(6);
- String mainComponentUuid3 = randomAlphabetic(7);
- String mainComponentUuid4 = randomAlphabetic(8);
- String mainComponentUuid5 = randomAlphabetic(9);
+ String mainComponentUuid1 = secure().nextAlphabetic(5);
+ String mainComponentUuid2 = secure().nextAlphabetic(6);
+ String mainComponentUuid3 = secure().nextAlphabetic(7);
+ String mainComponentUuid4 = secure().nextAlphabetic(8);
+ String mainComponentUuid5 = secure().nextAlphabetic(9);
CeTaskSubmit taskSubmit1 = createTaskSubmit("with_one_pending", newComponent(mainComponentUuid1), null);
CeQueueDto dto1 = insertPendingInQueue(newComponent(mainComponentUuid1));
Component componentForMainComponentUuid2 = newComponent(mainComponentUuid2);
@Test
public void cancel_pending() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get();
underTest.cancel(db.getSession(), queueDto);
@Test
public void cancel_pending_whenNodeNameProvided_setItInCeActivity() {
when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME));
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get();
underTest.cancel(db.getSession(), queueDto);
@Test
public void cancel_pending_whenNodeNameNOtProvided_setNulInCeActivity() {
when(nodeInformation.getNodeName()).thenReturn(Optional.empty());
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get();
underTest.cancel(db.getSession(), queueDto);
@Test
public void fail_to_cancel_if_in_progress() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(11)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(11)));
CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID).get();
assertThatThrownBy(() -> underTest.cancel(db.getSession(), ceQueueDto))
@Test
public void cancelAll_pendings_but_not_in_progress() {
- CeTask inProgressTask = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
- CeTask pendingTask1 = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
- CeTask pendingTask2 = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask inProgressTask = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
+ CeTask pendingTask1 = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
+ CeTask pendingTask2 = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
db.getDbClient().ceQueueDao().tryToPeek(session, inProgressTask.getUuid(), WORKER_UUID);
@Test
public void pauseWorkers_marks_workers_as_paused_if_zero_tasks_in_progress() {
- submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
// task is pending
assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED);
@Test
public void pauseWorkers_marks_workers_as_pausing_if_some_tasks_in_progress() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID);
// task is in-progress
@Test
public void resumeWorkers_resumes_pausing_workers() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID);
// task is in-progress
@Test
public void fail_in_progress_task() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get();
underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout");
@Test
public void fail_in_progress_task_whenNodeNameProvided_setsItInCeActivityDto() {
when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME));
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get();
underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout");
@Test
public void fail_throws_exception_if_task_is_pending() {
- CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12)));
+ CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12)));
CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get();
Throwable thrown = catchThrowable(() -> underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout"));
import org.sonar.db.protobuf.DbProjectBranches;
import org.sonar.server.project.Project;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public static Object[][] nullOrNotNullString() {
return new Object[][] {
{null},
- {randomAlphabetic(12)}
+ {secure().nextAlphabetic(12)}
};
}
import org.sonar.core.issue.tracking.Input;
import org.sonar.db.DbClient;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@Test
public void underTest_returns_inputFactory_loading_closed_issues_only_when_getIssues_is_called() {
- String componentUuid = randomAlphanumeric(12);
+ String componentUuid = secure().nextAlphanumeric(12);
ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build();
when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty());
@Test
public void underTest_returns_inputFactory_loading_closed_issues_from_moved_component_when_present() {
- String componentUuid = randomAlphanumeric(12);
- String originalComponentUuid = randomAlphanumeric(12);
+ String componentUuid = secure().nextAlphanumeric(12);
+ String originalComponentUuid = secure().nextAlphanumeric(12);
ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build();
when(movedFilesRepository.getOriginalFile(component))
- .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalComponentUuid, randomAlphanumeric(2))));
+ .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalComponentUuid, secure().nextAlphanumeric(2))));
Input<DefaultIssue> input = underTest.create(component);
@Test
public void underTest_returns_inputFactory_which_caches_loaded_issues() {
- String componentUuid = randomAlphanumeric(12);
+ String componentUuid = secure().nextAlphanumeric(12);
ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build();
when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty());
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
System2 system2 = mock(System2.class);
DbClient dbClient = mock(DbClient.class);
Configuration configuration = newConfiguration("0");
- String componentUuid = randomAlphabetic(15);
+ String componentUuid = secure().nextAlphabetic(15);
ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, configuration, system2, issueChangesToDeleteRepository);
assertThat(underTest.loadClosedIssues(componentUuid)).isEmpty();
i++;
}
IntStream.range(0, random.nextInt(5))
- .forEach(i -> diffs.add(new Diff(randomAlphabetic(10), random.nextBoolean() ? null : randomAlphabetic(11), random.nextBoolean() ? null : randomAlphabetic(12))));
+ .forEach(i -> diffs.add(new Diff(secure().nextAlphabetic(10), random.nextBoolean() ? null : secure().nextAlphabetic(11), random.nextBoolean() ? null : secure().nextAlphabetic(12))));
Collections.shuffle(diffs);
FieldDiffs res = new FieldDiffs();
import org.sonar.server.project.Project;
import static java.util.Optional.ofNullable;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@Test
public void generate_keys_when_using_existing_branch() {
ComponentDto projectDto = dbTester.components().insertPublicProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto componentDto = dbTester.components().insertProjectBranch(projectDto, b -> b.setKey(branchName));
Branch branch = mock(Branch.class);
when(branch.getName()).thenReturn(branchName);
@Test
public void set_projectVersion_when_it_is_set_on_first_analysis() {
- String scannerProjectVersion = randomAlphabetic(12);
+ String scannerProjectVersion = secure().nextAlphabetic(12);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
@Test
@UseDataProvider("oneParameterNullNonNullCombinations")
public void set_projectVersion_when_it_is_set_on_later_analysis(@Nullable String previousAnalysisProjectVersion) {
- String scannerProjectVersion = randomAlphabetic(12);
+ String scannerProjectVersion = secure().nextAlphabetic(12);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING));
ComponentDto project = insertComponent(newPrivateProjectDto("ABCD").setKey(REPORT_PROJECT_KEY));
@Test
@UseDataProvider("oneParameterNullNonNullCombinations")
public void set_buildString(@Nullable String buildString) {
- String projectVersion = randomAlphabetic(7);
+ String projectVersion = secure().nextAlphabetic(7);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(projectVersion, buildString));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
public static Object[][] oneParameterNullNonNullCombinations() {
return new Object[][] {
{null},
- {randomAlphabetic(7)}
+ {secure().nextAlphabetic(7)}
};
}
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.server.project.Project;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
@DataProvider
public static Object[][] stringConsideredAsVersions() {
return new Object[][] {
- {randomAlphabetic(5)},
+ {secure().nextAlphabetic(5)},
{"1,3"},
{"1.3"},
{"0 1"},
public static Object[][] projectVersionNullOrNot() {
return new Object[][] {
{null},
- {randomAlphabetic(15)},
+ {secure().nextAlphabetic(15)},
};
}
import org.sonar.db.component.AnalysisPropertyDto;
import org.sonar.scanner.protocol.output.ScannerReport;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersistAnalysisPropertiesStepIT {
- private static final String SNAPSHOT_UUID = randomAlphanumeric(40);
- private static final String SMALL_VALUE1 = randomAlphanumeric(50);
- private static final String SMALL_VALUE2 = randomAlphanumeric(50);
- private static final String SMALL_VALUE3 = randomAlphanumeric(50);
- private static final String BIG_VALUE = randomAlphanumeric(5000);
+ private static final String SNAPSHOT_UUID = secure().nextAlphanumeric(40);
+ private static final String SMALL_VALUE1 = secure().nextAlphanumeric(50);
+ private static final String SMALL_VALUE2 = secure().nextAlphanumeric(50);
+ private static final String SMALL_VALUE3 = secure().nextAlphanumeric(50);
+ private static final String BIG_VALUE = secure().nextAlphanumeric(5000);
private static final String VALUE_PREFIX_FOR_PR_PROPERTIES = "pr_";
private static final List<ScannerReport.ContextProperty> PROPERTIES = Arrays.asList(
newContextProperty("key1", "value1"),
import org.sonar.db.component.SnapshotQuery;
import org.sonar.db.component.SnapshotTesting;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void persist_analysis() {
- String projectVersion = randomAlphabetic(10);
+ String projectVersion = secure().nextAlphabetic(10);
ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project");
dbTester.components().insertComponent(projectDto);
ComponentDto directoryDto = ComponentTesting.newDirectory(projectDto, "CDEF", "src/main/java/dir").setKey("PROJECT_KEY:src/main/java/dir");
Component file = ReportComponent.builder(Component.Type.FILE, 3).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java").build();
Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir").addChildren(file).build();
- String buildString = Optional.ofNullable(projectVersion).map(v -> randomAlphabetic(7)).orElse(null);
+ String buildString = Optional.ofNullable(projectVersion).map(v -> secure().nextAlphabetic(7)).orElse(null);
Component project = ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid("ABCD")
.setKey(PROJECT_KEY)
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.concat;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentCaptor.forClass;
private static final Component FILE = builder(Type.FILE, 11).build();
private static final Component PROJECT = builder(Type.PROJECT, 1)
- .setProjectVersion(randomAlphanumeric(10))
+ .setProjectVersion(secure().nextAlphanumeric(10))
.addChildren(FILE).build();
@Rule
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DataProvider
public static Object[][] versionAndBuildStringCombinations() {
- String version = randomAlphabetic(7);
- String buildString = randomAlphabetic(12);
+ String version = secure().nextAlphabetic(7);
+ String buildString = secure().nextAlphabetic(12);
return new Object[][] {
{null, null},
{version, null},
.setCleanCodeAttribute(CleanCodeAttribute.CONVENTIONAL)
.addDefaultImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.MAINTAINABILITY).setSeverity(org.sonar.api.issue.impact.Severity.MEDIUM))
.addDefaultImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.RELIABILITY).setSeverity(org.sonar.api.issue.impact.Severity.HIGH))
- .setAdHocName("ad_hoc_rule" + RandomStringUtils.randomAlphabetic(10))
+ .setAdHocName("ad_hoc_rule" + RandomStringUtils.secure().nextAlphabetic(10))
.setAdHocType(RuleType.VULNERABILITY)
.setAdHocSeverity(Severity.CRITICAL)
- .setAdHocDescription("ad hoc description: " + RandomStringUtils.randomAlphanumeric(100));
+ .setAdHocDescription("ad hoc description: " + RandomStringUtils.secure().nextAlphanumeric(100));
return insertRule(ruleName, ruleDto);
}
private RuleDto insertRule(String ruleName, RuleDto partiallyInitRuleDto) {
RuleKey ruleKey = RuleKey.of("plugin1", ruleName);
partiallyInitRuleDto
- .setName("ruleName" + RandomStringUtils.randomAlphanumeric(10))
+ .setName("ruleName" + RandomStringUtils.secure().nextAlphanumeric(10))
.setRuleKey(ruleKey)
- .setPluginKey("pluginKey" + RandomStringUtils.randomAlphanumeric(10))
+ .setPluginKey("pluginKey" + RandomStringUtils.secure().nextAlphanumeric(10))
.setStatus(RuleStatus.READY)
.setScope(RuleDto.Scope.ALL);
@Test
public void date_comes_from_AnalysisMetadataHolder() {
analysisMetadataHolder.setAnalysisDate(8_465_132_498L);
- analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
+ analysisMetadataHolder.setUuid(RandomStringUtils.secure().nextAlphanumeric(40));
underTest.finished(true);
@Test
public void analysisDate_and_analysisUuid_comes_from_AnalysisMetadataHolder_when_set() {
analysisMetadataHolder.setAnalysisDate(8465132498L);
- analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
+ analysisMetadataHolder.setUuid(RandomStringUtils.secure().nextAlphanumeric(40));
underTest.finished(true);
verify(postProjectAnalysisTask).finished(taskContextCaptor.capture());
PostProjectAnalysisTask.LogStatistics logStatistics = taskContextCaptor.getValue().getLogStatistics();
- String key = RandomStringUtils.randomAlphabetic(10);
+ String key = RandomStringUtils.secure().nextAlphabetic(10);
logStatistics.add(key, new Object());
assertThat(catchThrowable(() -> logStatistics.add(key, "bar")))
.isInstanceOf(IllegalArgumentException.class)
import org.sonar.ce.task.projectanalysis.component.Component.Status;
import static com.google.common.base.Strings.repeat;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
.setUuid("uuid_" + dbKey)
.setReportAttributes(ReportAttributes.newBuilder(dbKey.hashCode()).build());
if (type == PROJECT) {
- String buildString = randomAlphabetic(15);
+ String buildString = secure().nextAlphabetic(15);
builder.setProjectAttributes(new ProjectAttributes("version_1", buildString, "453def"));
}
return builder;
import org.sonar.server.project.Project;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
private static final String NO_SCM_BASE_PATH = "";
// both no project as "" or null should be supported
private static final ProjectAttributes SOME_PROJECT_ATTRIBUTES = new ProjectAttributes(
- randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12), "1def5123");
+ secure().nextAlphabetic(20), new Random().nextBoolean() ? null : secure().nextAlphabetic(12), "1def5123");
@RegisterExtension
private final ScannerComponentProvider scannerComponentProvider = new ScannerComponentProvider();
void by_default_project_fields_are_loaded_from_report() {
String nameInReport = "the name";
String descriptionInReport = "the desc";
- String buildString = randomAlphabetic(21);
+ String buildString = secure().nextAlphabetic(21);
Component root = call(newBuilder()
.setType(PROJECT)
.setKey(projectInDb.getKey())
@Test
void project_name_is_loaded_from_report_if_present_and_on_main_branch() {
- String reportName = randomAlphabetic(5);
+ String reportName = secure().nextAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setName(reportName)
@Test
void project_name_is_loaded_from_db_if_not_on_main_branch() {
- String reportName = randomAlphabetic(5);
+ String reportName = secure().nextAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setName(reportName)
@Test
void project_description_is_loaded_from_report_if_present_and_on_main_branch() {
- String reportDescription = randomAlphabetic(5);
+ String reportDescription = secure().nextAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setDescription(reportDescription)
@Test
void project_description_is_loaded_from_db_if_not_on_main_branch() {
- String reportDescription = randomAlphabetic(5);
+ String reportDescription = secure().nextAlphabetic(5);
ScannerReport.Component reportProject = newBuilder()
.setType(PROJECT)
.setDescription(reportDescription)
@Test
void any_component_with_projectRelativePath_has_this_value_appended_to_scmBasePath_and_a_slash_as_scmPath_if_scmBasePath_is_not_empty() {
ScannerReport.Component project = createProject();
- String scmBasePath = randomAlphabetic(10);
+ String scmBasePath = secure().nextAlphabetic(10);
Component root = call(project, scmBasePath, SOME_PROJECT_ATTRIBUTES);
assertThat(root.getReportAttributes().getScmPath())
import static com.google.common.base.Strings.padStart;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
for (int i = 0; i < 110; i++) {
duplicatedBlocks.add(
blockBuilder
- .setResourceId(randomAlphanumeric(16))
+ .setResourceId(secure().nextAlphanumeric(16))
.build());
}
import org.sonar.ce.task.projectanalysis.filemove.ScoreMatrix.ScoreFile;
import org.sonar.server.platform.ServerFileSystem;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void dumpAsCsv_has_no_effect_if_configuration_is_empty() throws IOException {
- String taskUuid = randomAlphabetic(6);
+ String taskUuid = secure().nextAlphabetic(6);
when(ceTask.getUuid()).thenReturn(taskUuid);
underTest.dumpAsCsv(A_SCORE_MATRIX);
@Test
@UseDataProvider("notTruePropertyValues")
public void dumpAsCsv_has_no_effect_if_property_is_not_true(String value) throws IOException {
- String taskUuid = randomAlphabetic(6);
+ String taskUuid = secure().nextAlphabetic(6);
when(ceTask.getUuid()).thenReturn(taskUuid);
settings.setProperty("sonar.filemove.dumpCsv", value);
@DataProvider
public static Object[][] notTruePropertyValues() {
return new Object[][] {
- {randomAlphabetic(6)},
+ {secure().nextAlphabetic(6)},
{"false"},
};
}
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
when(treeRootHolder.getComponentByUuid(componentId)).thenReturn(component);
return DbIssues.Location.newBuilder()
.setComponentId(componentId)
- .setChecksum("hash" + randomAlphanumeric(10))
+ .setChecksum("hash" + secure().nextAlphanumeric(10))
.setTextRange(textRange)
- .setMsg("msg" + randomAlphanumeric(15))
+ .setMsg("msg" + secure().nextAlphanumeric(15))
.build();
}
import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition;
import static java.util.Collections.emptyMap;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
.setStatus(STATUS_OPEN);
Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid();
ReportComponent project = ReportComponent.builder(PROJECT, 1).build();
- String branchName = randomAlphabetic(12);
+ String branchName = secure().nextAlphabetic(12);
ruleRepository.add(ruleKey);
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(new Random().nextLong());
.setStatus(STATUS_OPEN);
Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid();
ReportComponent project = ReportComponent.builder(PROJECT, 1).build();
- String branchName = randomAlphabetic(12);
+ String branchName = secure().nextAlphabetic(12);
ruleRepository.add(ruleKey);
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(new Random().nextLong());
@Test
public void newIssuesChangesNotification_fails_with_ISE_if_issue_has_assignee_not_in_assigneesByUuid() {
RuleKey ruleKey = RuleKey.of("foo", "bar");
- String assigneeUuid = randomAlphabetic(40);
+ String assigneeUuid = secure().nextAlphabetic(40);
DefaultIssue issue = new DefaultIssue()
.setRuleKey(ruleKey)
.setKey("issueKey")
ruleRepository.add(ruleKey);
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(new Random().nextLong());
- analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12)));
+ analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12)));
assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid))
.isInstanceOf(IllegalStateException.class)
@Test
public void newIssuesChangesNotification_creates_assignee_from_UserDto() {
RuleKey ruleKey = RuleKey.of("foo", "bar");
- String assigneeUuid = randomAlphabetic(40);
+ String assigneeUuid = secure().nextAlphabetic(40);
DefaultIssue issue = new DefaultIssue()
.setRuleKey(ruleKey)
.setKey("issueKey")
ruleRepository.add(ruleKey);
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(new Random().nextLong());
- analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12)));
+ analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12)));
IssuesChangesNotification expected = mock(IssuesChangesNotification.class);
when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected);
ruleRepository.add(ruleKey);
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(analysisDate);
- analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12)));
+ analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12)));
IssuesChangesNotification expected = mock(IssuesChangesNotification.class);
when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected);
.forEach(ruleKey -> ruleRepository.add(ruleKey));
treeRootHolder.setRoot(project);
analysisMetadata.setAnalysisDate(analysisDate);
- analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12)));
+ analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12)));
IssuesChangesNotification expected = mock(IssuesChangesNotification.class);
when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected);
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_ReportFailure_notifications() {
- String projectKey = randomAlphabetic(12);
+ String projectKey = secure().nextAlphabetic(12);
ReportAnalysisFailureNotification notification = newNotification(projectKey);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS))
@Test
public void deliver_ignores_notification_without_projectKey() {
- String projectKey = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(10);
Set<ReportAnalysisFailureNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(toSet());
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_ReportFailure_notifications() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<ReportAnalysisFailureNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<ReportAnalysisFailureNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
@Test
public void deliver_send_notifications_to_all_subscribers_of_all_projects() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<ReportAnalysisFailureNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<ReportAnalysisFailureNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
import org.sonar.db.rule.RuleDto;
import org.sonar.server.issue.TaintChecker;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.tuple;
public void raiseEventOnIssue_whenNewTaintVulnerability_shouldCreateRaisedEvent() {
DefaultIssue defaultIssue = createDefaultIssue()
.setNew(true)
- .setRuleDescriptionContextKey(randomAlphabetic(6));
+ .setRuleDescriptionContextKey(secure().nextAlphabetic(6));
when(taintChecker.isTaintVulnerability(any())).thenReturn(true);
DefaultIssue defaultIssue = createDefaultIssue()
.setNew(true)
.addImpact(SoftwareQuality.MAINTAINABILITY, Severity.HIGH)
- .setRuleDescriptionContextKey(randomAlphabetic(6));
+ .setRuleDescriptionContextKey(secure().nextAlphabetic(6));
when(taintChecker.isTaintVulnerability(any())).thenReturn(true);
.setType(RuleType.SECURITY_HOTSPOT)
.setStatus(Issue.STATUS_TO_REVIEW)
.setNew(true)
- .setRuleDescriptionContextKey(randomAlphabetic(6));
+ .setRuleDescriptionContextKey(secure().nextAlphabetic(6));
assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue))
.isNotEmpty()
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.source.linereader.LineReader;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
private Random random = new Random();
private int line = 1 + new Random().nextInt(200);
private long timeStamp = 9_887L + new Random().nextInt(300);
- private String path = randomAlphabetic(50);
+ private String path = secure().nextAlphabetic(50);
private FileSourceDataWarnings underTest = new FileSourceDataWarnings(taskMessages, system2);
import org.sonar.db.component.ComponentDao;
import static java.util.Collections.emptyList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
Component component = mock(Component.class);
DbClient dbClient = mock(DbClient.class);
ComponentDao componentDao = mock(ComponentDao.class);
- String projectKey = randomAlphabetic(20);
+ String projectKey = secure().nextAlphabetic(20);
doReturn(component).when(treeRootHolder).getRoot();
doReturn(projectKey).when(component).getKey();
import org.sonar.server.qualitygate.notification.QGChangeNotification;
import static java.util.Collections.emptyList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
public class QualityGateEventsStepTest {
- private static final String PROJECT_VERSION = randomAlphabetic(19);
+ private static final String PROJECT_VERSION = secure().nextAlphabetic(19);
private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid("uuid 1")
.setKey("key 1")
import org.sonar.server.webhook.WebhookPayload;
import org.sonar.server.webhook.WebhookPayloadFactory;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@Test
public void call_webhooks_with_analysis_and_qualitygate() {
QualityGate.Condition condition = newConditionBuilder()
- .setMetricKey(randomAlphanumeric(96))
+ .setMetricKey(secure().nextAlphanumeric(96))
.setOperator(QualityGate.Operator.LESS_THAN)
- .setErrorThreshold(randomAlphanumeric(22))
- .build(QualityGate.EvaluationStatus.OK, randomAlphanumeric(33));
+ .setErrorThreshold(secure().nextAlphanumeric(22))
+ .build(QualityGate.EvaluationStatus.OK, secure().nextAlphanumeric(33));
QualityGate qualityGate = newQualityGateBuilder()
- .setId(randomAlphanumeric(23))
- .setName(randomAlphanumeric(66))
+ .setId(secure().nextAlphanumeric(23))
+ .setName(secure().nextAlphanumeric(66))
.setStatus(QualityGate.Status.values()[random.nextInt(QualityGate.Status.values().length)])
.add(condition)
.build();
- callWebHooks(randomAlphanumeric(40), qualityGate);
+ callWebHooks(secure().nextAlphanumeric(40), qualityGate);
}
private void callWebHooks(@Nullable String analysisUUid, @Nullable QualityGate qualityGate) {
Project project = newProjectBuilder()
- .setUuid(randomAlphanumeric(3))
- .setKey(randomAlphanumeric(4))
- .setName(randomAlphanumeric(5))
+ .setUuid(secure().nextAlphanumeric(3))
+ .setKey(secure().nextAlphanumeric(4))
+ .setName(secure().nextAlphanumeric(5))
.build();
CeTask ceTask = newCeTaskBuilder()
.setStatus(CeTask.Status.values()[random.nextInt(CeTask.Status.values().length)])
- .setId(randomAlphanumeric(6))
+ .setId(secure().nextAlphanumeric(6))
.build();
Date date = new Date();
- Map<String, String> properties = ImmutableMap.of(randomAlphanumeric(17), randomAlphanumeric(18));
+ Map<String, String> properties = ImmutableMap.of(secure().nextAlphanumeric(17), secure().nextAlphanumeric(18));
Branch branch = newBranchBuilder()
.setIsMain(random.nextBoolean())
.setType(Branch.Type.values()[random.nextInt(Branch.Type.values().length)])
- .setName(randomAlphanumeric(29))
+ .setName(secure().nextAlphanumeric(29))
.build();
PostProjectAnalysisTaskTester.of(underTest)
import org.sonar.db.DbTester;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
private DbClient dbClient = dbTester.getDbClient();
private UuidFactory uuidFactory = mock(UuidFactory.class);
- private String taskUuid = randomAlphabetic(12);
+ private String taskUuid = secure().nextAlphabetic(12);
private CeTask ceTask = new CeTask.Builder()
.setUuid(taskUuid)
- .setType(randomAlphabetic(5))
+ .setType(secure().nextAlphabetic(5))
.build();
private CeTaskMessagesImpl underTest = new CeTaskMessagesImpl(dbClient, uuidFactory, ceTask);
@Test
public void add_persist_message_to_DB() {
- CeTaskMessages.Message message = new CeTaskMessages.Message(randomAlphabetic(20), 2_999L);
- String uuid = randomAlphanumeric(40);
+ CeTaskMessages.Message message = new CeTaskMessages.Message(secure().nextAlphabetic(20), 2_999L);
+ String uuid = secure().nextAlphanumeric(40);
when(uuidFactory.create()).thenReturn(uuid);
underTest.add(message);
Random random = new Random();
List<CeTaskMessages.Message> messages = Stream.of(
// some (or none) non null Message before null one
- IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i)),
+ IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(secure().nextAlphabetic(3) + "_i", 1_999L + i)),
Stream.of((CeTaskMessages.Message) null),
// some (or none) non null Message after null one
- IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i)))
+ IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(secure().nextAlphabetic(3) + "_i", 1_999L + i)))
.flatMap(t -> t)
.collect(toList());
import org.junit.Test;
import org.sonar.db.ce.CeActivityDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskCanceledExceptionTest {
@Test
public void message_is_based_on_specified_thread_name() {
Thread t = new Thread();
- t.setName(randomAlphabetic(29));
+ t.setName(secure().nextAlphabetic(29));
CeTaskCanceledException underTest = new CeTaskCanceledException(t);
import org.junit.Test;
import org.junit.runner.RunWith;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void equals_is_based_on_all_fields() {
- String uuid = randomAlphabetic(2);
- String key = randomAlphabetic(3);
- String name = randomAlphabetic(4);
- String somethingElse = randomAlphabetic(5);
+ String uuid = secure().nextAlphabetic(2);
+ String key = secure().nextAlphabetic(3);
+ String name = secure().nextAlphabetic(4);
+ String somethingElse = secure().nextAlphabetic(5);
CeTask.Component underTest = new CeTask.Component(uuid, key, name);
assertThat(underTest)
@Test
public void hashcode_is_based_on_all_fields() {
- String uuid = randomAlphabetic(2);
- String key = randomAlphabetic(3);
- String name = randomAlphabetic(4);
- String somethingElse = randomAlphabetic(5);
+ String uuid = secure().nextAlphabetic(2);
+ String key = secure().nextAlphabetic(3);
+ String name = secure().nextAlphabetic(4);
+ String somethingElse = secure().nextAlphabetic(5);
CeTask.Component underTest = new CeTask.Component(uuid, key, name);
assertThat(underTest)
import org.junit.Test;
import org.sonar.db.ce.CeActivityDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.ce.task.CeTaskInterruptedException.isTaskInterruptedException;
@Test
public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass() {
- String message = randomAlphabetic(50);
+ String message = secure().nextAlphabetic(50);
CeActivityDto.Status status = randomStatus();
CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) {
@Test
public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass_in_cause_chain() {
- String message = randomAlphabetic(50);
+ String message = secure().nextAlphabetic(50);
CeActivityDto.Status status = randomStatus();
CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) {
import static org.assertj.core.api.Assertions.assertThat;
public class CeTaskTimeoutExceptionTest {
- private String message = RandomStringUtils.randomAlphabetic(50);
+ private String message = RandomStringUtils.secure().nextAlphabetic(50);
private CeTaskTimeoutException underTest = new CeTaskTimeoutException(message);
@Test
import org.junit.Test;
import org.sonar.ce.task.log.CeTaskMessages.Message;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void equals_is_based_on_text_and_timestamp() {
long timestamp = 10_000_000_000L;
- String text = randomAlphabetic(23);
+ String text = secure().nextAlphabetic(23);
Message underTest = new Message(text, timestamp);
assertThat(underTest)
@Test
public void hashsode_is_based_on_text_and_timestamp() {
long timestamp = 10_000_000_000L;
- String text = randomAlphabetic(23);
+ String text = secure().nextAlphabetic(23);
Message underTest = new Message(text, timestamp);
assertThat(underTest.hashCode())
import org.sonar.server.notification.NotificationService;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
@Test
public void onEnd_has_no_effect_if_CeTask_type_is_not_report() {
- when(ceTaskMock.getType()).thenReturn(randomAlphanumeric(12));
+ when(ceTaskMock.getType()).thenReturn(secure().nextAlphanumeric(12));
fullMockedUnderTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock);
@Test
public void onEnd_fails_with_ISE_if_branch_does_not_exist_in_DB() {
- String componentUuid = randomAlphanumeric(6);
- ProjectDto project = new ProjectDto().setUuid(componentUuid).setKey(randomAlphanumeric(5)).setQualifier(Qualifiers.PROJECT).setCreationMethod(CreationMethod.LOCAL_API);
+ String componentUuid = secure().nextAlphanumeric(6);
+ ProjectDto project = new ProjectDto().setUuid(componentUuid).setKey(secure().nextAlphanumeric(5)).setQualifier(Qualifiers.PROJECT).setCreationMethod(CreationMethod.LOCAL_API);
dbTester.getDbClient().projectDao().insert(dbTester.getSession(), project);
dbTester.getSession().commit();
when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT);
public void onEnd_fails_with_IAE_if_component_is_not_a_branch() {
when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT);
ComponentDto mainBranch = dbTester.components().insertPrivateProject().getMainBranchComponent();
- ComponentDto directory = dbTester.components().insertComponent(newDirectory(mainBranch, randomAlphanumeric(12)));
+ ComponentDto directory = dbTester.components().insertComponent(newDirectory(mainBranch, secure().nextAlphanumeric(12)));
ComponentDto file = dbTester.components().insertComponent(ComponentTesting.newFileDto(mainBranch));
ComponentDto view = dbTester.components().insertComponent(ComponentTesting.newPortfolio());
ComponentDto subView = dbTester.components().insertComponent(ComponentTesting.newSubPortfolio(view));
public void onEnd_fails_with_RowNotFoundException_if_activity_for_task_does_not_exist_in_DB() {
ProjectData projectData = dbTester.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String taskUuid = randomAlphanumeric(6);
+ String taskUuid = secure().nextAlphanumeric(6);
when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT);
when(ceTaskMock.getUuid()).thenReturn(taskUuid);
when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(mainBranch.uuid(), null, null)));
@Test
public void onEnd_creates_notification_with_data_from_activity_and_project_and_deliver_it() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
int createdAt = random.nextInt(999_999);
long executedAt = random.nextInt(999_999);
ProjectData project = initMocksToPassConditions(taskUuid, createdAt, executedAt);
@Test
public void onEnd_shouldCreateNotificationWithDataFromActivity_whenNonMainBranchIsFailing() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
int createdAt = random.nextInt(999_999);
long executedAt = random.nextInt(999_999);
@Test
public void onEnd_creates_notification_with_error_message_from_Throwable_argument_message() {
- initMocksToPassConditions(randomAlphanumeric(12), random.nextInt(999_999), (long) random.nextInt(999_999));
- String message = randomAlphanumeric(66);
+ initMocksToPassConditions(secure().nextAlphanumeric(12), random.nextInt(999_999), (long) random.nextInt(999_999));
+ String message = secure().nextAlphanumeric(66);
when(throwableMock.getMessage()).thenReturn(message);
underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock);
@Test
public void onEnd_creates_notification_with_null_error_message_if_Throwable_is_null() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999));
Notification notificationMock = mockSerializer();
@Test
public void onEnd_ignores_null_CeTaskResult_argument() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999));
Notification notificationMock = mockSerializer();
@Test
public void onEnd_ignores_CeTaskResult_argument() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999));
Notification notificationMock = mockSerializer();
@Test
public void onEnd_uses_system_data_as_failedAt_if_task_has_no_executedAt() {
- String taskUuid = randomAlphanumeric(12);
+ String taskUuid = secure().nextAlphanumeric(12);
initMocksToPassConditions(taskUuid, random.nextInt(999_999), null);
long now = random.nextInt(999_999);
when(system2.now()).thenReturn(now);
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@Test
void call_sets_and_restores_thread_name_with_information_of_worker_when_there_is_no_task_to_process() throws Exception {
- String threadName = randomAlphabetic(3);
+ String threadName = secure().nextAlphabetic(3);
when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> {
assertThat(Thread.currentThread().getName())
.isEqualTo("Worker " + ordinal + " (UUID=" + workerUuid + ") on " + threadName);
@Test
void call_sets_and_restores_thread_name_with_information_of_worker_when_a_task_is_processed() throws Exception {
- String threadName = randomAlphabetic(3);
+ String threadName = secure().nextAlphabetic(3);
when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> {
assertThat(Thread.currentThread().getName())
.isEqualTo("Worker " + ordinal + " (UUID=" + workerUuid + ") on " + threadName);
@Test
void call_sets_and_restores_thread_name_with_information_of_worker_when_an_error_occurs() throws Exception {
- String threadName = randomAlphabetic(3);
+ String threadName = secure().nextAlphabetic(3);
CeTask ceTask = createCeTask(submitter);
when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> {
assertThat(Thread.currentThread().getName())
reset(ceWorkerController);
when(ceWorkerController.isEnabled(underTest)).thenReturn(false);
- String threadName = randomAlphabetic(3);
+ String threadName = secure().nextAlphabetic(3);
Thread newThread = createThreadNameVerifyingThread(threadName);
newThread.start();
void isExecutedBy_returns_false_unless_a_thread_is_currently_executing_a_task() throws InterruptedException {
CountDownLatch inCallLatch = new CountDownLatch(1);
CountDownLatch assertionsDoneLatch = new CountDownLatch(1);
- String taskType = randomAlphabetic(12);
+ String taskType = secure().nextAlphabetic(12);
CeTask ceTask = mock(CeTask.class);
when(ceTask.getType()).thenReturn(taskType);
when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask));
void getCurrentTask_returns_empty_unless_a_thread_is_currently_executing_a_task() throws InterruptedException {
CountDownLatch inCallLatch = new CountDownLatch(1);
CountDownLatch assertionsDoneLatch = new CountDownLatch(1);
- String taskType = randomAlphabetic(12);
+ String taskType = secure().nextAlphabetic(12);
CeTask ceTask = mock(CeTask.class);
when(ceTask.getType()).thenReturn(taskType);
when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask));
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.testfixtures.log.LogTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class CeWorkerCountSettingWarningTest {
@Test
public void start_logs_a_warning_if_property_ceWorkerCount_exists_with_a_value() {
- settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, randomAlphabetic(12));
+ settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, secure().nextAlphabetic(12));
underTest.start();
private static final int WORKER_MAX_COUNT = 666;
private static final int WORKER_COUNT = 56;
private static final Set<CeWorker> WORKERS = IntStream.range(0, 2 + new Random().nextInt(10))
- .mapToObj(i -> RandomStringUtils.randomAlphabetic(15))
+ .mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(15))
.map(uuid -> {
CeWorker res = mock(CeWorker.class);
when(res.getUUID()).thenReturn(uuid);
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskCanceledException;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException {
- String threadName = randomAlphabetic(30);
+ String threadName = secure().nextAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
try {
import org.sonar.ce.task.CeTaskCanceledException;
import org.sonar.ce.task.CeTaskTimeoutException;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@Test
public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_has_not_been_called_on_it() {
- String taskUuid = randomAlphabetic(15);
+ String taskUuid = secure().nextAlphabetic(15);
Thread t = new Thread();
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
@Test
public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_and_on_end_have_not_been_called_on_it() {
- String taskUuid = randomAlphabetic(15);
+ String taskUuid = secure().nextAlphabetic(15);
Thread t = new Thread();
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException {
- String threadName = randomAlphabetic(30);
+ String threadName = secure().nextAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
@Test
public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted_even_if_timed_out() throws InterruptedException {
- String threadName = randomAlphabetic(30);
+ String threadName = secure().nextAlphabetic(30);
ComputingThread t = new ComputingThread(threadName);
mockWorkerOnThread(t, ceWorker);
mockWorkerWithTask(ceTask);
}
private static Thread newThreadWithRandomName() {
- String threadName = randomAlphabetic(30);
+ String threadName = secure().nextAlphabetic(30);
Thread t = new Thread();
t.setName(threadName);
return t;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.user.UserDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
AlmPatDto almPatDto = newAlmPatDto();
almPatDto.setAlmSettingUuid(almSetting.getUuid());
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
almPatDto.setUserUuid(userUuid);
underTest.insert(dbSession, almPatDto, null, null);
.containsExactly(A_UUID, almPatDto.getPersonalAccessToken(),
userUuid, almSetting.getUuid(), NOW, NOW);
- assertThat(underTest.selectByUserAndAlmSetting(dbSession, randomAlphanumeric(40), newGithubAlmSettingDto())).isNotPresent();
+ assertThat(underTest.selectByUserAndAlmSetting(dbSession, secure().nextAlphanumeric(40), newGithubAlmSettingDto())).isNotPresent();
}
@Test
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.audit.AuditDao.EXCEEDED_LENGTH;
@Test
void insert_truncateVeryLongNewValue() {
AuditDto auditDto = AuditTesting.newAuditDto();
- String veryLongString = randomAlphanumeric(5000);
+ String veryLongString = secure().nextAlphanumeric(5000);
auditDto.setNewValue(veryLongString);
testAuditDao.insert(dbSession, auditDto);
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.Pagination.forPage;
class CeActivityDaoIT {
- private static final String ENTITY_1 = randomAlphabetic(12);
- private static final String MAINCOMPONENT_2 = randomAlphabetic(13);
- private static final String COMPONENT_1 = randomAlphabetic(14);
+ private static final String ENTITY_1 = secure().nextAlphabetic(12);
+ private static final String MAINCOMPONENT_2 = secure().nextAlphabetic(13);
+ private static final String COMPONENT_1 = secure().nextAlphabetic(14);
private static final long INITIAL_TIME = 1_450_000_000_000L;
private static final String NODE_NAME = "node1";
@ParameterizedTest
@MethodSource("notCanceledStatus")
void insert_resets_is_last_and_main_is_last_fields_based_on_component_and_main_component(CeActivityDto.Status status) {
- String project1 = randomAlphabetic(5);
- String branch11 = randomAlphabetic(6);
- String project2 = randomAlphabetic(8);
- String branch21 = randomAlphabetic(9);
- String type = randomAlphabetic(10);
+ String project1 = secure().nextAlphabetic(5);
+ String branch11 = secure().nextAlphabetic(6);
+ String project2 = secure().nextAlphabetic(8);
+ String branch21 = secure().nextAlphabetic(9);
+ String type = secure().nextAlphabetic(10);
String task1Project1 = insertAndCommit(newUuid(), type, project1, project1, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true));
@ParameterizedTest
@MethodSource("notCanceledStatus")
void insert_resets_is_last_and_main_is_last_fields_based_on_type(CeActivityDto.Status status) {
- String type1 = randomAlphabetic(10);
- String type2 = randomAlphabetic(11);
- String project = randomAlphabetic(5);
- String branch = randomAlphabetic(6);
+ String type1 = secure().nextAlphabetic(10);
+ String type2 = secure().nextAlphabetic(11);
+ String project = secure().nextAlphabetic(5);
+ String branch = secure().nextAlphabetic(6);
String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
@ParameterizedTest
@MethodSource("notCanceledStatus")
void insert_resets_is_last_and_main_is_last_fields_based_on_component_or_not(CeActivityDto.Status status) {
- String project = randomAlphabetic(5);
- String type1 = randomAlphabetic(11);
- String type2 = randomAlphabetic(11);
+ String project = secure().nextAlphabetic(5);
+ String type1 = secure().nextAlphabetic(11);
+ String type2 = secure().nextAlphabetic(11);
String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true));
@ParameterizedTest
@MethodSource("notCanceledStatus")
void insert_does_not_resets_is_last_and_main_is_last_fields_if_status_is_CANCELED(CeActivityDto.Status status) {
- String project = randomAlphabetic(5);
- String branch = randomAlphabetic(6);
- String type = randomAlphabetic(10);
+ String project = secure().nextAlphabetic(5);
+ String branch = secure().nextAlphabetic(6);
+ String type = secure().nextAlphabetic(10);
String task1Project1 = insertAndCommit(newUuid(), type, project, project, status).getUuid();
assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true));
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
@Test
void insert_with_null_uuid_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
- .setAnalysisUuid(randomAlphanumeric(10))
- .setKey(randomAlphanumeric(10))
- .setValue(randomAlphanumeric(10));
+ .setAnalysisUuid(secure().nextAlphanumeric(10))
+ .setKey(secure().nextAlphanumeric(10))
+ .setValue(secure().nextAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
@Test
void insert_with_null_key_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
- .setAnalysisUuid(randomAlphanumeric(10))
- .setUuid(randomAlphanumeric(10))
- .setValue(randomAlphanumeric(10));
+ .setAnalysisUuid(secure().nextAlphanumeric(10))
+ .setUuid(secure().nextAlphanumeric(10))
+ .setValue(secure().nextAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
@Test
void insert_with_null_analysis_uuid_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
- .setUuid(randomAlphanumeric(10))
- .setKey(randomAlphanumeric(10))
- .setValue(randomAlphanumeric(10));
+ .setUuid(secure().nextAlphanumeric(10))
+ .setKey(secure().nextAlphanumeric(10))
+ .setValue(secure().nextAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
@Test
void insert_with_null_value_throws_NPE() {
AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto()
- .setAnalysisUuid(randomAlphanumeric(10))
- .setUuid(randomAlphanumeric(10))
- .setKey(randomAlphanumeric(10));
+ .setAnalysisUuid(secure().nextAlphanumeric(10))
+ .setUuid(secure().nextAlphanumeric(10))
+ .setKey(secure().nextAlphanumeric(10));
assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto))
.isInstanceOf(NullPointerException.class)
@Test
void insert_a_list() {
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)),
- newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)));
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)),
+ newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)));
underTest.insert(dbSession, propertyDtos);
assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isEqualTo(propertyDtos.size());
@Test
void selectByAnalysisUuid_should_return_correct_values() {
- String analysisUuid = randomAlphanumeric(40);
+ String analysisUuid = secure().nextAlphanumeric(40);
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
newAnalysisPropertyDto(random.nextInt(8000), analysisUuid),
@Test
void selectByKeyAndAnalysisUuids_should_return_correct_values() {
- String analysisUuid = randomAlphanumeric(40);
+ String analysisUuid = secure().nextAlphanumeric(40);
List<AnalysisPropertyDto> propertyDtos = Arrays.asList(
newAnalysisPropertyDto(random.nextInt(10), "key1", analysisUuid),
}
private AnalysisPropertyDto insertAnalysisPropertyDto(int valueLength) {
- AnalysisPropertyDto analysisPropertyDto = newAnalysisPropertyDto(valueLength, randomAlphanumeric(40));
+ AnalysisPropertyDto analysisPropertyDto = newAnalysisPropertyDto(valueLength, secure().nextAlphanumeric(40));
underTest.insert(dbSession, analysisPropertyDto);
return analysisPropertyDto;
}
return new AnalysisPropertyDto()
.setAnalysisUuid(analysisUuid)
.setKey(key)
- .setUuid(randomAlphanumeric(40))
- .setValue(randomAlphanumeric(valueLength))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setValue(secure().nextAlphanumeric(valueLength))
.setCreatedAt(1_000L);
}
private AnalysisPropertyDto newAnalysisPropertyDto(int valueLength, String analysisUuid) {
- return newAnalysisPropertyDto(valueLength, randomAlphanumeric(512), analysisUuid);
+ return newAnalysisPropertyDto(valueLength, secure().nextAlphanumeric(512), analysisUuid);
}
private void compareFirstValueWith(AnalysisPropertyDto analysisPropertyDto) {
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
@MethodSource("oneOrMoreProjects")
void selectViewKeysWithEnabledCopyOfProject_returns_empty_when_there_is_no_view(int projectCount) {
Set<String> projectUuids = IntStream.range(0, projectCount)
- .mapToObj(i -> randomAlphabetic(5))
+ .mapToObj(i -> secure().nextAlphabetic(5))
.collect(toSet());
assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, projectUuids)).isEmpty();
@Test
void selectByKeyCaseInsensitive_shouldFindProject_whenCaseIsDifferent() {
- String projectKey = randomAlphabetic(5).toLowerCase();
+ String projectKey = secure().nextAlphabetic(5).toLowerCase();
db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent();
List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey.toUpperCase());
@Test
void selectByKeyCaseInsensitive_should_not_match_non_main_branch() {
- String projectKey = randomAlphabetic(5).toLowerCase();
+ String projectKey = secure().nextAlphabetic(5).toLowerCase();
ProjectDto project = db.components().insertPrivateProject(c -> c.setKey(projectKey)).getProjectDto();
BranchDto projectBranch = db.components().insertProjectBranch(project);
ComponentDto file = db.components().insertFile(projectBranch);
@Test
void selectByKeyCaseInsensitive_shouldNotFindProject_whenKeyIsDifferent() {
- String projectKey = randomAlphabetic(5).toLowerCase();
+ String projectKey = secure().nextAlphabetic(5).toLowerCase();
db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent();
- List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey + randomAlphabetic(1));
+ List<ComponentDto> result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey + secure().nextAlphabetic(1));
assertThat(result).isEmpty();
}
private static Set<String> shuffleWithNonExistentUuids(String... uuids) {
return Stream.concat(
- IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> randomAlphabetic(9)),
+ IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> secure().nextAlphabetic(9)),
Arrays.stream(uuids))
.collect(toSet());
}
import org.sonar.db.audit.model.ComponentKeyNewValue;
import org.sonar.db.project.ProjectDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
void updateKey_updates_branches_too() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
void updateKey_updates_pull_requests_too() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String pullRequestKey1 = randomAlphanumeric(100);
+ String pullRequestKey1 = secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1));
db.components().insertComponent(newFileDto(pullRequest));
db.components().insertComponent(newFileDto(pullRequest));
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.source.FileSourceDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.resources.Qualifiers.FILE;
import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE;
@Test
void scrollAllFilesForFileMove_has_no_effect_if_project_does_not_exist() {
- String nonExistingProjectUuid = randomAlphabetic(10);
+ String nonExistingProjectUuid = secure().nextAlphabetic(10);
underTest.scrollAllFilesForFileMove(dbSession, nonExistingProjectUuid, resultContext -> Assertions.fail("handler should not be " +
"called"));
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.ce.CeActivityDto.Status.CANCELED;
return new Object[][]{
{null},
{""},
- {randomAlphanumeric(7)},
+ {secure().nextAlphanumeric(7)},
};
}
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
queueDto.setComponentUuid(projectUuid);
- queueDto.setUuid(randomAlphanumeric(40));
+ queueDto.setUuid(secure().nextAlphanumeric(40));
queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE));
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setStatus(status);
import org.sonar.db.DbTester;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
@Test
void selectByEventUuid_on_empty_table() {
- assertThat(underTest.selectByEventUuid(dbSession, randomAlphabetic(10)))
+ assertThat(underTest.selectByEventUuid(dbSession, secure().nextAlphabetic(10)))
.isEmpty();
}
@Test
void selectByEventUuid_maps_columns_correctly() {
- String eventBase = randomAlphabetic(5);
- String rowBase = randomAlphabetic(6);
+ String eventBase = secure().nextAlphabetic(5);
+ String rowBase = secure().nextAlphabetic(6);
String eventUuid = eventBase + "_event_uuid";
String uuid = rowBase + "_uuid";
EventComponentChangeDto dto = new EventComponentChangeDto()
@Test
void selectByAnalysisUuids_maps_columns_correctly() {
- String eventBase = randomAlphabetic(5);
- String rowBase = randomAlphabetic(6);
+ String eventBase = secure().nextAlphabetic(5);
+ String rowBase = secure().nextAlphabetic(6);
String eventUuid = eventBase + "_event_uuid";
String uuid = rowBase + "_uuid";
EventComponentChangeDto dto = new EventComponentChangeDto()
@Test
void selectByEventUuid_branchKey_can_be_null() {
- String eventBase = randomAlphabetic(5);
- String rowBase = randomAlphabetic(6);
+ String eventBase = secure().nextAlphabetic(5);
+ String rowBase = secure().nextAlphabetic(6);
String eventUuid = eventBase + "_event_uuid";
EventComponentChangeDto dto = new EventComponentChangeDto()
.setCategory(REMOVED)
@Test
void selectByEventUuid_returns_all_rows_for_specified_event() {
- String eventBase = randomAlphabetic(5);
- String rowBase = randomAlphabetic(6);
+ String eventBase = secure().nextAlphabetic(5);
+ String rowBase = secure().nextAlphabetic(6);
String eventUuid1 = eventBase + "_event_uuid1";
String eventUuid2 = eventBase + "_event_uuid2";
EventComponentChangeDto[] event1Dtos = IntStream.range(0, 3)
.setComponentName(rowBase + "_component_name")
.setComponentBranchKey(null))
.toArray(EventComponentChangeDto[]::new);
- EventPurgeData doesNotMatter = new EventPurgeData(randomAlphabetic(7), randomAlphabetic(8));
+ EventPurgeData doesNotMatter = new EventPurgeData(secure().nextAlphabetic(7), secure().nextAlphabetic(8));
when(system2.now()).thenReturn(now)
.thenReturn(now + 1)
.thenReturn(now + 2)
@Test
void selectByAnalysisUuids_returns_all_rows_for_specified_event() {
- String eventBase = randomAlphabetic(5);
- String rowBase = randomAlphabetic(6);
+ String eventBase = secure().nextAlphabetic(5);
+ String rowBase = secure().nextAlphabetic(6);
String eventUuid1 = eventBase + "_event_uuid1";
String eventUuid2 = eventBase + "_event_uuid2";
EventComponentChangeDto[] event1Dtos = IntStream.range(0, 3)
.setComponentName(rowBase + "_component_name")
.setComponentBranchKey(null))
.toArray(EventComponentChangeDto[]::new);
- EventPurgeData doesNotMatter = new EventPurgeData(randomAlphabetic(7), randomAlphabetic(8));
+ EventPurgeData doesNotMatter = new EventPurgeData(secure().nextAlphabetic(7), secure().nextAlphabetic(8));
when(system2.now()).thenReturn(now)
.thenReturn(now + 1)
.thenReturn(now + 2)
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
@Test
void scrollClosedByComponentUuid_returns_empty_when_no_issue_for_component() {
- String componentUuid = randomAlphabetic(10);
+ String componentUuid = secure().nextAlphabetic(10);
RecorderResultHandler resultHandler = new RecorderResultHandler();
underTest.scrollClosedByComponentUuid(componentUuid, new Date().getTime(), resultHandler);
.setIsExternal(isExternal)
.setIsAdHoc(isAdHoc)
.setRuleKey(ruleKey)
- .setPluginKey("pluginKey" + RandomStringUtils.randomAlphanumeric(10))
+ .setPluginKey("pluginKey" + RandomStringUtils.secure().nextAlphanumeric(10))
.setStatus(ruleStatus);
if (isAdHoc) {
- rule.setAdHocName("ad_hoc_rule" + RandomStringUtils.randomAlphabetic(10))
+ rule.setAdHocName("ad_hoc_rule" + RandomStringUtils.secure().nextAlphabetic(10))
.setAdHocType(RuleType.VULNERABILITY)
.setAdHocSeverity(Severity.CRITICAL)
- .setAdHocDescription("ad hoc description: " + RandomStringUtils.randomAlphanumeric(100));
+ .setAdHocDescription("ad hoc description: " + RandomStringUtils.secure().nextAlphanumeric(100));
}
};
}
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
@Test
void tryLock_fails_if_it_would_insert_concurrently() {
- String name = randomAlphabetic(5);
+ String name = secure().nextAlphabetic(5);
String propertyKey = propertyKeyOf(name);
long now = new Random().nextInt();
@Test
void tryLock_fails_if_concurrent_caller_succeeded_first() {
int lockDurationSeconds = 60;
- String name = randomAlphabetic(5);
+ String name = secure().nextAlphabetic(5);
String propertyKey = propertyKeyOf(name);
long now = new Random().nextInt(4_889_989);
@Test
void tryLock_throws_IAE_if_lock_name_length_is_too_long() {
- String tooLongName = randomAlphabetic(LOCK_NAME_MAX_LENGTH + 1);
+ String tooLongName = secure().nextAlphabetic(LOCK_NAME_MAX_LENGTH + 1);
assertThatThrownBy(() -> underTest.tryLock(dbSession, tooLongName, 60))
.isInstanceOf(IllegalArgumentException.class)
import static com.google.common.collect.ImmutableSet.of;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
UserDto user1 = db.users().insertUser(u -> u.setLogin("user1"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("user2"));
String projectUuid = db.components().insertPrivateProject().getProjectDto().getUuid();
- String projectKey = randomAlphabetic(4);
- String projectName = randomAlphabetic(4);
+ String projectKey = secure().nextAlphabetic(4);
+ String projectName = secure().nextAlphabetic(4);
// global subscription
@Test
void findEmailRecipientsForNotification_returns_empty_on_empty_properties_table() {
db.users().insertUser();
- String dispatcherKey = randomAlphabetic(5);
- String channelKey = randomAlphabetic(6);
- String projectKey = randomAlphabetic(7);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String channelKey = secure().nextAlphabetic(6);
+ String projectKey = secure().nextAlphabetic(7);
Set<EmailSubscriberDto> subscribers = underTest.findEmailSubscribersForNotification(db.getSession(), dispatcherKey, channelKey,
projectKey);
@Test
void findEmailRecipientsForNotification_with_logins_returns_empty_on_empty_properties_table() {
db.users().insertUser();
- String dispatcherKey = randomAlphabetic(5);
- String channelKey = randomAlphabetic(6);
- String projectKey = randomAlphabetic(7);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String channelKey = secure().nextAlphabetic(6);
+ String projectKey = secure().nextAlphabetic(7);
Set<String> logins = of("user1", "user2");
Set<EmailSubscriberDto> subscribers = underTest.findEmailSubscribersForNotification(db.getSession(), dispatcherKey, channelKey,
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(withEmail("user4"));
ProjectDto project = insertPrivateProject("PROJECT_A");
- String dispatcherKey = randomAlphabetic(5);
- String otherDispatcherKey = randomAlphabetic(6);
- String channelKey = randomAlphabetic(7);
- String otherChannelKey = randomAlphabetic(8);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String otherDispatcherKey = secure().nextAlphabetic(6);
+ String channelKey = secure().nextAlphabetic(7);
+ String otherChannelKey = secure().nextAlphabetic(8);
// user1 subscribed only globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(withEmail("user4"));
ProjectDto project = insertPrivateProject("PROJECT_A");
- String dispatcherKey = randomAlphabetic(5);
- String otherDispatcherKey = randomAlphabetic(6);
- String channelKey = randomAlphabetic(7);
- String otherChannelKey = randomAlphabetic(8);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String otherDispatcherKey = secure().nextAlphabetic(6);
+ String channelKey = secure().nextAlphabetic(7);
+ String otherChannelKey = secure().nextAlphabetic(8);
// user1 subscribed only globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
UserDto user2 = db.users().insertUser(withEmail("user2"));
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(withEmail("user4"));
- String projectKey = randomAlphabetic(3);
- String otherProjectKey = randomAlphabetic(4);
+ String projectKey = secure().nextAlphabetic(3);
+ String otherProjectKey = secure().nextAlphabetic(4);
ProjectDto project = insertPrivateProject(projectKey);
- String dispatcherKey = randomAlphabetic(5);
- String otherDispatcherKey = randomAlphabetic(6);
- String channelKey = randomAlphabetic(7);
- String otherChannelKey = randomAlphabetic(8);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String otherDispatcherKey = secure().nextAlphabetic(6);
+ String channelKey = secure().nextAlphabetic(7);
+ String otherChannelKey = secure().nextAlphabetic(8);
// user1 subscribed only globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
UserDto user2 = db.users().insertUser(withEmail("user2"));
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(withEmail("user4"));
- String projectKey = randomAlphabetic(3);
- String otherProjectKey = randomAlphabetic(4);
+ String projectKey = secure().nextAlphabetic(3);
+ String otherProjectKey = secure().nextAlphabetic(4);
ProjectDto project = insertPrivateProject(projectKey);
- String dispatcherKey = randomAlphabetic(5);
- String otherDispatcherKey = randomAlphabetic(6);
- String channelKey = randomAlphabetic(7);
- String otherChannelKey = randomAlphabetic(8);
+ String dispatcherKey = secure().nextAlphabetic(5);
+ String otherDispatcherKey = secure().nextAlphabetic(6);
+ String channelKey = secure().nextAlphabetic(7);
+ String otherChannelKey = secure().nextAlphabetic(8);
// user1 subscribed only globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
UserDto user2 = db.users().insertUser(noEmail("user2"));
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(noEmail("user4"));
- String projectKey = randomAlphabetic(3);
+ String projectKey = secure().nextAlphabetic(3);
ProjectDto project = insertPrivateProject(projectKey);
- String dispatcherKey = randomAlphabetic(4);
- String channelKey = randomAlphabetic(5);
+ String dispatcherKey = secure().nextAlphabetic(4);
+ String channelKey = secure().nextAlphabetic(5);
// user1 and user2 subscribed on project and globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
UserDto user3 = db.users().insertUser(withEmail("user3"));
UserDto user4 = db.users().insertUser(noEmail("user4"));
Set<String> allLogins = of("user1", "user2", "user3");
- String projectKey = randomAlphabetic(3);
+ String projectKey = secure().nextAlphabetic(3);
ProjectDto project = insertPrivateProject(projectKey);
- String dispatcherKey = randomAlphabetic(4);
- String channelKey = randomAlphabetic(5);
+ String dispatcherKey = secure().nextAlphabetic(4);
+ String channelKey = secure().nextAlphabetic(5);
// user1 and user2 subscribed on project and globally
insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(),
null, null);
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.tuple;
dbTester.getDbClient().duplicationDao().insert(dbTester.getSession(), new DuplicationUnitDto()
.setAnalysisUuid(analysis.getUuid())
.setComponentUuid(project.uuid())
- .setHash(randomAlphabetic(12))
+ .setHash(secure().nextAlphabetic(12))
.setIndexInFile(random.nextInt(10))
.setStartLine(random.nextInt(10))
.setEndLine(random.nextInt(10)));
"EVENT_UUID", newUuid(),
"EVENT_COMPONENT_UUID", componentUuid,
"EVENT_ANALYSIS_UUID", analysisUuid,
- "CHANGE_CATEGORY", randomAlphabetic(12),
+ "CHANGE_CATEGORY", secure().nextAlphabetic(12),
"COMPONENT_UUID", newUuid(),
- "COMPONENT_KEY", randomAlphabetic(9),
- "COMPONENT_NAME", randomAlphabetic(10),
+ "COMPONENT_KEY", secure().nextAlphabetic(9),
+ "COMPONENT_NAME", secure().nextAlphabetic(10),
"CREATED_AT", 1L);
}
"ANALYSIS_PROPERTIES",
"UUID", newUuid(),
"ANALYSIS_UUID", analysis1.getUuid(),
- "KEE", randomAlphabetic(10),
- "TEXT_VALUE", isEmpty ? null : randomAlphabetic(50),
+ "KEE", secure().nextAlphabetic(10),
+ "TEXT_VALUE", isEmpty ? null : secure().nextAlphabetic(50),
"IS_EMPTY", isEmpty,
"CREATED_AT", 1L);
}
dbTester.executeInsert(
"PROPERTIES",
"UUID", newUuid(),
- "PROP_KEY", randomAlphabetic(10),
+ "PROP_KEY", secure().nextAlphabetic(10),
"ENTITY_UUID", component.uuid(),
- "TEXT_VALUE", randomAlphabetic(10),
+ "TEXT_VALUE", secure().nextAlphabetic(10),
"IS_EMPTY", isEmpty,
"CREATED_AT", 1L);
}
import static java.time.ZoneOffset.UTC;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
private void insertPropertyFor(ComponentDto... components) {
Stream.of(components).forEach(componentDto -> db.properties().insertProperty(new PropertyDto()
- .setKey(randomAlphabetic(3))
- .setValue(randomAlphabetic(3))
+ .setKey(secure().nextAlphabetic(3))
+ .setValue(secure().nextAlphabetic(3))
.setEntityUuid(componentDto.uuid()),
componentDto.getKey(), componentDto.name(), componentDto.qualifier(), null));
}
private void insertPropertyFor(ProjectDto project) {
db.properties().insertProperty(new PropertyDto()
- .setKey(randomAlphabetic(3))
- .setValue(randomAlphabetic(3))
+ .setKey(secure().nextAlphabetic(3))
+ .setValue(secure().nextAlphabetic(3))
.setEntityUuid(project.getUuid()),
null, project.getKey(), null, null);
}
private void insertProjectMeasureFor(ComponentDto... components) {
Arrays.stream(components).forEach(componentDto -> db.getDbClient().projectMeasureDao().insert(dbSession, new ProjectMeasureDto()
- .setMetricUuid(randomAlphabetic(3))
+ .setMetricUuid(secure().nextAlphabetic(3))
.setComponentUuid(componentDto.uuid())
- .setAnalysisUuid(randomAlphabetic(3))));
+ .setAnalysisUuid(secure().nextAlphabetic(3))));
dbSession.commit();
}
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
}
private QualityGateConditionDto insertQGCondition(String qualityGateUuid) {
- return insertQGCondition(qualityGateUuid, randomAlphabetic(2));
+ return insertQGCondition(qualityGateUuid, secure().nextAlphabetic(2));
}
private QualityGateConditionDto insertQGCondition(String qualityGateUuid, String metricUuid) {
- return insertQGCondition(qualityGateUuid, metricUuid, randomAlphabetic(2), randomAlphabetic(3));
+ return insertQGCondition(qualityGateUuid, metricUuid, secure().nextAlphabetic(2), secure().nextAlphabetic(3));
}
private QualityGateConditionDto insertQGCondition(String qualityGateUuid, String metricUuid, String operator, String threshold) {
import org.sonar.db.user.GroupTesting;
import org.sonar.db.user.SearchGroupMembershipDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.eq;
@Test
void existsReturnsFalseWhenQGEditGroupsDoesNotExist() {
- assertThat(underTest.exists(dbSession, randomAlphabetic(5), randomAlphabetic(5))).isFalse();
+ assertThat(underTest.exists(dbSession, secure().nextAlphabetic(5), secure().nextAlphabetic(5))).isFalse();
}
@Test
private QualityGateDto insertQualityGate() {
QualityGateDto qg = new QualityGateDto()
- .setUuid(randomAlphabetic(5))
- .setName(randomAlphabetic(5));
+ .setUuid(secure().nextAlphabetic(5))
+ .setName(secure().nextAlphabetic(5));
dbTester.getDbClient().qualityGateDao().insert(dbTester.getSession(), qg);
dbTester.commit();
return qg;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
private RulesProfileDto insertRulesProfile() {
RulesProfileDto dto = new RulesProfileDto()
- .setName(randomAlphanumeric(10))
- .setLanguage(randomAlphanumeric(3))
+ .setName(secure().nextAlphanumeric(10))
+ .setLanguage(secure().nextAlphanumeric(3))
.setUuid(Uuids.createFast())
.setIsBuiltIn(false);
db.getDbClient().qualityProfileDao().insert(dbSession, dto);
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
RuleDto rule = db.rules().insert();
RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next();
RuleDescriptionSectionDto newSection = RuleDescriptionSectionDto.builder()
- .uuid(randomAlphanumeric(20))
+ .uuid(secure().nextAlphanumeric(20))
.key("new_key")
- .content(randomAlphanumeric(1000))
+ .content(secure().nextAlphanumeric(1000))
.build();
rule.addRuleDescriptionSectionDto(newSection);
Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos();
RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next();
RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder()
- .uuid(randomAlphanumeric(20))
+ .uuid(secure().nextAlphanumeric(20))
.key(existingSection.getKey())
- .content(randomAlphanumeric(1000))
+ .content(secure().nextAlphanumeric(1000))
.build();
rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection));
RuleDto rule = db.rules().insert();
Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos();
RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next();
- RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(randomAlphanumeric(10), randomAlphanumeric(10));
+ RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(secure().nextAlphanumeric(10), secure().nextAlphanumeric(10));
RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder()
- .uuid(randomAlphanumeric(20))
+ .uuid(secure().nextAlphanumeric(20))
.key(existingSection.getKey())
- .content(randomAlphanumeric(1000))
+ .content(secure().nextAlphanumeric(1000))
.context(contextDto)
.build();
@Test
void insertDeprecatedRuleKey_with_same_RuleKey_should_fail() {
- String repositoryKey = randomAlphanumeric(50);
- String ruleKey = randomAlphanumeric(50);
+ String repositoryKey = secure().nextAlphanumeric(50);
+ String ruleKey = secure().nextAlphanumeric(50);
RuleDbTester ruleTester = db.rules();
ruleTester.insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey)
.setOldRuleKey(ruleKey));
private static RuleDescriptionSectionDto createDefaultRuleDescriptionSection() {
return RuleDescriptionSectionDto.createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(),
- RandomStringUtils.randomAlphanumeric(1000));
+ RandomStringUtils.secure().nextAlphanumeric(1000));
}
private static class Accumulator<T> implements Consumer<T> {
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
@Test
void deleteFromUserUuid_shouldNotFail_whenNoUser() {
- assertThatCode(() -> scimUserDao.deleteByUserUuid(dbSession, randomAlphanumeric(6))).doesNotThrowAnyException();
+ assertThatCode(() -> scimUserDao.deleteByUserUuid(dbSession, secure().nextAlphanumeric(6))).doesNotThrowAnyException();
}
private List<ScimUserTestData> insertScimUsersWithUsers(List<String> userLogins) {
}
private ScimUserTestData insertScimUser(String scimUserUuid) {
- return insertScimUser(scimUserUuid, randomAlphanumeric(40));
+ return insertScimUser(scimUserUuid, secure().nextAlphanumeric(40));
}
private ScimUserTestData insertScimUser(String scimUserUuid, String userUuid) {
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.groups.Tuple.tuple;
}
private UserGroupDto insertUserGroup(UserDto user) {
- GroupDto group = newGroupDto().setName(randomAlphanumeric(30));
+ GroupDto group = newGroupDto().setName(secure().nextAlphanumeric(30));
dbClient.groupDao().insert(session, group);
UserGroupDto dto = new UserGroupDto().setUserUuid(user.getUuid()).setGroupUuid(group.getUuid());
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.UserNewValue;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
}
private UserGroupDto insertUserGroup(UserDto user) {
- GroupDto group = newGroupDto().setName(randomAlphanumeric(30));
+ GroupDto group = newGroupDto().setName(secure().nextAlphanumeric(30));
dbClient.groupDao().insert(db.getSession(), group);
UserGroupDto dto = new UserGroupDto().setUserUuid(user.getUuid()).setGroupUuid(group.getUuid());
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Sets.newHashSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class IssueTesting {
//TODO map to correct impact. Will be fixed with persistence of impacts on issues
.addImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.MAINTAINABILITY).setSeverity(org.sonar.api.issue.impact.Severity.HIGH))
.setEffort((long) RANDOM.nextInt(10))
- .setAssigneeUuid("assignee-uuid_" + randomAlphabetic(26))
- .setAuthorLogin("author_" + randomAlphabetic(5))
+ .setAssigneeUuid("assignee-uuid_" + secure().nextAlphabetic(26))
+ .setAuthorLogin("author_" + secure().nextAlphabetic(5))
// Starting from 1 in order to never get 0 (as it's a forbidden value)
.setLine(RANDOM.nextInt(1, 1_001))
- .setMessage("message_" + randomAlphabetic(5))
- .setChecksum("checksum_" + randomAlphabetic(5))
- .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5)))
- .setRuleDescriptionContextKey("context_" + randomAlphabetic(5))
+ .setMessage("message_" + secure().nextAlphabetic(5))
+ .setChecksum("checksum_" + secure().nextAlphabetic(5))
+ .setTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5)))
+ .setRuleDescriptionContextKey("context_" + secure().nextAlphabetic(5))
.setIssueCreationDate(new Date(System.currentTimeMillis() - 2_000))
.setIssueUpdateDate(new Date(System.currentTimeMillis() - 1_500))
.setCreatedAt(System.currentTimeMillis() - 1_000)
.setUuid(UuidFactoryFast.getInstance().create())
.setKey(UuidFactoryFast.getInstance().create())
.setIssueKey(issue.getKey())
- .setChangeData("data_" + randomAlphanumeric(40))
+ .setChangeData("data_" + secure().nextAlphanumeric(40))
.setChangeType(IssueChangeDto.TYPE_FIELD_CHANGE)
- .setUserUuid("userUuid_" + randomAlphanumeric(40))
+ .setUserUuid("userUuid_" + secure().nextAlphanumeric(40))
.setProjectUuid(issue.getProjectUuid())
.setIssueChangeCreationDate(RANDOM.nextLong(Long.MAX_VALUE))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE))
import org.sonar.api.testfixtures.log.LogTesterJUnit5;
import static java.lang.Math.abs;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
dbSession.selectOne(str);
verify(myBatisDbSession).selectOne(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object object = new Object();
dbSession.selectOne(str, object);
verify(myBatisDbSession).selectOne(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
dbSession.selectList(str);
verify(myBatisDbSession).selectList(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object object = new Object();
dbSession.selectList(str, object);
verify(myBatisDbSession).selectList(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object parameter = new Object();
RowBounds rowBounds = new RowBounds();
dbSession.selectList(str, parameter, rowBounds);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
- String mapKey = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
+ String mapKey = secure().nextAlphabetic(10);
dbSession.selectMap(str, mapKey);
verify(myBatisDbSession).selectMap(str, mapKey);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object parameter = new Object();
- String mapKey = randomAlphabetic(10);
+ String mapKey = secure().nextAlphabetic(10);
dbSession.selectMap(str, parameter, mapKey);
verify(myBatisDbSession).selectMap(str, parameter, mapKey);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object parameter = new Object();
- String mapKey = randomAlphabetic(10);
+ String mapKey = secure().nextAlphabetic(10);
RowBounds rowBounds = new RowBounds();
dbSession.selectMap(str, parameter, mapKey, rowBounds);
verify(myBatisDbSession).selectMap(str, parameter, mapKey, rowBounds);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
ResultHandler handler = mock(ResultHandler.class);
dbSession.select(str, handler);
verify(myBatisDbSession).select(str, handler);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object parameter = new Object();
ResultHandler handler = mock(ResultHandler.class);
dbSession.select(str, parameter, handler);
verify(myBatisDbSession).select(str, parameter, handler);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object parameter = new Object();
ResultHandler handler = mock(ResultHandler.class);
RowBounds rowBounds = new RowBounds();
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
dbSession.insert(str);
verify(myBatisDbSession).insert(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object object = new Object();
dbSession.insert(str, object);
verify(myBatisDbSession).insert(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
dbSession.update(str);
verify(myBatisDbSession).update(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object object = new Object();
dbSession.update(str, object);
verify(myBatisDbSession).update(str, object);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
dbSession.delete(str);
verify(myBatisDbSession).delete(str);
});
verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> {
- String str = randomAlphabetic(10);
+ String str = secure().nextAlphabetic(10);
Object object = new Object();
dbSession.delete(str, object);
verify(myBatisDbSession).delete(str, object);
}
private static DbSessionCaller[] DIRTYING_CALLS = {
- session -> session.insert(randomAlphabetic(3)),
- session -> session.insert(randomAlphabetic(2), new Object()),
- session -> session.update(randomAlphabetic(3)),
- session -> session.update(randomAlphabetic(3), new Object()),
- session -> session.delete(randomAlphabetic(3)),
- session -> session.delete(randomAlphabetic(3), new Object()),
+ session -> session.insert(secure().nextAlphabetic(3)),
+ session -> session.insert(secure().nextAlphabetic(2), new Object()),
+ session -> session.update(secure().nextAlphabetic(3)),
+ session -> session.update(secure().nextAlphabetic(3), new Object()),
+ session -> session.delete(secure().nextAlphabetic(3)),
+ session -> session.delete(secure().nextAlphabetic(3), new Object()),
};
private static DbSessionCaller[] COMMIT_CALLS = {
};
private static DbSessionCaller[] NEUTRAL_CALLS = {
- session -> session.selectOne(randomAlphabetic(3)),
- session -> session.selectOne(randomAlphabetic(3), new Object()),
- session -> session.select(randomAlphabetic(3), mock(ResultHandler.class)),
- session -> session.select(randomAlphabetic(3), new Object(), mock(ResultHandler.class)),
- session -> session.select(randomAlphabetic(3), new Object(), new RowBounds(), mock(ResultHandler.class)),
- session -> session.selectList(randomAlphabetic(3)),
- session -> session.selectList(randomAlphabetic(3), new Object()),
- session -> session.selectList(randomAlphabetic(3), new Object(), new RowBounds()),
- session -> session.selectMap(randomAlphabetic(3), randomAlphabetic(3)),
- session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3)),
- session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3), new RowBounds()),
+ session -> session.selectOne(secure().nextAlphabetic(3)),
+ session -> session.selectOne(secure().nextAlphabetic(3), new Object()),
+ session -> session.select(secure().nextAlphabetic(3), mock(ResultHandler.class)),
+ session -> session.select(secure().nextAlphabetic(3), new Object(), mock(ResultHandler.class)),
+ session -> session.select(secure().nextAlphabetic(3), new Object(), new RowBounds(), mock(ResultHandler.class)),
+ session -> session.selectList(secure().nextAlphabetic(3)),
+ session -> session.selectList(secure().nextAlphabetic(3), new Object()),
+ session -> session.selectList(secure().nextAlphabetic(3), new Object(), new RowBounds()),
+ session -> session.selectMap(secure().nextAlphabetic(3), secure().nextAlphabetic(3)),
+ session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3)),
+ session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3), new RowBounds()),
session -> session.getMapper(Object.class),
session -> session.getConfiguration(),
session -> session.getConnection(),
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
Random random = new Random();
boolean randomBoolean = random.nextBoolean();
int randomInt = random.nextInt(200);
- String randomStatement = randomAlphabetic(10);
+ String randomStatement = secure().nextAlphabetic(10);
Object randomParameter = new Object();
Cursor<Object> mockCursor = mock(Cursor.class);
RowBounds rowBounds = new RowBounds();
Object randomObject = new Object();
List<Object> randomList = new ArrayList<>();
Map<Object, Object> randomMap = new HashMap<>();
- String randomMapKey = randomAlphabetic(10);
+ String randomMapKey = secure().nextAlphabetic(10);
ResultHandler randomResultHandler = resultContext -> {
// don't care
};
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class CeActivityDtoTest {
private static final String STR_40_CHARS = "0123456789012345678901234567890123456789";
- private static final String STR_100_CHARS = randomAlphabetic(100);
+ private static final String STR_100_CHARS = secure().nextAlphabetic(100);
private final CeActivityDto underTest = new CeActivityDto();
@Test
void constructor_from_CeQueueDto_populates_fields() {
long now = new Random().nextLong();
CeQueueDto ceQueueDto = new CeQueueDto()
- .setUuid(randomAlphanumeric(10))
- .setTaskType(randomAlphanumeric(11))
- .setComponentUuid(randomAlphanumeric(12))
- .setEntityUuid(randomAlphanumeric(13))
- .setSubmitterUuid(randomAlphanumeric(14))
- .setWorkerUuid(randomAlphanumeric(15))
+ .setUuid(secure().nextAlphanumeric(10))
+ .setTaskType(secure().nextAlphanumeric(11))
+ .setComponentUuid(secure().nextAlphanumeric(12))
+ .setEntityUuid(secure().nextAlphanumeric(13))
+ .setSubmitterUuid(secure().nextAlphanumeric(14))
+ .setWorkerUuid(secure().nextAlphanumeric(15))
.setCreatedAt(now + 9_999)
.setStartedAt(now + 865);
@Test
void setErrorMessage_truncates_to_1000_after_removing_char_zero() {
- String before = randomAlphanumeric(50);
- String after = randomAlphanumeric(950);
- String truncated = randomAlphanumeric(1 + new Random().nextInt(50));
+ String before = secure().nextAlphanumeric(50);
+ String after = secure().nextAlphanumeric(950);
+ String truncated = secure().nextAlphanumeric(1 + new Random().nextInt(50));
underTest.setErrorMessage(before + "\u0000" + after + truncated);
assertThat(underTest.getErrorMessage()).isEqualTo(before + after);
@Test
void newProperties_constructor_fails_with_IAE_if_workerUuid_is_41_or_more() {
- String workerUuid = RandomStringUtils.randomAlphanumeric(41 + new Random().nextInt(5));
+ String workerUuid = RandomStringUtils.secure().nextAlphanumeric(41 + new Random().nextInt(5));
assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 456))
.isInstanceOf(IllegalArgumentException.class)
import org.junit.jupiter.api.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
void test_equality() {
underTest = new AnalysisPropertyDto()
- .setUuid(randomAlphanumeric(40))
- .setAnalysisUuid(randomAlphanumeric(40))
- .setKey(randomAlphanumeric(512))
- .setValue(randomAlphanumeric(10000));
+ .setUuid(secure().nextAlphanumeric(40))
+ .setAnalysisUuid(secure().nextAlphanumeric(40))
+ .setKey(secure().nextAlphanumeric(512))
+ .setValue(secure().nextAlphanumeric(10000));
assertThat(underTest)
.isEqualTo(
@Test
void test_hashcode() {
underTest = new AnalysisPropertyDto()
- .setUuid(randomAlphanumeric(40))
- .setAnalysisUuid(randomAlphanumeric(40))
- .setKey(randomAlphanumeric(512))
- .setValue(randomAlphanumeric(10000));
+ .setUuid(secure().nextAlphanumeric(40))
+ .setAnalysisUuid(secure().nextAlphanumeric(40))
+ .setKey(secure().nextAlphanumeric(512))
+ .setValue(secure().nextAlphanumeric(10000));
assertThat(underTest.hashCode()).isEqualTo(
new AnalysisPropertyDto()
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
class ScrapAnalysisPropertyDtoTest {
@ValueSource(ints = {1, 2000, 4000})
void test_text_set(int value) {
ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto();
- String text = randomAlphanumeric(value);
+ String text = secure().nextAlphanumeric(value);
underTest.setTextValue(text);
assertThat(underTest.getValue()).isEqualTo(text);
@ValueSource(ints = {1, 2000, 4000})
void test_clob_set(int value) {
ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto();
- String text = randomAlphanumeric(4000 + value);
+ String text = secure().nextAlphanumeric(4000 + value);
underTest.setClobValue(text);
assertThat(underTest.getValue()).isEqualTo(text);
import org.sonar.core.util.Uuids;
import org.sonar.db.issue.ImpactDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.apache.commons.lang3.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
void addRuleDescriptionSectionDto_whenSameSectionAndContext_shouldThrowError() {
RuleDto dto = new RuleDto();
- String contextKey = randomAlphanumeric(50);
- String displayName = randomAlphanumeric(50);
+ String contextKey = secure().nextAlphanumeric(50);
+ String displayName = secure().nextAlphanumeric(50);
RuleDescriptionSectionDto section1 = createSection(SECTION_KEY, contextKey, displayName);
dto.addRuleDescriptionSectionDto(section1);
RuleDescriptionSectionDto section2 = createSection(SECTION_KEY, contextKey, displayName);
import org.sonar.db.Pagination;
import org.sonar.db.user.GroupDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Fail.fail;
@Test
void deleteFromGroupUuid_shouldNotFail_whenNoGroup() {
- assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), randomAlphanumeric(6))).doesNotThrowAnyException();
+ assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), secure().nextAlphanumeric(6))).doesNotThrowAnyException();
}
import java.time.ZonedDateTime;
import org.junit.jupiter.api.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
void fail_if_token_hash_is_longer_than_255_characters() {
- assertThatThrownBy(() -> new UserTokenDto().setTokenHash(randomAlphabetic(256)))
+ assertThatThrownBy(() -> new UserTokenDto().setTokenHash(secure().nextAlphabetic(256)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Token hash length (256) is longer than the maximum authorized (255)");
}
import org.sonar.db.alm.pat.AlmPatDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class AlmPatsTesting {
public static AlmPatDto newAlmPatDto() {
AlmPatDto almPatDto = new AlmPatDto();
- almPatDto.setAlmSettingUuid(randomAlphanumeric(40));
- almPatDto.setPersonalAccessToken(randomAlphanumeric(2000));
- almPatDto.setUserUuid(randomAlphanumeric(40));
+ almPatDto.setAlmSettingUuid(secure().nextAlphanumeric(40));
+ almPatDto.setPersonalAccessToken(secure().nextAlphanumeric(2000));
+ almPatDto.setUserUuid(secure().nextAlphanumeric(40));
return almPatDto;
}
import org.sonar.db.alm.setting.ProjectAlmSettingDto;
import org.sonar.db.project.ProjectDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
-import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
+
public class AlmSettingsTesting {
public static AlmSettingDto newGithubAlmSettingDto() {
return new AlmSettingDto()
- .setKey(randomAlphanumeric(200))
- .setUrl(randomAlphanumeric(2000))
- .setAppId(randomNumeric(8))
- .setClientId(randomNumeric(8))
- .setClientSecret(randomAlphanumeric(80))
- .setPrivateKey(randomAlphanumeric(2000))
+ .setKey(secure().nextAlphanumeric(200))
+ .setUrl(secure().nextAlphanumeric(2000))
+ .setAppId(secure().nextNumeric(8))
+ .setClientId(secure().nextNumeric(8))
+ .setClientSecret(secure().nextAlphanumeric(80))
+ .setPrivateKey(secure().nextAlphanumeric(2000))
.setAlm(ALM.GITHUB);
}
public static AlmSettingDto newAzureAlmSettingDto() {
return new AlmSettingDto()
- .setKey(randomAlphanumeric(200))
- .setPersonalAccessToken(randomAlphanumeric(2000))
- .setUrl(randomAlphanumeric(2000))
+ .setKey(secure().nextAlphanumeric(200))
+ .setPersonalAccessToken(secure().nextAlphanumeric(2000))
+ .setUrl(secure().nextAlphanumeric(2000))
.setAlm(ALM.AZURE_DEVOPS);
}
public static AlmSettingDto newGitlabAlmSettingDto() {
return new AlmSettingDto()
- .setKey(randomAlphanumeric(200))
- .setPersonalAccessToken(randomAlphanumeric(2000))
- .setUrl(randomAlphanumeric(2000))
+ .setKey(secure().nextAlphanumeric(200))
+ .setPersonalAccessToken(secure().nextAlphanumeric(2000))
+ .setUrl(secure().nextAlphanumeric(2000))
.setAlm(ALM.GITLAB);
}
public static AlmSettingDto newBitbucketAlmSettingDto() {
return new AlmSettingDto()
- .setKey(randomAlphanumeric(200))
- .setUrl(randomAlphanumeric(2000))
- .setPersonalAccessToken(randomAlphanumeric(2000))
+ .setKey(secure().nextAlphanumeric(200))
+ .setUrl(secure().nextAlphanumeric(2000))
+ .setPersonalAccessToken(secure().nextAlphanumeric(2000))
.setAlm(ALM.BITBUCKET);
}
public static AlmSettingDto newBitbucketCloudAlmSettingDto() {
return new AlmSettingDto()
- .setKey(randomAlphanumeric(200))
- .setClientId(randomAlphanumeric(50))
- .setAppId(randomAlphanumeric(80))
- .setClientSecret(randomAlphanumeric(50))
+ .setKey(secure().nextAlphanumeric(200))
+ .setClientId(secure().nextAlphanumeric(50))
+ .setAppId(secure().nextAlphanumeric(80))
+ .setClientSecret(secure().nextAlphanumeric(50))
.setAlm(ALM.BITBUCKET_CLOUD);
}
return new ProjectAlmSettingDto()
.setAlmSettingUuid(githubAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
- .setAlmRepo(randomAlphanumeric(256))
+ .setAlmRepo(secure().nextAlphanumeric(256))
.setSummaryCommentEnabled(true)
.setMonorepo(monorepo);
}
return new ProjectAlmSettingDto()
.setAlmSettingUuid(azureAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
- .setAlmSlug(randomAlphanumeric(256))
- .setAlmRepo(randomAlphanumeric(256))
+ .setAlmSlug(secure().nextAlphanumeric(256))
+ .setAlmRepo(secure().nextAlphanumeric(256))
.setMonorepo(false);
}
return new ProjectAlmSettingDto()
.setAlmSettingUuid(bitbucketAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
- .setAlmRepo(randomAlphanumeric(256))
- .setAlmSlug(randomAlphanumeric(256))
+ .setAlmRepo(secure().nextAlphanumeric(256))
+ .setAlmSlug(secure().nextAlphanumeric(256))
.setMonorepo(false);
}
return new ProjectAlmSettingDto()
.setAlmSettingUuid(bitbucketCloudAlmSetting.getUuid())
.setProjectUuid(project.getUuid())
- .setAlmRepo(randomAlphanumeric(256))
+ .setAlmRepo(secure().nextAlphanumeric(256))
.setMonorepo(false);
}
}
import org.sonar.db.issue.AnticipatedTransitionDto;
import org.sonar.db.issue.AnticipatedTransitionMapper;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class AnticipatedTransitionDbTester {
public AnticipatedTransitionDto createForIssue(DefaultIssue issue, String userUuid, String filePath) {
var dto = new AnticipatedTransitionDto(
- "uuid_" + randomAlphabetic(5),
+ "uuid_" + secure().nextAlphabetic(5),
issue.projectUuid(),
userUuid,
"wontfix",
import java.security.SecureRandom;
import java.util.Random;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class AuditTesting {
public static AuditDto newAuditDto(long createdAt, String operation) {
AuditDto auditDto = new AuditDto();
- auditDto.setUuid(randomAlphanumeric(40));
- auditDto.setUserUuid(randomAlphanumeric(255));
- auditDto.setUserLogin(randomAlphanumeric(255));
+ auditDto.setUuid(secure().nextAlphanumeric(40));
+ auditDto.setUserUuid(secure().nextAlphanumeric(255));
+ auditDto.setUserLogin(secure().nextAlphanumeric(255));
auditDto.setNewValue("{ \"someKey\": \"someValue\", \"anotherKey\": \"\\\"anotherValue\\\" with quotes \\ \n\t\b\f\r\"}");
auditDto.setOperation(operation);
auditDto.setCategory("category");
import org.sonar.db.DbSession;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS;
import static org.sonar.db.ce.CeQueueDto.Status.PENDING;
public static CeQueueDto newCeQueueDto(String uuid) {
return new CeQueueDto()
.setUuid(uuid)
- .setComponentUuid(randomAlphanumeric(40))
- .setEntityUuid(randomAlphanumeric(39))
+ .setComponentUuid(secure().nextAlphanumeric(40))
+ .setEntityUuid(secure().nextAlphanumeric(39))
.setStatus(CeQueueDto.Status.PENDING)
.setTaskType(CeTaskTypes.REPORT)
- .setSubmitterUuid(randomAlphanumeric(255))
+ .setSubmitterUuid(secure().nextAlphanumeric(255))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE))
.setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE));
}
import org.sonar.db.project.ProjectDto;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent;
public static BranchDto newBranchDto(@Nullable String projectUuid, BranchType branchType) {
- String key = "branch_" + randomAlphanumeric(248);
+ String key = "branch_" + secure().nextAlphanumeric(248);
return new BranchDto()
.setKey(key)
.setUuid(Uuids.createFast())
}
public static BranchDto newBranchDto(ComponentDto branchComponent, BranchType branchType, String projectUuid) {
- String key = "branch_" + randomAlphanumeric(248);
+ String key = "branch_" + secure().nextAlphanumeric(248);
return new BranchDto()
.setKey(key)
import java.util.Random;
import org.sonar.core.util.Uuids;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class ProjectLinkTesting {
}
public static ProjectLinkDto newCustomLinkDto() {
- String nameAndType = randomAlphabetic(20);
+ String nameAndType = secure().nextAlphabetic(20);
return newCommonLinkDto()
.setName(nameAndType)
.setType(nameAndType);
return new ProjectLinkDto()
.setUuid(Uuids.createFast())
.setProjectUuid(Uuids.createFast())
- .setHref(randomAlphanumeric(128))
+ .setHref(secure().nextAlphanumeric(128))
.setCreatedAt(System.currentTimeMillis())
.setUpdatedAt(System.currentTimeMillis());
}
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang3.RandomStringUtils.randomAscii;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class SnapshotTesting {
public static SnapshotDto newAnalysis(String uuid) {
return new SnapshotDto()
- .setUuid(randomAlphanumeric(40))
+ .setUuid(secure().nextAlphanumeric(40))
.setRootComponentUuid(uuid)
.setStatus(SnapshotDto.STATUS_PROCESSED)
.setCreatedAt(System.currentTimeMillis())
.setAnalysisDate(System.currentTimeMillis())
- .setRevision(randomAlphanumeric(50))
+ .setRevision(secure().nextAlphanumeric(50))
.setLast(true);
}
public static SnapshotDto newSnapshot() {
return new SnapshotDto()
- .setUuid(randomAlphanumeric(40))
- .setRootComponentUuid(randomAlphanumeric(40))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setRootComponentUuid(secure().nextAlphanumeric(40))
.setStatus(randomAscii(1))
.setCreatedAt(System.currentTimeMillis())
.setAnalysisDate(System.currentTimeMillis())
import org.sonar.db.component.SnapshotDto;
import static java.util.Objects.requireNonNull;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class EventTesting {
return new EventDto()
.setAnalysisUuid(analysis.getUuid())
.setComponentUuid(analysis.getRootComponentUuid())
- .setUuid(randomAlphanumeric(40))
- .setName(randomAlphanumeric(400))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setName(secure().nextAlphanumeric(400))
.setDescription(null)
.setCategory("Other")
.setCreatedAt(System.currentTimeMillis())
public static MetricDto newMetricDto() {
Metric.ValueType[] metricTypes = Metric.ValueType.values();
return new MetricDto()
- .setUuid(RandomStringUtils.randomAlphanumeric(40))
- .setKey(RandomStringUtils.randomAlphanumeric(64))
- .setShortName(RandomStringUtils.randomAlphanumeric(64))
+ .setUuid(RandomStringUtils.secure().nextAlphanumeric(40))
+ .setKey(RandomStringUtils.secure().nextAlphanumeric(64))
+ .setShortName(RandomStringUtils.secure().nextAlphanumeric(64))
.setValueType(metricTypes[RANDOM.nextInt(metricTypes.length - 1)].name())
- .setDomain(RandomStringUtils.randomAlphanumeric(64))
- .setDescription(RandomStringUtils.randomAlphanumeric(250))
+ .setDomain(RandomStringUtils.secure().nextAlphanumeric(64))
+ .setDescription(RandomStringUtils.secure().nextAlphanumeric(250))
.setBestValue(RANDOM.nextDouble())
.setDeleteHistoricalData(RANDOM.nextBoolean())
.setDirection(RANDOM.nextInt(Integer.MAX_VALUE))
import org.sonar.db.permission.PermissionsTestHelper;
import static java.util.Arrays.stream;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang3.RandomStringUtils.randomAscii;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class PermissionTemplateTesting {
@SafeVarargs
public static PermissionTemplateDto newPermissionTemplateDto(Consumer<PermissionTemplateDto>... populators) {
PermissionTemplateDto dto = new PermissionTemplateDto()
- .setName(randomAlphanumeric(60))
+ .setName(secure().nextAlphanumeric(60))
.setDescription(randomAscii(500))
.setUuid(Uuids.create())
.setCreatedAt(new Date())
import java.util.Random;
import org.sonar.core.util.Uuids;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class PluginTesting {
return new PluginDto()
.setUuid(uuid)
.setKee(uuid)
- .setFileHash(randomAlphanumeric(32))
+ .setFileHash(secure().nextAlphanumeric(32))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE))
.setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE));
}
import java.util.function.Consumer;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
-import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
+
public class QualityGateDbTester {
private static final String DEFAULT_QUALITY_GATE_PROPERTY_NAME = "qualitygate.default";
@SafeVarargs
public final QualityGateDto insertQualityGate(Consumer<QualityGateDto>... dtoPopulators) {
QualityGateDto qualityGate = new QualityGateDto()
- .setName(randomAlphanumeric(30))
+ .setName(secure().nextAlphanumeric(30))
.setUuid(Uuids.createFast())
.setBuiltIn(false);
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(qualityGate));
.setUuid(Uuids.createFast())
.setMetricUuid(metric.getUuid())
.setOperator("GT")
- .setErrorThreshold(randomNumeric(10));
+ .setErrorThreshold(secure().nextNumeric(10));
Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition));
dbClient.gateConditionDao().insert(condition, db.getSession());
db.commit();
import org.sonar.core.util.Uuids;
import static java.util.Arrays.stream;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class QualityProfileTesting {
.setKee(uuid)
.setRulesProfileUuid(Uuids.createFast())
.setName(uuid)
- .setLanguage(randomAlphanumeric(20))
+ .setLanguage(secure().nextAlphanumeric(20))
.setLastUsed(RANDOM.nextLong(Long.MAX_VALUE));
}
*/
public static QProfileChangeDto newQProfileChangeDto() {
return new QProfileChangeDto()
- .setUuid(randomAlphanumeric(40))
- .setRulesProfileUuid(randomAlphanumeric(40))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setRulesProfileUuid(secure().nextAlphanumeric(40))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE))
.setChangeType("ACTIVATED")
- .setUserUuid("userUuid_" + randomAlphanumeric(10));
+ .setUserUuid("userUuid_" + secure().nextAlphanumeric(10));
}
/**
*/
public static RulesProfileDto newRuleProfileDto(Consumer<RulesProfileDto>... populators) {
RulesProfileDto dto = new RulesProfileDto()
- .setUuid("uuid" + randomAlphabetic(10))
- .setName("name" + randomAlphabetic(10))
- .setLanguage("lang" + randomAlphabetic(5))
+ .setUuid("uuid" + secure().nextAlphabetic(10))
+ .setName("name" + secure().nextAlphabetic(10))
+ .setLanguage("lang" + secure().nextAlphabetic(5))
.setIsBuiltIn(false);
stream(populators).forEach(p -> p.accept(dto));
return dto;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Arrays.stream;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
}
public static RuleDto newRule() {
- return newRule(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30)));
+ return newRule(RuleKey.of(secure().nextAlphanumeric(30), secure().nextAlphanumeric(30)));
}
public static RuleDto newRule(RuleDescriptionSectionDto... ruleDescriptionSectionDtos) {
public static RuleDto newRule(RuleKey key, RuleDescriptionSectionDto... ruleDescriptionSectionDtos) {
RuleDto ruleDto = newRuleWithoutDescriptionSection(key);
if (ruleDescriptionSectionDtos.length == 0) {
- ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5)));
+ ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + secure().nextAlphabetic(5)));
} else {
stream(ruleDescriptionSectionDtos).forEach(ruleDto::addRuleDescriptionSectionDto);
}
return new RuleDto()
.setRepositoryKey(ruleKey.repository())
.setRuleKey(ruleKey.rule())
- .setUuid("rule_uuid_" + randomAlphanumeric(5))
- .setName("name_" + randomAlphanumeric(5))
+ .setUuid("rule_uuid_" + secure().nextAlphanumeric(5))
+ .setName("name_" + secure().nextAlphanumeric(5))
.setDescriptionFormat(RuleDto.Format.HTML)
.setType(CODE_SMELL)
.setCleanCodeAttribute(CleanCodeAttribute.CLEAR)
.setIsTemplate(false)
.setIsExternal(false)
.setIsAdHoc(false)
- .setSystemTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5)))
- .setLanguage("lang_" + randomAlphanumeric(3))
- .setGapDescription("gapDescription_" + randomAlphanumeric(5))
+ .setSystemTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5)))
+ .setLanguage("lang_" + secure().nextAlphanumeric(3))
+ .setGapDescription("gapDescription_" + secure().nextAlphanumeric(5))
.setDefRemediationBaseEffort(RANDOM.nextInt(10) + "h")
// voluntarily offset the remediation to be able to detect issues
.setDefRemediationGapMultiplier((RANDOM.nextInt(10) + 10) + "h")
.setRemediationBaseEffort(RANDOM.nextInt(10) + "h")
.setRemediationGapMultiplier(RANDOM.nextInt(10) + "h")
.setRemediationFunction("LINEAR_OFFSET")
- .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5)))
- .setNoteData("noteData_" + randomAlphanumeric(5))
- .setNoteUserUuid("noteUserUuid_" + randomAlphanumeric(5))
+ .setTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5)))
+ .setNoteData("noteData_" + secure().nextAlphanumeric(5))
+ .setNoteUserUuid("noteUserUuid_" + secure().nextAlphanumeric(5))
.setNoteCreatedAt(System.currentTimeMillis() - 200)
.setNoteUpdatedAt(System.currentTimeMillis() - 150)
- .setAdHocName("adHocName_" + randomAlphanumeric(5))
- .setAdHocDescription("adHocDescription_" + randomAlphanumeric(5))
+ .setAdHocName("adHocName_" + secure().nextAlphanumeric(5))
+ .setAdHocDescription("adHocDescription_" + secure().nextAlphanumeric(5))
.setAdHocSeverity(Severity.ALL.get(RANDOM.nextInt(Severity.ALL.size())))
.setAdHocType(RuleType.values()[RANDOM.nextInt(RuleType.values().length - 1)])
.setCreatedAt(currentTimeMillis)
.setUpdatedAt(currentTimeMillis + 5)
.setScope(Scope.MAIN)
- .setEducationPrinciples(Set.of(randomAlphanumeric(5), randomAlphanumeric(5)));
+ .setEducationPrinciples(Set.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(5)));
}
public static RuleParamDto newRuleParam(RuleDto rule) {
return new RuleParamDto()
.setRuleUuid(rule.getUuid())
- .setName("name_" + randomAlphabetic(5))
- .setDefaultValue("default_" + randomAlphabetic(5))
- .setDescription("description_" + randomAlphabetic(5))
+ .setName("name_" + secure().nextAlphabetic(5))
+ .setDefaultValue("default_" + secure().nextAlphabetic(5))
+ .setDescription("description_" + secure().nextAlphabetic(5))
.setType(RuleParamType.STRING.type());
}
public static DeprecatedRuleKeyDto newDeprecatedRuleKey() {
return new DeprecatedRuleKeyDto()
.setUuid(uuidFactory.create())
- .setOldRepositoryKey(randomAlphanumeric(50))
- .setOldRuleKey(randomAlphanumeric(50))
- .setRuleUuid(randomAlphanumeric(40))
+ .setOldRepositoryKey(secure().nextAlphanumeric(50))
+ .setOldRuleKey(secure().nextAlphanumeric(50))
+ .setRuleUuid(secure().nextAlphanumeric(40))
.setCreatedAt(System.currentTimeMillis());
}
}
public static RuleDto newCustomRule(RuleDto templateRule) {
- return newCustomRule(templateRule, "description_" + randomAlphabetic(5));
+ return newCustomRule(templateRule, "description_" + secure().nextAlphabetic(5));
}
public static RuleDto newCustomRule(RuleDto templateRule, String description) {
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbFileSources;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class FileSourceTester {
.setUuid(Uuids.createFast())
.setProjectUuid(file.branchUuid())
.setFileUuid(file.uuid())
- .setSrcHash(randomAlphanumeric(50))
- .setDataHash(randomAlphanumeric(50))
+ .setSrcHash(secure().nextAlphanumeric(50))
+ .setDataHash(secure().nextAlphanumeric(50))
.setLineHashes(IntStream.range(0, RANDOM.nextInt(21)).mapToObj(String::valueOf).toList())
- .setRevision(randomAlphanumeric(100))
+ .setRevision(secure().nextAlphanumeric(100))
.setSourceData(newRandomData(3).build())
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
.setUuid(Uuids.createFast())
.setProjectUuid(file.branchUuid())
.setFileUuid(file.uuid())
- .setSrcHash(randomAlphanumeric(50))
- .setDataHash(randomAlphanumeric(50))
+ .setSrcHash(secure().nextAlphanumeric(50))
+ .setDataHash(secure().nextAlphanumeric(50))
.setLineHashes(IntStream.range(0, numLines).mapToObj(String::valueOf).toList())
- .setRevision(randomAlphanumeric(100))
+ .setRevision(secure().nextAlphanumeric(100))
.setSourceData(newRandomData(numLines).build())
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
for (int i = 1; i <= numberOfLines; i++) {
dataBuilder.addLinesBuilder()
.setLine(i)
- .setScmRevision(randomAlphanumeric(15))
- .setScmAuthor(randomAlphanumeric(10))
+ .setScmRevision(secure().nextAlphanumeric(15))
+ .setScmAuthor(secure().nextAlphanumeric(10))
.setScmDate(RANDOM.nextLong(Long.MAX_VALUE))
- .setSource(randomAlphanumeric(20))
+ .setSource(secure().nextAlphanumeric(20))
.setLineHits(RANDOM.nextInt(4))
.setConditions(RANDOM.nextInt(4))
.setCoveredConditions(RANDOM.nextInt(4))
public static TelemetryMetricsSentDto newTelemetryMetricsSentDto() {
return new TelemetryMetricsSentDto(
- RandomStringUtils.randomAlphanumeric(40), // key
- RandomStringUtils.randomAlphanumeric(30) // dimension
+ RandomStringUtils.secure().nextAlphanumeric(40), // key
+ RandomStringUtils.secure().nextAlphanumeric(30) // dimension
).setLastSent(RANDOM.nextLong());
}
}
import java.util.Date;
import java.util.Random;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class GroupTesting {
public static GroupDto newGroupDto() {
return new GroupDto()
- .setUuid(randomAlphanumeric(40))
- .setName(randomAlphanumeric(255))
- .setDescription(randomAlphanumeric(200))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setName(secure().nextAlphanumeric(255))
+ .setDescription(secure().nextAlphanumeric(200))
.setCreatedAt(new Date(RANDOM.nextLong(Long.MAX_VALUE)))
.setUpdatedAt(new Date(RANDOM.nextLong(Long.MAX_VALUE)));
}
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.db.user.GroupTesting.newGroupDto;
}
public void markGroupAsGithubManaged(String groupUuid) {
- db.getDbClient().externalGroupDao().insert(db.getSession(), new ExternalGroupDto(groupUuid, randomAlphanumeric(20), "github"));
+ db.getDbClient().externalGroupDao().insert(db.getSession(), new ExternalGroupDto(groupUuid, secure().nextAlphanumeric(20), "github"));
db.commit();
}
package org.sonar.db.user;
import java.security.SecureRandom;
-import java.util.Collections;
import java.util.Locale;
import java.util.Random;
import javax.annotation.Nullable;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.math.RandomUtils.nextBoolean;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class UserTesting {
public static UserDto newUserDto() {
return new UserDto()
- .setUuid(randomAlphanumeric(40))
+ .setUuid(secure().nextAlphanumeric(40))
.setActive(true)
.setLocal(RANDOM.nextBoolean())
- .setLogin(randomAlphanumeric(30))
- .setName(randomAlphanumeric(30))
- .setEmail(randomAlphanumeric(30))
- .setScmAccounts(singletonList(randomAlphanumeric(40).toLowerCase(Locale.ENGLISH)))
- .setExternalId(randomAlphanumeric(40))
- .setExternalLogin(randomAlphanumeric(40))
- .setExternalIdentityProvider(randomAlphanumeric(40))
- .setSalt(randomAlphanumeric(40))
- .setCryptedPassword(randomAlphanumeric(40))
+ .setLogin(secure().nextAlphanumeric(30))
+ .setName(secure().nextAlphanumeric(30))
+ .setEmail(secure().nextAlphanumeric(30))
+ .setScmAccounts(singletonList(secure().nextAlphanumeric(40).toLowerCase(Locale.ENGLISH)))
+ .setExternalId(secure().nextAlphanumeric(40))
+ .setExternalLogin(secure().nextAlphanumeric(40))
+ .setExternalIdentityProvider(secure().nextAlphanumeric(40))
+ .setSalt(secure().nextAlphanumeric(40))
+ .setCryptedPassword(secure().nextAlphanumeric(40))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE))
.setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE));
}
public static UserDto newUserDtoRealistic() {
long timeNow = System.currentTimeMillis();
- String loginAndAndId = randomAlphanumeric(30);
+ String loginAndAndId = secure().nextAlphanumeric(30);
String realisticIdentityProvider = realisticIdentityProviders[nextInt(realisticIdentityProviders.length)];
boolean isExternal = nextBoolean();
String externalIdAndLogin = isExternal ? loginAndAndId + "_" + realisticIdentityProvider : loginAndAndId;
- return new UserDto().setUuid(randomAlphanumeric(40))
+ return new UserDto().setUuid(secure().nextAlphanumeric(40))
.setActive(nextBoolean())
.setLocal(!isExternal)
.setLogin(loginAndAndId)
.setName(name)
.setEmail(email)
.setLogin(login)
- .setExternalId(randomAlphanumeric(40))
- .setExternalLogin(randomAlphanumeric(40))
- .setExternalIdentityProvider(randomAlphanumeric(40));
+ .setExternalId(secure().nextAlphanumeric(40))
+ .setExternalLogin(secure().nextAlphanumeric(40))
+ .setExternalIdentityProvider(secure().nextAlphanumeric(40));
}
public static UserDto newDisabledUser() {
import org.sonar.api.utils.System2;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class UserTokenTesting {
public static UserTokenDto newUserToken() {
return new UserTokenDto()
- .setUserUuid("userUuid_" + randomAlphanumeric(40))
- .setName("name_" + randomAlphanumeric(20))
- .setTokenHash("hash_" + randomAlphanumeric(30))
+ .setUserUuid("userUuid_" + secure().nextAlphanumeric(40))
+ .setName("name_" + secure().nextAlphanumeric(20))
+ .setTokenHash("hash_" + secure().nextAlphanumeric(30))
.setCreatedAt(NOW)
.setType("USER_TOKEN");
}
public static UserTokenDto newProjectAnalysisToken() {
return new UserTokenDto()
- .setUserUuid("userUuid_" + randomAlphanumeric(40))
- .setName("name_" + randomAlphanumeric(20))
- .setTokenHash("hash_" + randomAlphanumeric(30))
- .setProjectUuid("projectUuid_" + randomAlphanumeric(20))
- .setProjectKey("projectKey_" + randomAlphanumeric(40))
- .setProjectName("Project " + randomAlphanumeric(40))
+ .setUserUuid("userUuid_" + secure().nextAlphanumeric(40))
+ .setName("name_" + secure().nextAlphanumeric(20))
+ .setTokenHash("hash_" + secure().nextAlphanumeric(30))
+ .setProjectUuid("projectUuid_" + secure().nextAlphanumeric(20))
+ .setProjectKey("projectKey_" + secure().nextAlphanumeric(40))
+ .setProjectName("Project " + secure().nextAlphanumeric(40))
.setCreatedAt(NOW)
.setType("PROJECT_ANALYSIS_TOKEN");
}
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class WebhookDeliveryTesting {
public static WebhookDeliveryDto newDto() {
return new WebhookDeliveryDto()
.setUuid(Uuids.createFast())
- .setWebhookUuid(randomAlphanumeric(40))
- .setProjectUuid(randomAlphanumeric(40))
- .setCeTaskUuid(randomAlphanumeric(40))
- .setAnalysisUuid(randomAlphanumeric(40))
- .setName(randomAlphanumeric(10))
- .setUrl(randomAlphanumeric(10))
+ .setWebhookUuid(secure().nextAlphanumeric(40))
+ .setProjectUuid(secure().nextAlphanumeric(40))
+ .setCeTaskUuid(secure().nextAlphanumeric(40))
+ .setAnalysisUuid(secure().nextAlphanumeric(40))
+ .setName(secure().nextAlphanumeric(10))
+ .setUrl(secure().nextAlphanumeric(10))
.setDurationMs(RANDOM.nextInt(Integer.MAX_VALUE))
.setHttpStatus(RANDOM.nextInt(Integer.MAX_VALUE))
.setSuccess(RANDOM.nextBoolean())
- .setPayload(randomAlphanumeric(10))
+ .setPayload(secure().nextAlphanumeric(10))
.setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE));
}
import java.util.function.Consumer;
import org.sonar.db.project.ProjectDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class WebhookTesting {
@SafeVarargs
private static WebhookDto getWebhookDto(Consumer<WebhookDto>... consumers) {
WebhookDto res = new WebhookDto()
- .setUuid(randomAlphanumeric(40))
- .setName(randomAlphanumeric(64))
- .setUrl("https://www.random-site/" + randomAlphanumeric(256))
- .setSecret(randomAlphanumeric(10))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setName(secure().nextAlphanumeric(64))
+ .setUrl("https://www.random-site/" + secure().nextAlphanumeric(256))
+ .setSecret(secure().nextAlphanumeric(10))
.setCreatedAt(Calendar.getInstance().getTimeInMillis());
Arrays.stream(consumers).forEach(consumer -> consumer.accept(res));
return res;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.CoreDbTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.platform.db.migration.step.ForceReloadingOfAllPlugins.OVERWRITE_HASH;
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
- map.put("KEE", randomAlphabetic(20));
- map.put("FILE_HASH", randomAlphabetic(32));
+ map.put("KEE", secure().nextAlphabetic(20));
+ map.put("FILE_HASH", secure().nextAlphabetic(32));
map.put("CREATED_AT", System.currentTimeMillis());
map.put("UPDATED_AT", System.currentTimeMillis());
map.put("TYPE", "EXTERNAL");
import org.sonar.db.MigrationDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
class PopulateNclocForForProjectsIT {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
- map.put("KEE", randomAlphabetic(20));
+ map.put("KEE", secure().nextAlphabetic(20));
map.put("QUALIFIER", "TRK");
map.put("PRIVATE", true);
map.put("UPDATED_AT", System.currentTimeMillis());
String uuid = uuidFactory.create();
map.put("UUID", uuid);
map.put("PROJECT_UUID", projectUuid);
- map.put("KEE", randomAlphabetic(20));
+ map.put("KEE", secure().nextAlphabetic(20));
map.put("BRANCH_TYPE", "PULL_REQUEST");
map.put("UPDATED_AT", System.currentTimeMillis());
map.put("CREATED_AT", System.currentTimeMillis());
import org.sonar.db.MigrationDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
class UpdateUserLocalValueInUsersIT {
Map<String, Object> map = new HashMap<>();
String uuid = uuidFactory.create();
map.put("UUID", uuid);
- map.put("LOGIN", randomAlphabetic(20));
- map.put("EXTERNAL_LOGIN", randomAlphabetic(20));
+ map.put("LOGIN", secure().nextAlphabetic(20));
+ map.put("EXTERNAL_LOGIN", secure().nextAlphabetic(20));
map.put("EXTERNAL_IDENTITY_PROVIDER", "sonarqube");
- map.put("EXTERNAL_ID", randomNumeric(5));
+ map.put("EXTERNAL_ID", secure().nextNumeric(5));
map.put("CREATED_AT", System.currentTimeMillis());
map.put("USER_LOCAL", userLocal);
map.put("RESET_PASSWORD", false);
import org.sonar.server.platform.db.migration.def.TinyIntColumnDef;
import org.sonar.server.platform.db.migration.def.VarcharColumnDef;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class RenameColumnsBuilderTest {
- private static final String NEW_COLUMN_NAME = "new_" + randomAlphabetic(6).toLowerCase();
+ private static final String NEW_COLUMN_NAME = "new_" + secure().nextAlphabetic(6).toLowerCase();
private static final DatabaseAndResult[] DATABASES = {
new DatabaseAndResult(new H2(), "ALTER TABLE ${table_name} ALTER COLUMN ${old_column_name} RENAME TO ${new_column_name}"),
DatabaseAndResult database,
ColumnDef columnDef) {
- String oldColumnName = "old_" + randomAlphabetic(6).toLowerCase();
- String tableName = "table_" + randomAlphabetic(6).toLowerCase();
+ String oldColumnName = "old_" + secure().nextAlphabetic(6).toLowerCase();
+ String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase();
List<String> result = new RenameColumnsBuilder(database.dialect(), tableName)
.renameColumn(oldColumnName, columnDef)
DatabaseAndResult database,
ColumnDef columnDef) {
- String tableName = "table_" + randomAlphabetic(6).toLowerCase();
+ String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase();
RenameColumnsBuilder renameColumnsBuilder = new RenameColumnsBuilder(database.dialect(), tableName)
.renameColumn(NEW_COLUMN_NAME, columnDef);
ColumnDef columnDef,
String illegalColumnName) {
- String tableName = "table_" + randomAlphabetic(6).toLowerCase();
+ String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase();
RenameColumnsBuilder renameColumnsBuilder = new RenameColumnsBuilder(database.dialect(), tableName)
.renameColumn(illegalColumnName, columnDef);
@Rule
public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60));
- private String threadName = RandomStringUtils.randomAlphabetic(12);
+ private String threadName = RandomStringUtils.secure().nextAlphabetic(12);
private TestBooleanSupplier booleanSupplier = new TestBooleanSupplier();
private TestAction stopAction = new TestAction();
import static com.google.common.collect.ImmutableMap.of;
import static java.util.Collections.synchronizedList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
}
private ImmutableMap.Builder<String, String> addRequiredNodeProperties(ImmutableMap.Builder<String, String> builder) {
- builder.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(4));
- builder.put(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(4));
+ builder.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(4));
+ builder.put(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(4));
builder.put(CLUSTER_NODE_HZ_PORT.getKey(), String.valueOf(1 + new Random().nextInt(999)));
return builder;
}
import org.sonar.process.cluster.health.NodeHealth;
import static java.lang.String.valueOf;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.Mockito.mock;
@Test
public void constructor_throws_NPE_if_NetworkUtils_getHostname_returns_null_and_property_is_not_set() {
Properties properties = new Properties();
- properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
Props props = new Props(properties);
assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock))
@Test
public void constructor_throws_IAE_if_property_node_port_is_not_set() {
Properties properties = new Properties();
- properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34));
+ properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34));
Props props = new Props(properties);
assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock))
@Test
public void constructor_throws_FormatException_if_property_node_port_is_not_an_integer() {
- String port = randomAlphabetic(3);
+ String port = secure().nextAlphabetic(3);
Properties properties = new Properties();
- properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
properties.put(CLUSTER_NODE_HZ_PORT.getKey(), port);
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34));
Props props = new Props(properties);
assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock))
@Test
public void get_returns_name_and_port_from_properties_at_constructor_time() {
- String name = randomAlphanumeric(3);
+ String name = secure().nextAlphanumeric(3);
int port = 1 + random.nextInt(4);
Properties properties = new Properties();
properties.setProperty(CLUSTER_NODE_NAME.getKey(), name);
properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(port));
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34));
when(clock.now()).thenReturn(1L + random.nextInt(87));
SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock);
assertThat(nodeHealth.getDetails().getPort()).isEqualTo(port);
// change values in properties
- properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(6));
+ properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(6));
properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(99)));
NodeHealth newNodeHealth = underTest.get();
@Test
public void get_returns_host_from_property_if_set_at_constructor_time() {
- String host = randomAlphanumeric(55);
+ String host = secure().nextAlphanumeric(55);
Properties properties = new Properties();
- properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4)));
properties.setProperty(CLUSTER_NODE_HOST.getKey(), host);
when(clock.now()).thenReturn(1L + random.nextInt(87));
assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host);
// change now
- properties.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(96));
+ properties.setProperty(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(96));
NodeHealth newNodeHealth = underTest.get();
}
private void getReturnsHostFromNetworkUtils(@Nullable String hostPropertyValue) {
- String host = randomAlphanumeric(34);
+ String host = secure().nextAlphanumeric(34);
Properties properties = new Properties();
- properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4)));
if (hostPropertyValue != null) {
properties.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue);
assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host);
// change now
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(96));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(96));
NodeHealth newNodeHealth = underTest.get();
}
private long setRequiredPropertiesAndMocks(Properties properties) {
- properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4)));
long now = 1L + random.nextInt(87);
when(clock.now()).thenReturn(now);
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34));
return now;
}
}
import org.sonar.process.ProcessId;
import org.sonar.process.System2;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
};
- assertThatThrownBy(() -> underTest.setEnvVariable(null, randomAlphanumeric(30)))
+ assertThatThrownBy(() -> underTest.setEnvVariable(null, secure().nextAlphanumeric(30)))
.isInstanceOf(NullPointerException.class)
.hasMessage("key can't be null");
}
};
- assertThatThrownBy(() -> underTest.setEnvVariable(randomAlphanumeric(30), null))
+ assertThatThrownBy(() -> underTest.setEnvVariable(secure().nextAlphanumeric(30), null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
File workDir = temp.newFolder();
System2 system2 = Mockito.mock(System2.class);
Map<String, String> env = new HashMap<>();
- String key1 = randomAlphanumeric(3);
- env.put(key1, randomAlphanumeric(9));
+ String key1 = secure().nextAlphanumeric(3);
+ env.put(key1, secure().nextAlphanumeric(9));
when(system2.getenv()).thenReturn(env);
AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, system2) {
import org.junit.runner.RunWith;
import org.sonar.process.Props;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void constructor_forces_boostrap_checks_if_jdbc_url_property_is_not_h2() throws IOException {
- properties.put("sonar.jdbc.url", randomAlphanumeric(53));
+ properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53));
File tmpDir = temporaryFolder.newFolder();
EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir);
@Test
public void boostrap_checks_can_be_set_true_if_jdbc_other_than_h2() throws IOException {
- properties.put("sonar.jdbc.url", randomAlphanumeric(53));
+ properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53));
properties.put("sonar.es.bootstrap.checks.disable", "true");
File tmpDir = temporaryFolder.newFolder();
@Test
public void boostrap_checks_can_be_set_false_if_jdbc_other_than_h2() throws IOException {
- properties.put("sonar.jdbc.url", randomAlphanumeric(53));
+ properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53));
properties.put("sonar.es.bootstrap.checks.disable", "false");
File tmpDir = temporaryFolder.newFolder();
import org.sonar.process.Props;
import static java.lang.String.valueOf;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
public class JvmOptionsTest {
private final Random random = new Random();
- private final String randomPropertyName = randomAlphanumeric(3);
- private final String randomPrefix = "-" + randomAlphabetic(5).toLowerCase(Locale.ENGLISH);
- private final String randomValue = randomAlphanumeric(4).toLowerCase(Locale.ENGLISH);
+ private final String randomPropertyName = secure().nextAlphanumeric(3);
+ private final String randomPrefix = "-" + secure().nextAlphabetic(5).toLowerCase(Locale.ENGLISH);
+ private final String randomValue = secure().nextAlphanumeric(4).toLowerCase(Locale.ENGLISH);
private final Properties properties = new Properties();
private final JvmOptions underTest = new JvmOptions();
@Test
public void constructor_throws_IAE_if_any_option_prefix_does_not_start_with_dash() {
- String invalidPrefix = randomAlphanumeric(3);
+ String invalidPrefix = secure().nextAlphanumeric(3);
Map<String, String> mandatoryJvmOptions = shuffleThenToMap(
Stream.of(
IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))),
@Test
public void add_throws_IAE_if_argument_does_not_start_with_dash() {
- expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(randomAlphanumeric(3)));
+ expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(secure().nextAlphanumeric(3)));
}
public void add_throws_MessageException_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() {
String[] optionOverrides = {
randomPrefix,
- randomPrefix + randomAlphanumeric(1),
- randomPrefix + randomAlphanumeric(2),
- randomPrefix + randomAlphanumeric(3),
- randomPrefix + randomAlphanumeric(4),
+ randomPrefix + secure().nextAlphanumeric(1),
+ randomPrefix + secure().nextAlphanumeric(2),
+ randomPrefix + secure().nextAlphanumeric(3),
+ randomPrefix + secure().nextAlphanumeric(4),
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(2),
randomPrefix + randomValue.substring(3)
public void add_checks_against_mandatory_options_is_case_sensitive() {
String[] optionOverrides = {
randomPrefix,
- randomPrefix + randomAlphanumeric(1),
- randomPrefix + randomAlphanumeric(2),
- randomPrefix + randomAlphanumeric(3),
- randomPrefix + randomAlphanumeric(4),
+ randomPrefix + secure().nextAlphanumeric(1),
+ randomPrefix + secure().nextAlphanumeric(2),
+ randomPrefix + secure().nextAlphanumeric(3),
+ randomPrefix + secure().nextAlphanumeric(4),
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(2),
randomPrefix + randomValue.substring(3)
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(2),
randomPrefix + randomValue.substring(3),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(1),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(2),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(3),
- randomPrefix + randomValue + randomAlphanumeric(1)
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(1),
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(2),
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(3),
+ randomPrefix + randomValue + secure().nextAlphanumeric(1)
};
JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue));
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(2),
randomPrefix + randomValue.substring(3),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(1),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(2),
- randomPrefix + randomValue.substring(3) + randomAlphanumeric(3),
- randomPrefix + randomValue + randomAlphanumeric(1)
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(1),
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(2),
+ randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(3),
+ randomPrefix + randomValue + secure().nextAlphanumeric(1)
};
JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue));
@Test
public void addFromMandatoryProperty_reports_all_overriding_options_in_single_exception() {
String overriding1 = randomPrefix;
- String overriding2 = randomPrefix + randomValue + randomAlphanumeric(1);
+ String overriding2 = randomPrefix + randomValue + secure().nextAlphanumeric(1);
properties.setProperty(randomPropertyName, "-foo " + overriding1 + " -bar " + overriding2);
JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue));
import org.sonar.process.System2;
import static java.util.Optional.ofNullable;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public void constructor_logs_warning_if_env_variable_ES_JVM_OPTIONS_is_set_and_non_empty() {
this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(EsSettings.class);
Props props = minimalProps();
- when(system.getenv("ES_JVM_OPTIONS")).thenReturn(randomAlphanumeric(2));
+ when(system.getenv("ES_JVM_OPTIONS")).thenReturn(secure().nextAlphanumeric(2));
new EsSettings(props, new EsInstallation(props), system);
assertThat(listAppender.getLogs())
private Props minimalProps() {
Props props = new Props(new Properties());
- props.set(PATH_HOME.getKey(), randomAlphanumeric(12));
- props.set(PATH_DATA.getKey(), randomAlphanumeric(12));
- props.set(PATH_TEMP.getKey(), randomAlphanumeric(12));
- props.set(PATH_LOGS.getKey(), randomAlphanumeric(12));
- props.set(CLUSTER_NAME.getKey(), randomAlphanumeric(12));
+ props.set(PATH_HOME.getKey(), secure().nextAlphanumeric(12));
+ props.set(PATH_DATA.getKey(), secure().nextAlphanumeric(12));
+ props.set(PATH_TEMP.getKey(), secure().nextAlphanumeric(12));
+ props.set(PATH_LOGS.getKey(), secure().nextAlphanumeric(12));
+ props.set(CLUSTER_NAME.getKey(), secure().nextAlphanumeric(12));
return props;
}
import org.hamcrest.CoreMatchers;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeThat;
@Test
public void toInetAddress_returns_empty_on_unvalid_IP_and_hostname() {
- assertThat(underTest.toInetAddress(randomAlphabetic(32))).isEmpty();
+ assertThat(underTest.toInetAddress(secure().nextAlphabetic(32))).isEmpty();
}
@Test
@UseDataProvider("beforeAndAfterBlanks")
public void constructor_trims_key_and_values_from_Properties_argument(String blankBefore, String blankAfter) {
Properties properties = new Properties();
- String key = RandomStringUtils.randomAlphanumeric(3);
- String value = RandomStringUtils.randomAlphanumeric(3);
+ String key = RandomStringUtils.secure().nextAlphanumeric(3);
+ String value = RandomStringUtils.secure().nextAlphanumeric(3);
properties.put(blankBefore + key + blankAfter, blankBefore + value + blankAfter);
Props underTest = new Props(properties);
import java.util.Random;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;
public void build_throws_NPE_if_host_is_null() {
builderUnderTest
.setType(randomType)
- .setName(randomAlphanumeric(2));
+ .setName(secure().nextAlphanumeric(2));
assertThatThrownBy(() -> builderUnderTest.build())
.isInstanceOf(NullPointerException.class)
public void build_throws_IAE_if_setPort_not_called() {
builderUnderTest
.setType(randomType)
- .setName(randomAlphanumeric(2))
- .setHost(randomAlphanumeric(3));
+ .setName(secure().nextAlphanumeric(2))
+ .setHost(secure().nextAlphanumeric(3));
assertThatThrownBy(() -> builderUnderTest.build())
.isInstanceOf(IllegalArgumentException.class)
public void build_throws_IAE_if_setStarted_not_called() {
builderUnderTest
.setType(randomType)
- .setName(randomAlphanumeric(2))
- .setHost(randomAlphanumeric(3))
+ .setName(secure().nextAlphanumeric(2))
+ .setHost(secure().nextAlphanumeric(3))
.setPort(1 + random.nextInt(33));
assertThatThrownBy(() -> builderUnderTest.build())
@Test
public void verify_toString() {
- String name = randomAlphanumeric(3);
- String host = randomAlphanumeric(10);
+ String name = secure().nextAlphanumeric(3);
+ String host = secure().nextAlphanumeric(10);
int port = 1 + random.nextInt(10);
long startedAt = 1 + random.nextInt(666);
@Test
public void verify_getters() {
- String name = randomAlphanumeric(3);
- String host = randomAlphanumeric(10);
+ String name = secure().nextAlphanumeric(3);
+ String host = secure().nextAlphanumeric(10);
int port = 1 + random.nextInt(10);
long startedAt = 1 + random.nextInt(666);
import java.util.Random;
import java.util.stream.IntStream;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;
NodeHealth.Builder builder = newNodeHealthBuilder()
.setStatus(randomStatus())
.setDetails(randomNodeDetails());
- IntStream.range(0, minCauseCount + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).forEach(builder::addCause);
+ IntStream.range(0, minCauseCount + random.nextInt(2)).mapToObj(i -> secure().nextAlphanumeric(4)).forEach(builder::addCause);
return builder;
}
NodeDetails.Builder randomNodeDetailsBuilder() {
return newNodeDetailsBuilder()
.setType(randomType())
- .setName(randomAlphanumeric(3))
- .setHost(randomAlphanumeric(10))
+ .setName(secure().nextAlphanumeric(3))
+ .setHost(secure().nextAlphanumeric(10))
.setPort(1 + random.nextInt(10))
.setStartedAt(1 + random.nextInt(666));
}
import java.util.stream.IntStream;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;
public void clearClauses_clears_clauses_of_builder() {
NodeHealth.Builder underTest = testSupport.randomBuilder();
NodeHealth original = underTest
- .addCause(randomAlphanumeric(3))
+ .addCause(secure().nextAlphanumeric(3))
.build();
underTest.clearCauses();
.clearCauses()
.setStatus(newRandomStatus)
.setDetails(newNodeDetails);
- String[] newCauses = IntStream.range(0, 1 + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new);
+ String[] newCauses = IntStream.range(0, 1 + random.nextInt(2)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new);
Arrays.stream(newCauses).forEach(builder::addCause);
NodeHealth newNodeHealth = builder.build();
@Test
public void verify_toString() {
NodeDetails nodeDetails = testSupport.randomNodeDetails();
- String cause = randomAlphanumeric(4);
+ String cause = secure().nextAlphanumeric(4);
NodeHealth.Builder builder = builderUnderTest
.setStatus(randomStatus)
.setDetails(nodeDetails)
NodeHealth.Builder builder = builderUnderTest
.setStatus(randomStatus)
.setDetails(nodeDetails);
- String[] causes = IntStream.range(0, random.nextInt(10)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new);
+ String[] causes = IntStream.range(0, random.nextInt(10)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new);
Arrays.stream(causes).forEach(builder::addCause);
NodeHealth underTest = builder.build();
import org.sonar.process.cluster.hz.HazelcastMember;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doReturn;
logging.setLevel(Level.TRACE);
NodeHealth newNodeHealth = randomNodeHealth();
Map<String, TimestampedNodeHealth> map = new HashMap<>();
- map.put(randomAlphanumeric(4), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong()));
+ map.put(secure().nextAlphanumeric(4), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong()));
doReturn(new HashMap<>(map)).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE);
UUID uuid = UUID.randomUUID();
when(hazelcastMember.getUuid()).thenReturn(uuid);
public void readAll_logs_message_for_each_non_existing_member_ignored_if_TRACE() {
logging.setLevel(Level.TRACE);
Map<String, TimestampedNodeHealth> map = new HashMap<>();
- String memberUuid1 = randomAlphanumeric(44);
- String memberUuid2 = randomAlphanumeric(44);
+ String memberUuid1 = secure().nextAlphanumeric(44);
+ String memberUuid2 = secure().nextAlphanumeric(44);
map.put(memberUuid1, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1));
map.put(memberUuid2, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1));
when(hazelcastMember.getClusterTime()).thenReturn(clusterTime);
.setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)])
.setDetails(newNodeDetailsBuilder()
.setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION)
- .setName(randomAlphanumeric(30))
- .setHost(randomAlphanumeric(10))
+ .setName(secure().nextAlphanumeric(30))
+ .setHost(secure().nextAlphanumeric(10))
.setPort(1 + random.nextInt(666))
.setStartedAt(1 + random.nextInt(852))
.build())
import org.sonar.process.Props;
import static java.lang.String.valueOf;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertThrows;
@Test
public void constructor_sets_status_to_ERROR() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Properties properties = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build();
assertThat(properties.getProperty("status")).isEqualTo("ERROR");
@Test
public void get_always_returns_a_new_object() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Properties previous = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build();
for (int i = 0; i < 2 + new Random().nextInt(5); i++) {
@Test
public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() {
- String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5);
+ String threadIdFieldPattern = RandomStringUtils.secure().nextAlphabetic(5);
String pattern = newLog4JPropertiesBuilder().buildLogPattern(
newRootLoggerConfigBuilder()
@Test
public void configureGlobalFileLog_sets_properties_for_daily_time_rolling_policy_with_max_7_files_for_empty_props() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
var underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
.logDir(logDir)
@Test
public void configureGlobalFileLog_throws_MessageException_when_property_is_not_supported() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
- String invalidPropertyValue = randomAlphanumeric(3);
+ String logPattern = secure().nextAlphanumeric(15);
+ String invalidPropertyValue = secure().nextAlphanumeric(3);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
ROLLING_POLICY_PROPERTY, invalidPropertyValue)
.rootLoggerConfig(esRootLoggerConfig)
@Test
public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_with_max_7_files_when_property_starts_with_time_colon() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
- String timePattern = randomAlphanumeric(6);
+ String logPattern = secure().nextAlphanumeric(15);
+ String timePattern = secure().nextAlphanumeric(6);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
ROLLING_POLICY_PROPERTY, "time:" + timePattern)
@Test
public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_when_property_starts_with_time_colon_and_specified_max_number_of_files() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
- String timePattern = randomAlphanumeric(6);
+ String logPattern = secure().nextAlphanumeric(15);
+ String timePattern = secure().nextAlphanumeric(6);
int maxFile = 1 + new Random().nextInt(10);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
@Test
public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_with_max_7_files_when_property_starts_with_size_colon() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
- String sizePattern = randomAlphanumeric(6);
+ String logPattern = secure().nextAlphanumeric(15);
+ String sizePattern = secure().nextAlphanumeric(6);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
ROLLING_POLICY_PROPERTY, "size:" + sizePattern)
.rootLoggerConfig(esRootLoggerConfig)
@Test
public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_when_property_starts_with_size_colon_and_specified_max_number_of_files() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
- String sizePattern = randomAlphanumeric(6);
+ String logPattern = secure().nextAlphanumeric(15);
+ String sizePattern = secure().nextAlphanumeric(6);
int maxFile = 1 + new Random().nextInt(10);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
ROLLING_POLICY_PROPERTY, "size:" + sizePattern,
@Test
public void configureGlobalFileLog_sets_properties_for_no_rolling_policy_when_property_is_none() throws Exception {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
ROLLING_POLICY_PROPERTY, "none")
.rootLoggerConfig(esRootLoggerConfig)
@Test
public void enable_all_logs_to_stdout_write_additionally_Console_appender() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(ROLLING_POLICY_PROPERTY, "none")
.enableAllLogsToConsole(true)
@Test
public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_rootLoggerName_of_Log4J() throws IOException {
- LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build();
+ LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(secure().nextAlphanumeric(2)).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
public void apply_fails_with_IAE_if_global_property_has_unsupported_level() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "ERROR")
.rootLoggerConfig(esRootLoggerConfig)
public void apply_fails_with_IAE_if_process_property_has_unsupported_level() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "ERROR")
.rootLoggerConfig(esRootLoggerConfig)
public void apply_sets_root_logger_to_INFO_if_no_property_is_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
public void apply_sets_root_logger_to_global_property_if_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "TRACE")
.rootLoggerConfig(esRootLoggerConfig)
public void apply_sets_root_logger_to_process_property_if_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "DEBUG")
.rootLoggerConfig(esRootLoggerConfig)
public void apply_sets_root_logger_to_process_property_over_global_property_if_both_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "DEBUG",
"sonar.log.level.web", "TRACE")
public void apply_sets_domain_property_over_process_and_global_property_if_all_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
"sonar.log.level", "DEBUG",
public void apply_sets_domain_property_over_process_property_if_both_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
"sonar.log.level.web", "DEBUG",
public void apply_sets_domain_property_over_global_property_if_both_set() throws IOException {
LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(
"sonar.log.level", "DEBUG",
@Test
public void apply_fails_with_IAE_if_domain_property_has_unsupported_level() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX).build();
public void apply_accepts_any_level_as_hardcoded_level(Level level) throws IOException {
LogLevelConfig config = newLogLevelConfig().immutableLevel("bar", level).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
@Test
public void apply_set_level_to_OFF_if_sonar_global_level_is_not_set() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
public void apply_does_not_create_loggers_property_if_only_root_level_is_defined() throws IOException {
LogLevelConfig logLevelConfig = newLogLevelConfig().rootLevelFor(ProcessId.APP).build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
.build();
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder()
.rootLoggerConfig(esRootLoggerConfig)
@Test
public void apply_does_not_set_level_if_sonar_global_level_is_TRACE() throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", Level.TRACE.toString())
.rootLoggerConfig(esRootLoggerConfig)
private void setLevelToOff(Level globalLogLevel) throws IOException {
File logDir = temporaryFolder.newFolder();
- String logPattern = randomAlphanumeric(15);
+ String logPattern = secure().nextAlphanumeric(15);
Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", globalLogLevel.toString())
.rootLoggerConfig(esRootLoggerConfig)
public class LogLevelConfigTest {
- private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20);
+ private final String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(20);
private LogLevelConfig.Builder underTest = newBuilder(rootLoggerName);
@Test
@Test
public void getLoggerName_returns_name_passed_to_builder() {
- String rootLoggerName = RandomStringUtils.randomAlphabetic(32);
+ String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(32);
LogLevelConfig logLevelConfig = newBuilder(rootLoggerName).build();
import org.sonar.process.Props;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
@Test
public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() {
- String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5);
+ String threadIdFieldPattern = RandomStringUtils.secure().nextAlphabetic(5);
String pattern = underTest.buildLogPattern(
newRootLoggerConfigBuilder()
.setProcessId(ProcessId.APP)
@Test
public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_ROOT_LOGGER_NAME_of_LogBack() {
- LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build();
+ LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(secure().nextAlphanumeric(2)).build();
assertThatThrownBy(() -> underTest.apply(logLevelConfig, props))
.isInstanceOf(IllegalArgumentException.class)
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.newindex.FakeIndexDefinition;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
@Rule
public EsTester es = EsTester.createCustom(new MetadataIndexDefinitionBridge(), new FakeIndexDefinition());
private final MetadataIndex underTest = new MetadataIndexImpl(es.client());
- private final String indexName = randomAlphabetic(20).toLowerCase(Locale.ENGLISH);
+ private final String indexName = secure().nextAlphabetic(20).toLowerCase(Locale.ENGLISH);
private final Index index = new Random().nextBoolean() ? Index.simple(indexName) : Index.withRelations(indexName);
@Test
@Test
public void hash_should_be_able_to_be_automatically_set() {
- String hash = randomAlphanumeric(20);
+ String hash = secure().nextAlphanumeric(20);
underTest.setHash(index, hash);
assertThat(underTest.getHash(index)).hasValue(hash);
}
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void set_project_version() {
- String version = randomAlphanumeric(5);
+ String version = secure().nextAlphanumeric(5);
underTest.setProjectVersion(version);
@Test
public void getProjectKey_returns_projectKey_if_setProject_has_been_called() {
- String projectKey = randomAlphabetic(5);
- String projectName = randomAlphabetic(6);
- String branchName = randomAlphabetic(7);
- String pullRequest = randomAlphabetic(8);
+ String projectKey = secure().nextAlphabetic(5);
+ String projectName = secure().nextAlphabetic(6);
+ String branchName = secure().nextAlphabetic(7);
+ String pullRequest = secure().nextAlphabetic(8);
underTest.setProject(projectKey, projectName, branchName, pullRequest);
assertThat(underTest.getProjectKey()).isEqualTo(projectKey);
@Test
public void getProjectKey_returns_value_of_field_projectKey() {
- String projectKey = randomAlphabetic(5);
+ String projectKey = secure().nextAlphabetic(5);
underTest.setFieldValue("projectKey", projectKey);
assertThat(underTest.getProjectKey()).isEqualTo(projectKey);
@Test
public void RuleDefinition_implements_equals_base_on_name_and_language() {
- String name = randomAlphabetic(5);
- String language = randomAlphabetic(6);
+ String name = secure().nextAlphabetic(5);
+ String language = secure().nextAlphabetic(6);
RuleDefinition underTest = new RuleDefinition(name, language);
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new RuleDefinition(name, language))
.isNotEqualTo(new RuleDefinition(language, name))
- .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name))
- .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7)))
+ .isNotEqualTo(new RuleDefinition(secure().nextAlphabetic(7), name))
+ .isNotEqualTo(new RuleDefinition(language, secure().nextAlphabetic(7)))
.isNotEqualTo(new RuleDefinition(language, null))
.isNotNull()
.isNotEqualTo(new Object());
@Test
public void RuleDefinition_implements_hashcode_base_on_name_and_language() {
- String name = randomAlphabetic(5);
- String language = randomAlphabetic(6);
+ String name = secure().nextAlphabetic(5);
+ String language = secure().nextAlphabetic(6);
RuleDefinition underTest = new RuleDefinition(name, language);
assertThat(underTest)
assertThat(underTest.hashCode())
.isNotEqualTo(new RuleDefinition(language, name).hashCode())
- .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name).hashCode())
- .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7)).hashCode())
+ .isNotEqualTo(new RuleDefinition(secure().nextAlphabetic(7), name).hashCode())
+ .isNotEqualTo(new RuleDefinition(language, secure().nextAlphabetic(7)).hashCode())
.isNotEqualTo(new RuleDefinition(language, null).hashCode())
.isNotEqualTo(new Object().hashCode());
}
import org.sonar.db.rule.RuleParamDto;
import static java.util.Collections.emptySet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
@Test
public void findByKey_populates_system_tags_but_not_tags() {
RuleDto ruleDto = dbTester.rules()
- .insert(t -> t.setSystemTags(Set.of(randomAlphanumeric(5), randomAlphanumeric(6))).setTags(emptySet()));
+ .insert(t -> t.setSystemTags(Set.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(6))).setTags(emptySet()));
dbTester.rules().insertRule();
Rule rule = underTest.findByKey(ruleDto.getKey());
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
import static org.sonar.db.rule.RuleTesting.newRule;
@Test
public void index_long_rule_description() {
- RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), randomAlphanumeric(100000));
+ RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), secure().nextAlphanumeric(100000));
RuleDto rule = dbTester.rules().insert(newRule(ruleDescriptionSectionDto));
underTest.commitAndIndex(dbTester.getSession(), rule.getUuid());
import org.sonar.db.webhook.WebhookDeliveryDto;
import org.sonar.db.webhook.WebhookDeliveryTesting;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void persist_effective_url_if_present() {
when(uuidFactory.create()).thenReturn(DELIVERY_UUID);
- String effectiveUrl = randomAlphabetic(15);
+ String effectiveUrl = secure().nextAlphabetic(15);
WebhookDelivery delivery = newBuilderTemplate()
.setEffectiveUrl(effectiveUrl)
.build();
private static WebhookDelivery.Builder newBuilderTemplate() {
return new WebhookDelivery.Builder()
- .setWebhook(new Webhook("WEBHOOK_UUID_1", "COMPONENT1", "TASK1", RandomStringUtils.randomAlphanumeric(40),"Jenkins", "http://jenkins", null))
+ .setWebhook(new Webhook("WEBHOOK_UUID_1", "COMPONENT1", "TASK1", RandomStringUtils.secure().nextAlphanumeric(40),"Jenkins", "http://jenkins", null))
.setPayload(new WebhookPayload("my-project", "{json}"))
.setAt(1_000_000L)
.setHttpStatus(200)
@RunWith(DataProviderRunner.class)
public class ConfigurationProviderTest {
private static final String[] EMPTY_STRING_ARRAY = {};
- private final String nonDeclaredKey = RandomStringUtils.randomAlphabetic(3);
- private final String nonMultivalueKey = RandomStringUtils.randomAlphabetic(3);
- private final String multivalueKey = RandomStringUtils.randomAlphabetic(3);
+ private final String nonDeclaredKey = RandomStringUtils.secure().nextAlphabetic(3);
+ private final String nonMultivalueKey = RandomStringUtils.secure().nextAlphabetic(3);
+ private final String multivalueKey = RandomStringUtils.secure().nextAlphabetic(3);
private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE,
builder(nonMultivalueKey).multiValues(false).build(),
builder(multivalueKey).multiValues(true).build()));
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class DocIdTest {
@Test
public void equals_is_based_on_index_type_and_id() {
- String index = randomAlphabetic(5);
- String type = randomAlphabetic(6);
- String id = randomAlphabetic(7);
+ String index = secure().nextAlphabetic(5);
+ String type = secure().nextAlphabetic(6);
+ String id = secure().nextAlphabetic(7);
DocId underTest = new DocId(index, type, id);
assertThat(underTest)
.isEqualTo(new DocId(index, type, id))
- .isNotEqualTo(new DocId(randomAlphabetic(7), type, id))
- .isNotEqualTo(new DocId(index, type, randomAlphabetic(7)))
- .isNotEqualTo(new DocId(index, randomAlphabetic(7), id))
- .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id))
- .isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8)))
- .isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8)))
- .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9)));
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, id))
+ .isNotEqualTo(new DocId(index, type, secure().nextAlphabetic(7)))
+ .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), id))
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), id))
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, secure().nextAlphabetic(8)))
+ .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), secure().nextAlphabetic(8)))
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), secure().nextAlphabetic(9)));
}
@Test
public void hashcode_is_based_on_index_type_and_id() {
- String index = randomAlphabetic(5);
- String type = randomAlphabetic(6);
- String id = randomAlphabetic(7);
+ String index = secure().nextAlphabetic(5);
+ String type = secure().nextAlphabetic(6);
+ String id = secure().nextAlphabetic(7);
DocId underTest = new DocId(index, type, id);
assertThat(underTest.hashCode())
.isEqualTo(new DocId(index, type, id).hashCode())
- .isNotEqualTo(new DocId(randomAlphabetic(7), type, id).hashCode())
- .isNotEqualTo(new DocId(index, type, randomAlphabetic(7)).hashCode())
- .isNotEqualTo(new DocId(index, randomAlphabetic(7), id).hashCode())
- .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id).hashCode())
- .isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8)).hashCode())
- .isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8)).hashCode())
- .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9)).hashCode());
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, id).hashCode())
+ .isNotEqualTo(new DocId(index, type, secure().nextAlphabetic(7)).hashCode())
+ .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), id).hashCode())
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), id).hashCode())
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, secure().nextAlphabetic(8)).hashCode())
+ .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), secure().nextAlphabetic(8)).hashCode())
+ .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), secure().nextAlphabetic(9)).hashCode());
}
}
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.newindex.SettingsConfiguration;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
@DataProvider
public static Object[][] paarOfIndicesWithSameName() {
- String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
return new Object[][] {
{Index.simple(indexName), Index.simple(indexName)},
{Index.withRelations(indexName), Index.withRelations(indexName)},
import org.junit.Test;
import org.junit.runner.RunWith;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void getName_returns_constructor_parameter() {
- String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
assertThat(Index.simple(indexName).getName()).isEqualTo(indexName);
assertThat(Index.withRelations(indexName).getName()).isEqualTo(indexName);
@Test
public void getJoinField_returns_name_based_on_index_name() {
- String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
Index underTest = Index.withRelations(indexName);
assertThat(underTest.getJoinField()).isEqualTo("join_" + indexName);
import java.util.stream.Stream;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
fieldSetters.forEach(c -> {
TestFieldAware underTest = new TestFieldAware();
// should not fail for other field name
- c.accept(underTest, randomAlphabetic(1 + new Random().nextInt(10)));
+ c.accept(underTest, secure().nextAlphabetic(1 + new Random().nextInt(10)));
// fails whatever the case
Stream.of("indexType", "indextype", "InDexType", "INDEXTYPE")
.forEach(illegalFieldName -> {
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
public class NewAuthorizedIndexTest {
- private String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ private String someIndexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
private Index someIndex = Index.withRelations(someIndexName);
private MapSettings settings = new MapSettings();
private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
import org.sonar.server.es.IndexType;
import org.sonar.server.es.IndexType.IndexMainType;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.data.MapEntry.entry;
public class NewIndexTest {
- private static final String someIndexName = randomAlphabetic(5).toLowerCase();
+ private static final String someIndexName = secure().nextAlphabetic(5).toLowerCase();
private MapSettings settings = new MapSettings();
private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
@DataProvider
public static Object[][] indexAndTypeMappings() {
- String indexName = randomAlphabetic(5).toLowerCase();
+ String indexName = secure().nextAlphabetic(5).toLowerCase();
MapSettings settings = new MapSettings();
SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build();
Index index = Index.withRelations(indexName);
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
@RunWith(DataProviderRunner.class)
public class NewRegularIndexTest {
- private static final String SOME_INDEX_NAME = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ private static final String SOME_INDEX_NAME = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
private MapSettings settings = new MapSettings();
@DataProvider
public static Object[][] indexes() {
- String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH);
+ String someIndexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH);
return new Object[][] {
{Index.simple(someIndexName)},
{Index.withRelations(someIndexName)}
import org.junit.Test;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
@Test
public void addFilter_fails_if_fieldname_is_null() {
- String name = randomAlphabetic(12);
+ String name = secure().nextAlphabetic(12);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
BoolQueryBuilder boolQuery = boolQuery();
@Test
public void addFilter_fails_if_field_with_name_already_exists() {
- String name1 = randomAlphabetic(12);
- String name2 = randomAlphabetic(15);
+ String name1 = secure().nextAlphabetic(12);
+ String name2 = secure().nextAlphabetic(15);
FilterScope filterScope1 = mock(FilterScope.class);
FilterScope filterScope2 = mock(FilterScope.class);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
@Test
public void addFilter_does_not_add_filter_if_QueryBuilder_is_null() {
- String name = randomAlphabetic(12);
- String name2 = randomAlphabetic(14);
+ String name = secure().nextAlphabetic(12);
+ String name2 = secure().nextAlphabetic(14);
RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters();
BoolQueryBuilder query = boolQuery();
allFilters.addFilter(name, mock(FilterScope.class), query)
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class NestedFieldFilterScopeTest {
@Test
public void constructor_fails_with_NPE_if_fieldName_is_null() {
- String nestedFieldName = randomAlphabetic(11);
- String value = randomAlphabetic(12);
+ String nestedFieldName = secure().nextAlphabetic(11);
+ String value = secure().nextAlphabetic(12);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(null, nestedFieldName, value))
.isInstanceOf(NullPointerException.class)
@Test
public void constructor_fails_with_NPE_if_nestedFieldName_is_null() {
- String fieldName = randomAlphabetic(10);
- String value = randomAlphabetic(12);
+ String fieldName = secure().nextAlphabetic(10);
+ String value = secure().nextAlphabetic(12);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, null, value))
.isInstanceOf(NullPointerException.class)
@Test
public void constructor_fails_with_NPE_if_value_is_null() {
- String fieldName = randomAlphabetic(10);
- String nestedFieldName = randomAlphabetic(11);
+ String fieldName = secure().nextAlphabetic(10);
+ String nestedFieldName = secure().nextAlphabetic(11);
assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, nestedFieldName, null))
.isInstanceOf(NullPointerException.class)
@Test
public void verify_getters() {
- String fieldName = randomAlphabetic(10);
- String nestedFieldName = randomAlphabetic(11);
+ String fieldName = secure().nextAlphabetic(10);
+ String nestedFieldName = secure().nextAlphabetic(11);
Object value = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
@Test
public void verify_equals() {
- String fieldName = randomAlphabetic(10);
- String nestedFieldName = randomAlphabetic(11);
+ String fieldName = secure().nextAlphabetic(10);
+ String nestedFieldName = secure().nextAlphabetic(11);
Object value = new Object();
- String fieldName2 = randomAlphabetic(12);
- String nestedFieldName2 = randomAlphabetic(13);
+ String fieldName2 = secure().nextAlphabetic(12);
+ String nestedFieldName2 = secure().nextAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
@Test
public void verify_hashcode() {
- String fieldName = randomAlphabetic(10);
- String nestedFieldName = randomAlphabetic(11);
+ String fieldName = secure().nextAlphabetic(10);
+ String nestedFieldName = secure().nextAlphabetic(11);
Object value = new Object();
- String fieldName2 = randomAlphabetic(12);
- String nestedFieldName2 = randomAlphabetic(13);
+ String fieldName2 = secure().nextAlphabetic(12);
+ String nestedFieldName2 = secure().nextAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
@Test
public void verify_intersect() {
- String fieldName = randomAlphabetic(10);
- String nestedFieldName = randomAlphabetic(11);
+ String fieldName = secure().nextAlphabetic(10);
+ String nestedFieldName = secure().nextAlphabetic(11);
Object value = new Object();
- String fieldName2 = randomAlphabetic(12);
- String nestedFieldName2 = randomAlphabetic(13);
+ String fieldName2 = secure().nextAlphabetic(12);
+ String nestedFieldName2 = secure().nextAlphabetic(13);
Object value2 = new Object();
NestedFieldFilterScope<Object> underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value);
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
@UseDataProvider("notOneLevelDeepPaths")
public void constructor_supports_nestedFieldPath_only_one_level_deep(String unsupportedPath) {
- String value = randomAlphabetic(7);
+ String value = secure().nextAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, sticky))
@Test
@UseDataProvider("emptyFieldNames")
public void constructor_fails_with_IAE_if_empty_field_name(String unsupportedPath, List<String> expectedParsedFieldNames) {
- String value = randomAlphabetic(7);
+ String value = secure().nextAlphabetic(7);
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, true))
.isInstanceOf(IllegalArgumentException.class)
@DataProvider
public static Object[][] emptyFieldNames() {
- String str1 = randomAlphabetic(6);
+ String str1 = secure().nextAlphabetic(6);
return new Object[][] {
{".", emptyList()},
{" . ", emptyList()},
@Test
public void constructor_parses_nested_field_path() {
- String fieldName = randomAlphabetic(5);
- String nestedFieldName = randomAlphabetic(6);
- String value = randomAlphabetic(7);
+ String fieldName = secure().nextAlphabetic(5);
+ String nestedFieldName = secure().nextAlphabetic(6);
+ String value = secure().nextAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
NestedFieldTopAggregationDefinition<String> underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky);
@Test
public void constructor_fails_with_NPE_if_nestedFieldPath_is_null() {
- String value = randomAlphabetic(7);
+ String value = secure().nextAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(null, value, sticky))
@Test
public void constructor_fails_with_NPE_if_value_is_null() {
- String value = randomAlphabetic(7);
+ String value = secure().nextAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(value, null, sticky))
@Test
public void getFilterScope_always_returns_the_same_instance() {
- String fieldName = randomAlphabetic(5);
- String nestedFieldName = randomAlphabetic(6);
- String value = randomAlphabetic(7);
+ String fieldName = secure().nextAlphabetic(5);
+ String nestedFieldName = secure().nextAlphabetic(6);
+ String value = secure().nextAlphabetic(7);
boolean sticky = RANDOM.nextBoolean();
NestedFieldTopAggregationDefinition<String> underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky);
import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope;
import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void getFieldName() {
- String fieldName = randomAlphabetic(12);
+ String fieldName = secure().nextAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName);
assertThat(underTest.getFieldName()).isEqualTo(fieldName);
@Test
public void verify_equals() {
- String fieldName1 = randomAlphabetic(11);
- String fieldName2 = randomAlphabetic(12);
+ String fieldName1 = secure().nextAlphabetic(11);
+ String fieldName2 = secure().nextAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest)
@Test
public void verify_hashcode() {
- String fieldName1 = randomAlphabetic(11);
- String fieldName2 = randomAlphabetic(12);
+ String fieldName1 = secure().nextAlphabetic(11);
+ String fieldName2 = secure().nextAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest.hashCode())
@Test
public void verify_intersect() {
- String fieldName1 = randomAlphabetic(11);
- String fieldName2 = randomAlphabetic(12);
+ String fieldName1 = secure().nextAlphabetic(11);
+ String fieldName2 = secure().nextAlphabetic(12);
SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1);
assertThat(underTest.intersect(underTest)).isTrue();
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void getters() {
- String fieldName = RandomStringUtils.randomAlphabetic(12);
+ String fieldName = RandomStringUtils.secure().nextAlphabetic(12);
boolean sticky = new Random().nextBoolean();
SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
@Test
public void getFilterScope_always_returns_the_same_instance() {
- String fieldName = randomAlphabetic(12);
+ String fieldName = secure().nextAlphabetic(12);
boolean sticky = RANDOM.nextBoolean();
SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky);
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.es.searchrequest.TopAggregationHelperTest.DEFAULT_BUCKET_SIZE;
@Test
public void buildTermsAggregation_adds_term_subaggregation_with_minDoc_1_and_default_sort() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
@Test
public void buildTermsAggregation_adds_custom_order_from_constructor() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
TermsAggregationBuilder agg = underTestWithCustomsSubAggAndOrder.buildTermsAggregation(aggName, topAggregation, null);
@Test
public void buildTermsAggregation_adds_custom_sub_agg_from_constructor() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
@Test
public void buildTermsAggregation_adds_custom_size_if_TermTopAggregation_specifies_one() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
int customSize = 1 + new Random().nextInt(400);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
@Test
public void buildSelectedItemsAggregation_returns_empty_if_no_selected_item() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
@Test
public void buildSelectedItemsAggregation_does_not_add_custom_order_from_constructor() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
String[] selected = randomNonEmptySelected();
@Test
public void buildSelectedItemsAggregation_adds_custom_sub_agg_from_constructor() {
- String aggName = randomAlphabetic(10);
+ String aggName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
String[] selected = randomNonEmptySelected();
import org.elasticsearch.search.aggregations.metrics.MinAggregationBuilder;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12))
.mapToObj(i -> AggregationBuilders.min("subAgg_" + i))
.toArray(AggregationBuilder[]::new);
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
AggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> Arrays.stream(subAggs).forEach(t::subAggregation));
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation,
NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
@Test
public void buildTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() {
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
MinAggregationBuilder subAggregation = AggregationBuilders.min("donut");
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation));
@Test
public void buildTermTopAggregation_adds_term_subaggregation_from_subAggregationHelper() {
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12))
.mapToObj(i -> AggregationBuilders.min("subAgg_" + i))
.toArray(AggregationBuilder[]::new);
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
AggregationBuilder[] allSubAggs = Stream.concat(Arrays.stream(subAggs), Stream.of(termSubAgg)).toArray(AggregationBuilder[]::new);
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter));
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
BoolQueryBuilder otherFilter = boolQuery();
when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty());
when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter));
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo");
when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg);
@Test
public void buildTermTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() {
- String topAggregationName = randomAlphabetic(10);
+ String topAggregationName = secure().nextAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false);
BoolQueryBuilder computerFilter = boolQuery();
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.mock;
@DataProvider
public static Object[][] userOrAnalysisChange() {
- User changeAuthor = new User(randomAlphabetic(12), randomAlphabetic(10), randomAlphabetic(11));
+ User changeAuthor = new User(secure().nextAlphabetic(12), secure().nextAlphabetic(10), secure().nextAlphabetic(11));
return new Object[][] {
{new AnalysisChange(new Random().nextLong())},
{new UserChange(new Random().nextLong(), changeAuthor)},
}
private static Project newProject() {
- String base = randomAlphabetic(6);
+ String base = secure().nextAlphabetic(6);
return newProject(base);
}
}
private static Rule newRule() {
- return newRandomNotAHotspotRule(randomAlphabetic(5));
+ return newRandomNotAHotspotRule(secure().nextAlphabetic(5));
}
private static Set<IssuesChangesNotification> randomSetOfNotifications(@Nullable String projectKey, @Nullable String assignee, @Nullable String changeAuthor) {
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
}
private void format_set_html_message_with_footer(Change change, String issueStatus, Function<HtmlParagraphAssert, HtmlListAssert> skipContent, RuleType ruleType) {
- String wordingNotification = randomAlphabetic(20);
- String host = randomAlphabetic(15);
+ String wordingNotification = secure().nextAlphabetic(20);
+ String host = secure().nextAlphabetic(15);
when(i18n.message(Locale.ENGLISH, "notification.dispatcher.ChangesOnMyIssue", "notification.dispatcher.ChangesOnMyIssue"))
.thenReturn(wordingNotification);
when(emailSettings.getServerBaseURL()).thenReturn(host);
@Test
public void formats_returns_html_message_for_single_issue_on_master_when_analysis_change() {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
AnalysisChange analysisChange = newAnalysisChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
public void user_input_content_should_be_html_escape() {
Project project = new Project.Builder("uuid").setProjectName("</projectName>").setKey("project_key").build();
String ruleName = "</RandomRule>";
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
@Test
public void formats_returns_html_message_for_single_issue_on_master_when_user_change() {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
UserChange userChange = newUserChange();
when(emailSettings.getServerBaseURL()).thenReturn(host);
@Test
public void formats_returns_html_message_for_single_issue_on_branch_when_analysis_change() {
- String branchName = randomAlphabetic(6);
+ String branchName = secure().nextAlphabetic(6);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
AnalysisChange analysisChange = newAnalysisChange();
@Test
public void formats_returns_html_message_for_single_issue_on_branch_when_user_change() {
- String branchName = randomAlphabetic(6);
+ String branchName = secure().nextAlphabetic(6);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded());
UserChange userChange = newUserChange();
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_analysis_change() {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
String issueStatus = randomValidStatus();
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_user_change() {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_analysis_change() {
- String branchName = randomAlphabetic(19);
+ String branchName = secure().nextAlphabetic(19);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded());
String status = randomValidStatus();
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
@Test
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_user_change() {
- String branchName = randomAlphabetic(19);
+ String branchName = secure().nextAlphabetic(19);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule))
Project project2 = newProject("B");
Project project2Branch1 = newBranch("B", "a");
Project project3 = newProject("C");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3)
- .map(project -> newChangedIssue("issue_" + project.getUuid(), randomValidStatus(), project, newRule(randomAlphabetic(2), randomRuleTypeHotspotExcluded())))
+ .map(project -> newChangedIssue("issue_" + project.getUuid(), randomValidStatus(), project, newRule(secure().nextAlphabetic(2), randomRuleTypeHotspotExcluded())))
.collect(toList());
Collections.shuffle(changedIssues);
UserChange userChange = newUserChange();
Rule rule3 = newRandomNotAHotspotRule("b");
Rule rule4 = newRandomNotAHotspotRule("X");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
String issueStatus = randomValidStatus();
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), issueStatus, project, rule))
Rule hotspot3 = newSecurityHotspotRule("N");
Rule hotspot4 = newSecurityHotspotRule("M");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4, hotspot1, hotspot2, hotspot3, hotspot4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), randomValidStatus(), project, rule))
.collect(toList());
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
String issueStatusClosed = STATUS_CLOSED;
String otherIssueStatus = STATUS_RESOLVED;
Rule hotspot2 = newSecurityHotspotRule("h2");
String status = randomValidStatus();
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, status, project1, rule1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, status, project1, rule2)),
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule;
@Test
public void key_is_ChangesOnMyIssues() {
ChangesOnMyIssuesNotification underTest = new ChangesOnMyIssuesNotification(
- new UserChange(new Random().nextLong(), new User(randomAlphabetic(2), randomAlphabetic(3), randomAlphabetic(4))),
+ new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(2), secure().nextAlphabetic(3), secure().nextAlphabetic(4))),
ImmutableSet.of());
assertThat(underTest.getType()).isEqualTo("ChangesOnMyIssues");
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class EmailMessageTest {
@Test
public void setHtmlMessage_sets_message_and_html_to_true() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
underTest.setHtmlMessage(message);
@Test
public void setPlainTextMessage_sets_message_and_html_to_false() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
underTest.setPlainTextMessage(message);
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
@UseDataProvider("FPorWontFixResolutionWithCorrespondingIssueStatus")
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_FPorWontFix_notifications(String newResolution,
IssueStatus newIssueStatus) {
- Project projectKey1 = newProject(randomAlphabetic(4));
- Project projectKey2 = newProject(randomAlphabetic(5));
- Project projectKey3 = newProject(randomAlphabetic(6));
- Project projectKey4 = newProject(randomAlphabetic(7));
+ Project projectKey1 = newProject(secure().nextAlphabetic(4));
+ Project projectKey2 = newProject(secure().nextAlphabetic(5));
+ Project projectKey3 = newProject(secure().nextAlphabetic(6));
+ Project projectKey4 = newProject(secure().nextAlphabetic(7));
Change changeMock = mock(Change.class);
// some notifications with some issues on project1
Stream<IssuesChangesNotificationBuilder> project1Notifications = IntStream.range(0, 5)
@Test
@UseDataProvider("FPorWontFixResolutionWithCorrespondingIssueStatus")
public void deliver_does_not_send_email_request_for_notifications_a_subscriber_is_the_changeAuthor_of(String newResolution, IssueStatus newIssueStatus) {
- Project project = newProject(randomAlphabetic(5));
+ Project project = newProject(secure().nextAlphabetic(5));
User subscriber1 = newUser("subscriber1");
User subscriber2 = newUser("subscriber2");
User subscriber3 = newUser("subscriber3");
return IntStream.range(0, 5)
.mapToObj(i -> {
ChangedIssue.Builder builder = new ChangedIssue.Builder("key_" + i)
- .setAssignee(new User(randomAlphabetic(3), randomAlphabetic(4), randomAlphabetic(5)))
- .setNewStatus(randomAlphabetic(12))
- .setRule(newRandomNotAHotspotRule(randomAlphabetic(8)))
- .setProject(new Project.Builder(randomAlphabetic(9))
- .setKey(randomAlphabetic(10))
- .setProjectName(randomAlphabetic(11))
+ .setAssignee(new User(secure().nextAlphabetic(3), secure().nextAlphabetic(4), secure().nextAlphabetic(5)))
+ .setNewStatus(secure().nextAlphabetic(12))
+ .setRule(newRandomNotAHotspotRule(secure().nextAlphabetic(8)))
+ .setProject(new Project.Builder(secure().nextAlphabetic(9))
+ .setKey(secure().nextAlphabetic(10))
+ .setProjectName(secure().nextAlphabetic(11))
.build());
consumer.accept(builder);
return builder.build();
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void format_sets_from_to_name_of_author_change_when_available() {
- UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), randomAlphabetic(7)));
+ UserChange change = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), secure().nextAlphabetic(7)));
EmailMessage emailMessage = underTest.format(new FPOrAcceptedNotification(change, Collections.emptySet(), ACCEPTED));
assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getName().get());
@Test
public void format_sets_from_to_login_of_author_change_when_name_is_not_available() {
- UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), null));
+ UserChange change = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), null));
EmailMessage emailMessage = underTest.format(new FPOrAcceptedNotification(change, Collections.emptySet(), ACCEPTED));
assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getLogin());
}
public void formats_returns_html_message_with_only_footer_and_header_when_no_issue(Change change, FpPrAccepted fpPrAccepted, String fpOrWontFixLabel) {
- String wordingNotification = randomAlphabetic(20);
- String host = randomAlphabetic(15);
+ String wordingNotification = secure().nextAlphabetic(20);
+ String host = secure().nextAlphabetic(15);
when(i18n.message(Locale.ENGLISH, "notification.dispatcher.NewFalsePositiveIssue", "notification.dispatcher.NewFalsePositiveIssue"))
.thenReturn(wordingNotification);
when(emailSettings.getServerBaseURL()).thenReturn(host);
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_issue_on_master(Change change, FpPrAccepted fpPrAccepted) {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, randomRuleTypeHotspotExcluded());
when(emailSettings.getServerBaseURL()).thenReturn(host);
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_hotspot_on_master(Change change, FpPrAccepted fpPrAccepted) {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, SECURITY_HOTSPOT);
when(emailSettings.getServerBaseURL()).thenReturn(host);
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_issue_on_branch(Change change, FpPrAccepted fpPrAccepted) {
- String branchName = randomAlphabetic(6);
+ String branchName = secure().nextAlphabetic(6);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, randomRuleTypeHotspotExcluded());
when(emailSettings.getServerBaseURL()).thenReturn(host);
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_single_hotspot_on_branch(Change change, FpPrAccepted fpPrAccepted) {
- String branchName = randomAlphabetic(6);
+ String branchName = secure().nextAlphabetic(6);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
String key = "key";
ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, SECURITY_HOTSPOT);
when(emailSettings.getServerBaseURL()).thenReturn(host);
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master(Change change, FpPrAccepted fpPrAccepted) {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_master(Change change, FpPrAccepted fpPrAccepted) {
Project project = newProject("1");
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newSecurityHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch(Change change, FpPrAccepted fpPrAccepted) {
- String branchName = randomAlphabetic(19);
+ String branchName = secure().nextAlphabetic(19);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newRandomNotAHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
@Test
@UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange")
public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_branch(Change change, FpPrAccepted fpPrAccepted) {
- String branchName = randomAlphabetic(19);
+ String branchName = secure().nextAlphabetic(19);
Project project = newBranch("1", branchName);
- String ruleName = randomAlphabetic(8);
- String host = randomAlphabetic(15);
+ String ruleName = secure().nextAlphabetic(8);
+ String host = secure().nextAlphabetic(15);
Rule rule = newSecurityHotspotRule(ruleName);
List<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(5))
.mapToObj(i -> newChangedIssue("issue_" + i, project, rule))
Project project2 = newProject("B");
Project project2Branch1 = newBranch("B", "a");
Project project3 = newProject("C");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3)
- .map(project -> newChangedIssue("issue_" + project.getUuid(), project, newRandomNotAHotspotRule(randomAlphabetic(2))))
+ .map(project -> newChangedIssue("issue_" + project.getUuid(), project, newRandomNotAHotspotRule(secure().nextAlphabetic(2))))
.collect(toList());
Collections.shuffle(changedIssues);
when(emailSettings.getServerBaseURL()).thenReturn(host);
Rule rule2 = newRandomNotAHotspotRule("a");
Rule rule3 = newRandomNotAHotspotRule("b");
Rule rule4 = newRandomNotAHotspotRule("X");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(rule1, rule2, rule3, rule4)
.map(rule -> newChangedIssue("issue_" + rule.getName(), project, rule))
.collect(toList());
Project project2Branch = newBranch("V", "AB");
Rule rule1 = newRandomNotAHotspotRule("1");
Rule rule2 = newRandomNotAHotspotRule("a");
- String host = randomAlphabetic(15);
+ String host = secure().nextAlphabetic(15);
List<ChangedIssue> changedIssues = Stream.of(
IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, project1, rule1)),
IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, project1, rule2)),
@DataProvider
public static Object[][] userOrAnalysisChange() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
- UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6),
- new Random().nextBoolean() ? null : randomAlphabetic(7)));
+ UserChange userChange = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6),
+ new Random().nextBoolean() ? null : secure().nextAlphabetic(7)));
return new Object[][] {
{analysisChange},
{userChange}
@DataProvider
public static Object[][] fpOrWontFixValuesByUserOrAnalysisChange() {
AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong());
- UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6),
- new Random().nextBoolean() ? null : randomAlphabetic(7)));
+ UserChange userChange = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6),
+ new Random().nextBoolean() ? null : secure().nextAlphabetic(7)));
return new Object[][] {
{analysisChange, FP},
{analysisChange, ACCEPTED},
private static ChangedIssue newChangedIssue(String key, Project project, Rule rule) {
return new ChangedIssue.Builder(key)
- .setNewStatus(randomAlphabetic(19))
+ .setNewStatus(secure().nextAlphabetic(19))
.setProject(project)
.setRule(rule)
.build();
}
private static Rule newRule(String ruleName, RuleType ruleType) {
- return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName);
+ return new Rule(RuleKey.of(secure().nextAlphabetic(6), secure().nextAlphabetic(7)), ruleType, ruleName);
}
private static Project newProject(String uuid) {
import static com.google.common.collect.ImmutableSet.of;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public void deliver_has_no_effect_if_no_notification_has_assignee() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<MyNewIssuesNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
- .mapToObj(i -> newNotification(randomAlphabetic(5 + i), null))
+ .mapToObj(i -> newNotification(secure().nextAlphabetic(5 + i), null))
.collect(toSet());
int deliver = underTest.deliver(notifications);
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_assignee_to_MyNewIssue_notifications() {
- String projectKey = randomAlphabetic(12);
- String assignee = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(12);
+ String assignee = secure().nextAlphabetic(10);
MyNewIssuesNotification notification = newNotification(projectKey, assignee);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, of(assignee), ALL_MUST_HAVE_ROLE_USER))
@Test
public void deliver_ignores_notification_without_projectKey() {
- String projectKey = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(10);
Set<MyNewIssuesNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
- .mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i)))
+ .mapToObj(i -> newNotification(projectKey, secure().nextAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
- .mapToObj(i -> newNotification(null, randomAlphabetic(11 + i)))
+ .mapToObj(i -> newNotification(null, secure().nextAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noProjectKeyNoAssignee = randomSetOfNotifications(null, null);
Set<EmailRecipient> authorizedRecipients = withProjectKey.stream()
@Test
public void deliver_ignores_notification_without_assignee() {
- String projectKey = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(10);
Set<MyNewIssuesNotification> withAssignee = IntStream.range(0, 1 + new Random().nextInt(5))
- .mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i)))
+ .mapToObj(i -> newNotification(projectKey, secure().nextAlphabetic(11 + i)))
.collect(toSet());
Set<MyNewIssuesNotification> noAssignee = randomSetOfNotifications(projectKey, null);
Set<MyNewIssuesNotification> noProjectKeyNoAssignee = randomSetOfNotifications(null, null);
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_MyNewIssue_notifications() {
- String projectKey1 = randomAlphabetic(10);
- String assignee1 = randomAlphabetic(11);
- String projectKey2 = randomAlphabetic(12);
- String assignee2 = randomAlphabetic(13);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String assignee1 = secure().nextAlphabetic(11);
+ String projectKey2 = secure().nextAlphabetic(12);
+ String assignee2 = secure().nextAlphabetic(13);
Set<MyNewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1, assignee1);
Set<MyNewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2, assignee2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
@Test
public void deliver_ignores_notifications_which_assignee_has_no_subscribed_to_MyNewIssue_notifications() {
- String projectKey = randomAlphabetic(5);
- String assignee1 = randomAlphabetic(6);
- String assignee2 = randomAlphabetic(7);
+ String projectKey = secure().nextAlphabetic(5);
+ String assignee1 = secure().nextAlphabetic(6);
+ String assignee2 = secure().nextAlphabetic(7);
Set<String> assignees = of(assignee1, assignee2);
// assignee1 is not authorized
Set<MyNewIssuesNotification> assignee1Notifications = randomSetOfNotifications(projectKey, assignee1);
@Test
public void deliver_returns_sum_of_delivery_counts_when_multiple_projects() {
- String projectKey1 = randomAlphabetic(5);
- String projectKey2 = randomAlphabetic(6);
- String projectKey3 = randomAlphabetic(7);
- String assignee1 = randomAlphabetic(8);
- String assignee2 = randomAlphabetic(9);
- String assignee3 = randomAlphabetic(10);
+ String projectKey1 = secure().nextAlphabetic(5);
+ String projectKey2 = secure().nextAlphabetic(6);
+ String projectKey3 = secure().nextAlphabetic(7);
+ String assignee1 = secure().nextAlphabetic(8);
+ String assignee2 = secure().nextAlphabetic(9);
+ String assignee3 = secure().nextAlphabetic(10);
// assignee1 has subscribed to project1 only, no notification on project3
Set<MyNewIssuesNotification> assignee1Project1 = randomSetOfNotifications(projectKey1, assignee1);
Set<MyNewIssuesNotification> assignee1Project2 = randomSetOfNotifications(projectKey2, assignee1);
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_NewIssue_notifications() {
- String projectKey = randomAlphabetic(12);
+ String projectKey = secure().nextAlphabetic(12);
NewIssuesNotification notification = newNotification(projectKey);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
@Test
public void deliver_ignores_notification_without_projectKey() {
- String projectKey = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(10);
Set<NewIssuesNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(toSet());
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_NewIssue_notifications() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<NewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<NewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
@Test
public void deliver_send_notifications_to_all_subscribers_of_all_projects() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<NewIssuesNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<NewIssuesNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.notification.NewIssuesStatistics.Metric;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
class NewIssuesStatisticsTest {
@Test
void add_counts_issues_on_current_analysis_globally_and_per_assignee() {
- String assignee = randomAlphanumeric(10);
+ String assignee = secure().nextAlphanumeric(10);
IntStream.range(0, 10)
.mapToObj(i -> new DefaultIssue().setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
@Test
void add_counts_issues_off_current_analysis_globally_and_per_assignee() {
- String assignee = randomAlphanumeric(10);
+ String assignee = secure().nextAlphanumeric(10);
IntStream.range(0, 10)
.mapToObj(i -> new DefaultIssue().setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
@Test
void add_counts_issue_per_component_on_current_analysis_globally_and_per_assignee() {
- List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
componentUuids.stream()
.map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
@Test
void add_counts_issue_per_component_off_current_analysis_globally_and_per_assignee() {
- List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ List<String> componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
componentUuids.stream()
.map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
@Test
void add_does_not_count_component_if_null_neither_globally_nor_per_assignee() {
- String assignee = randomAlphanumeric(10);
+ String assignee = secure().nextAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT);
@Test
void add_counts_issue_per_ruleKey_on_current_analysis_globally_and_per_assignee() {
- String repository = randomAlphanumeric(3);
- List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ String repository = secure().nextAlphanumeric(3);
+ List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
ruleKeys.stream()
.map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
@Test
void add_counts_issue_per_ruleKey_off_current_analysis_globally_and_per_assignee() {
- String repository = randomAlphanumeric(3);
- List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ String repository = secure().nextAlphanumeric(3);
+ List<String> ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
ruleKeys.stream()
.map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
@Test
void add_does_not_count_ruleKey_if_null_neither_globally_nor_per_assignee() {
- String assignee = randomAlphanumeric(10);
+ String assignee = secure().nextAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE);
@Test
void add_counts_issue_per_assignee_on_current_analysis_globally_and_per_assignee() {
- List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
+ List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
assignees.stream()
.map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(true))
.forEach(underTest::add);
@Test
void add_counts_issue_per_assignee_off_current_analysis_globally_and_per_assignee() {
- List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
+ List<String> assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
assignees.stream()
.map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(false))
.forEach(underTest::add);
@Test
void add_counts_issue_per_tags_on_current_analysis_globally_and_per_assignee() {
- List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(true));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
@Test
void add_counts_issue_per_tags_off_current_analysis_globally_and_per_assignee() {
- List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList();
- String assignee = randomAlphanumeric(10);
+ List<String> tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList();
+ String assignee = secure().nextAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(false));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
@Test
void add_does_not_count_tags_if_empty_neither_globally_nor_per_assignee() {
- String assignee = randomAlphanumeric(10);
+ String assignee = secure().nextAlphanumeric(10);
underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(Collections.emptyList()).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()));
DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG);
@Test
void verify_toString() {
- String componentUuid = randomAlphanumeric(2);
- String tag = randomAlphanumeric(3);
- String assignee = randomAlphanumeric(4);
+ String componentUuid = secure().nextAlphanumeric(2);
+ String tag = secure().nextAlphanumeric(3);
+ String assignee = secure().nextAlphanumeric(4);
int effort = 10 + new Random().nextInt(5);
- RuleKey ruleKey = RuleKey.of(randomAlphanumeric(5), randomAlphanumeric(6));
+ RuleKey ruleKey = RuleKey.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(6));
underTest.add(new DefaultIssue()
.setType(randomRuleTypeExceptHotspot)
.setComponentUuid(componentUuid)
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.server.issue.IssueFieldsSetter;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.issue.DefaultTransitions.RESET_AS_TO_REVIEW;
import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_ACKNOWLEDGED;
return Stream.of(
Issue.RESOLUTIONS.stream(),
Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(),
- Stream.of(randomAlphabetic(12), null))
+ Stream.of(secure().nextAlphabetic(12), null))
.flatMap(t -> t)
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
return Stream.of(
Issue.RESOLUTIONS.stream(),
Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(),
- Stream.of(randomAlphabetic(12)))
+ Stream.of(secure().nextAlphabetic(12)))
.flatMap(t -> t)
.filter(t -> !RESOLUTION_TYPES.contains(t))
.map(t -> new Object[] {t})
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20);
+ private final String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(20);
private LogbackHelper logbackHelper = spy(new LogbackHelper());
private MapSettings settings = new MapSettings();
private final ServerProcessLogging serverProcessLogging = mock(ServerProcessLogging.class);
import org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject;
import static com.google.common.collect.Sets.newHashSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@Test
public void findSubscribedEmailRecipients_fails_with_NPE_if_projectKey_is_null() {
- String dispatcherKey = randomAlphabetic(12);
+ String dispatcherKey = secure().nextAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
@Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_projectKey_is_null() {
- String dispatcherKey = randomAlphabetic(12);
+ String dispatcherKey = secure().nextAlphabetic(12);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
@Test
public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_logins_is_null() {
- String dispatcherKey = randomAlphabetic(12);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String projectKey = secure().nextAlphabetic(6);
assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER))
.isInstanceOf(NullPointerException.class)
@Test
public void findSubscribedEmailRecipients_with_logins_returns_empty_if_login_set_is_empty() {
- String dispatcherKey = randomAlphabetic(12);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String projectKey = secure().nextAlphabetic(6);
Set<EmailRecipient> recipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER);
@Test
public void findSubscribedEmailRecipients_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(Collections.emptySet());
@Test
public void findSubscribedEmailRecipients_with_logins_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<String> logins = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "login_" + i)
.collect(Collectors.toSet());
@Test
public void findSubscribedEmailRecipients_applies_distinct_permission_filtering_global_or_project_subscribers() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey))
.thenReturn(
newHashSet(EmailSubscriberDto.create("user1", false, "user1@foo"), EmailSubscriberDto.create("user3", false, "user3@foo"),
@Test
public void findSubscribedEmailRecipients_with_logins_applies_distinct_permission_filtering_global_or_project_subscribers() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<String> logins = ImmutableSet.of("user1", "user2", "user3");
when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins))
.thenReturn(
@Test
public void findSubscribedEmailRecipients_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
@Test
public void findSubscribedEmailRecipients_with_logins_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
@Test
public void findSubscribedEmailRecipients_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
@Test
public void findSubscribedEmailRecipients_with_logins_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() {
- String dispatcherKey = randomAlphabetic(12);
- String globalPermission = randomAlphanumeric(4);
- String projectPermission = randomAlphanumeric(5);
- String projectKey = randomAlphabetic(6);
+ String dispatcherKey = secure().nextAlphabetic(12);
+ String globalPermission = secure().nextAlphanumeric(4);
+ String projectPermission = secure().nextAlphanumeric(5);
+ String projectKey = secure().nextAlphabetic(6);
Set<EmailSubscriberDto> subscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com"))
.collect(Collectors.toSet());
import org.junit.Test;
import org.sonar.server.notification.NotificationManager.EmailRecipient;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void constructor_fails_with_NPE_if_login_is_null() {
- String email = randomAlphabetic(12);
+ String email = secure().nextAlphabetic(12);
assertThatThrownBy(() -> new EmailRecipient(null, email))
.isInstanceOf(NullPointerException.class)
@Test
public void constructor_fails_with_NPE_if_email_is_null() {
- String login = randomAlphabetic(12);
+ String login = secure().nextAlphabetic(12);
assertThatThrownBy(() -> new EmailRecipient(login, null))
.isInstanceOf(NullPointerException.class)
@Test
public void equals_is_based_on_login_and_email() {
- String login = randomAlphabetic(11);
- String email = randomAlphabetic(12);
+ String login = secure().nextAlphabetic(11);
+ String email = secure().nextAlphabetic(12);
EmailRecipient underTest = new EmailRecipient(login, email);
assertThat(underTest)
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new EmailRecipient(email, login))
- .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email))
- .isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5)))
- .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6)));
+ .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), email))
+ .isNotEqualTo(new EmailRecipient(login, secure().nextAlphabetic(5)))
+ .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), secure().nextAlphabetic(6)));
}
@Test
public void hashcode_is_based_on_login_and_email() {
- String login = randomAlphabetic(11);
- String email = randomAlphabetic(12);
+ String login = secure().nextAlphabetic(11);
+ String email = secure().nextAlphabetic(12);
EmailRecipient underTest = new EmailRecipient(login, email);
assertThat(underTest.hashCode())
.isEqualTo(new EmailRecipient(login, email).hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new EmailRecipient(email, login).hashCode())
- .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email).hashCode())
- .isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5)).hashCode())
- .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6)).hashCode());
+ .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), email).hashCode())
+ .isNotEqualTo(new EmailRecipient(login, secure().nextAlphabetic(5)).hashCode())
+ .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), secure().nextAlphabetic(6)).hashCode());
}
@Test
public void verify_to_String() {
- String login = randomAlphabetic(11);
- String email = randomAlphabetic(12);
+ String login = secure().nextAlphabetic(11);
+ String email = secure().nextAlphabetic(12);
assertThat(new EmailRecipient(login, email)).hasToString("EmailRecipient{'" + login + "':'" + email + "'}");
}
import org.sonar.db.DbClient;
import org.sonar.db.property.PropertiesDao;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyCollection;
@Test
public void hasProjectSubscribersForType_returns_false_if_there_are_no_handler() {
- String projectUuid = randomAlphabetic(7);
+ String projectUuid = secure().nextAlphabetic(7);
NotificationService underTest = new NotificationService(dbClient);
assertThat(underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class))).isFalse();
@Test
public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_type() {
- String dispatcherKey1A = randomAlphabetic(5);
- String dispatcherKey1B = randomAlphabetic(6);
- String projectUuid = randomAlphabetic(7);
+ String dispatcherKey1A = secure().nextAlphabetic(5);
+ String dispatcherKey1B = secure().nextAlphabetic(6);
+ String projectUuid = secure().nextAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
@Test
public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_types() {
- String dispatcherKey1A = randomAlphabetic(5);
- String dispatcherKey1B = randomAlphabetic(6);
- String dispatcherKey2 = randomAlphabetic(7);
- String projectUuid = randomAlphabetic(8);
+ String dispatcherKey1A = secure().nextAlphabetic(5);
+ String dispatcherKey1B = secure().nextAlphabetic(6);
+ String dispatcherKey2 = secure().nextAlphabetic(7);
+ String projectUuid = secure().nextAlphabetic(8);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
@Test
public void hasProjectSubscribersForType_returns_false_if_set_is_empty() {
- String dispatcherKey1A = randomAlphabetic(5);
- String dispatcherKey1B = randomAlphabetic(6);
- String projectUuid = randomAlphabetic(7);
+ String dispatcherKey1A = secure().nextAlphabetic(5);
+ String dispatcherKey1B = secure().nextAlphabetic(6);
+ String projectUuid = secure().nextAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
@Test
public void hasProjectSubscribersForType_returns_false_for_type_which_have_no_handler() {
- String dispatcherKey1A = randomAlphabetic(5);
- String dispatcherKey1B = randomAlphabetic(6);
- String projectUuid = randomAlphabetic(7);
+ String dispatcherKey1A = secure().nextAlphabetic(5);
+ String dispatcherKey1B = secure().nextAlphabetic(6);
+ String projectUuid = secure().nextAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Fail.fail;
@Test
public void idOf_returns_argument_with_a_prefix() {
- String s = randomAlphabetic(12);
+ String s = secure().nextAlphabetic(12);
assertThat(AuthorizationDoc.idOf(s)).isEqualTo("auth_" + s);
}
public void projectUuidOf_returns_substring_if_starts_with_id_prefix() {
assertThat(AuthorizationDoc.entityUuidOf("auth_")).isEmpty();
- String id = randomAlphabetic(1 + new Random().nextInt(10));
+ String id = secure().nextAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf("auth_" + id)).isEqualTo(id);
}
@Test
public void projectUuidOf_returns_argument_if_does_not_starts_with_id_prefix() {
- String id = randomAlphabetic(1 + new Random().nextInt(10));
+ String id = secure().nextAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf(id)).isEqualTo(id);
assertThat(AuthorizationDoc.entityUuidOf("")).isEmpty();
}
@Test
public void fromDto_of_allowAnyone_is_false_and_no_user_nor_group() {
- IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
AuthorizationDoc doc = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), underTest);
@Test
public void fromDto_defines_userIds_and_groupIds_if_allowAnyone_is_false() {
- IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid);
@Test
public void fromDto_ignores_userIds_and_groupUuids_if_allowAnyone_is_true() {
- IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid);
underTest.allowAnyone();
@DataProvider
public static Object[][] dtos() {
- IndexPermissions allowAnyone = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions allowAnyone = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
allowAnyone.allowAnyone();
- IndexPermissions someUserIds = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions someUserIds = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someUserIds::addUserUuid);
- IndexPermissions someGroupUuids = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions someGroupUuids = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuids::addGroupUuid);
- IndexPermissions someGroupUuidAndUserIs = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
+ IndexPermissions someGroupUuidAndUserIs = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someGroupUuidAndUserIs::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuidAndUserIs::addGroupUuid);
return new Object[][] {
private final Level randomStatus = Level.values()[random.nextInt(Level.values().length)];
private final EvaluatedCondition.EvaluationStatus randomEvaluationStatus = EvaluatedCondition.EvaluationStatus.values()[random
.nextInt(EvaluatedCondition.EvaluationStatus.values().length)];
- private final String randomValue = random.nextBoolean() ? null : RandomStringUtils.randomAlphanumeric(3);
+ private final String randomValue = random.nextBoolean() ? null : RandomStringUtils.secure().nextAlphanumeric(3);
private EvaluatedQualityGate.Builder builder = newBuilder();
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_QGChange_notifications() {
- String projectKey = randomAlphabetic(12);
+ String projectKey = secure().nextAlphabetic(12);
QGChangeNotification notification = newNotification(projectKey);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
@Test
public void deliver_ignores_notification_without_projectKey() {
- String projectKey = randomAlphabetic(10);
+ String projectKey = secure().nextAlphabetic(10);
Set<QGChangeNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(toSet());
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_QGChange_notifications() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<QGChangeNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<QGChangeNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
@Test
public void deliver_send_notifications_to_all_subscribers_of_all_projects() {
- String projectKey1 = randomAlphabetic(10);
- String projectKey2 = randomAlphabetic(11);
+ String projectKey1 = secure().nextAlphabetic(10);
+ String projectKey2 = secure().nextAlphabetic(11);
Set<QGChangeNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<QGChangeNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void childSettings_should_retrieve_parent_settings() {
- String multipleValuesKey = randomAlphanumeric(19);
+ String multipleValuesKey = secure().nextAlphanumeric(19);
PropertyDefinition multipleValues = PropertyDefinition.builder(multipleValuesKey).multiValues(true).build();
MapSettings parent = new MapSettings(new PropertyDefinitions(System2.INSTANCE, Collections.singletonList(multipleValues)));
ChildSettings underTest = new ChildSettings(parent);
- parent.setProperty(randomAlphanumeric(10), randomAlphanumeric(20));
- parent.setProperty(randomAlphanumeric(11), RANDOM.nextLong());
- parent.setProperty(randomAlphanumeric(12), RANDOM.nextDouble());
- parent.setProperty(randomAlphanumeric(13), RANDOM.nextFloat());
- parent.setProperty(randomAlphanumeric(14), RANDOM.nextBoolean());
- parent.setProperty(randomAlphanumeric(15), RANDOM.nextInt(Integer.MAX_VALUE));
- parent.setProperty(randomAlphanumeric(16), new Date(RANDOM.nextInt()));
- parent.setProperty(randomAlphanumeric(17), new Date(RANDOM.nextInt()), true);
- parent.setProperty(randomAlphanumeric(18), new Date(RANDOM.nextInt()), false);
- parent.setProperty(multipleValuesKey, new String[] {randomAlphanumeric(10), randomAlphanumeric(20)});
+ parent.setProperty(secure().nextAlphanumeric(10), secure().nextAlphanumeric(20));
+ parent.setProperty(secure().nextAlphanumeric(11), RANDOM.nextLong());
+ parent.setProperty(secure().nextAlphanumeric(12), RANDOM.nextDouble());
+ parent.setProperty(secure().nextAlphanumeric(13), RANDOM.nextFloat());
+ parent.setProperty(secure().nextAlphanumeric(14), RANDOM.nextBoolean());
+ parent.setProperty(secure().nextAlphanumeric(15), RANDOM.nextInt(Integer.MAX_VALUE));
+ parent.setProperty(secure().nextAlphanumeric(16), new Date(RANDOM.nextInt()));
+ parent.setProperty(secure().nextAlphanumeric(17), new Date(RANDOM.nextInt()), true);
+ parent.setProperty(secure().nextAlphanumeric(18), new Date(RANDOM.nextInt()), false);
+ parent.setProperty(multipleValuesKey, new String[] {secure().nextAlphanumeric(10), secure().nextAlphanumeric(20)});
assertThat(underTest.getProperties()).isEqualTo(parent.getProperties());
}
@Test
public void set_will_throw_NPE_if_value_is_null() {
- assertThatThrownBy(() -> underTest.set(randomAlphanumeric(10), null))
+ assertThatThrownBy(() -> underTest.set(secure().nextAlphanumeric(10), null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
@Test
public void childSettings_override_parent() {
- String key = randomAlphanumeric(10);
- parent.setProperty(key, randomAlphanumeric(20));
- underTest.setProperty(key, randomAlphanumeric(10));
+ String key = secure().nextAlphanumeric(10);
+ parent.setProperty(key, secure().nextAlphanumeric(20));
+ underTest.setProperty(key, secure().nextAlphanumeric(10));
Optional<String> result = underTest.get(key);
assertThat(result).isPresent();
@Test
public void remove_should_not_throw_exception_if_key_is_not_present() {
- underTest.remove(randomAlphanumeric(90));
+ underTest.remove(secure().nextAlphanumeric(90));
}
@Test
public void remove_should_remove_value() {
- String key = randomAlphanumeric(10);
- String childValue = randomAlphanumeric(10);
+ String key = secure().nextAlphanumeric(10);
+ String childValue = secure().nextAlphanumeric(10);
underTest.set(key, childValue);
assertThat(underTest.get(key)).isEqualTo(Optional.of(childValue));
@Test
public void remove_should_retrieve_parent_value() {
- String key = randomAlphanumeric(10);
- String childValue = randomAlphanumeric(10);
- String parentValue = randomAlphanumeric(10);
+ String key = secure().nextAlphanumeric(10);
+ String childValue = secure().nextAlphanumeric(10);
+ String parentValue = secure().nextAlphanumeric(10);
parent.setProperty(key, parentValue);
underTest.set(key, childValue);
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static java.util.concurrent.TimeUnit.SECONDS;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.mockito.Mockito.doAnswer;
@Test
public void getProperties_return_properties_from_previous_thread_cache_if_DB_error_on_not_first_call() {
- String key = randomAlphanumeric(3);
- String value1 = randomAlphanumeric(4);
- String value2 = randomAlphanumeric(5);
+ String key = secure().nextAlphanumeric(3);
+ String value1 = secure().nextAlphanumeric(4);
+ String value2 = secure().nextAlphanumeric(5);
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
doAnswer(invocationOnMock -> ImmutableMap.of(key, value1))
public void get_returns_empty_if_DB_error_on_first_call_ever_out_of_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
doThrow(toBeThrown).when(settingLoaderMock).load(key);
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
public void get_returns_empty_if_DB_error_on_first_call_ever_in_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
doThrow(toBeThrown).when(settingLoaderMock).load(key);
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
underTest.load();
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.server.util.OkHttpClientProvider;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY;
@Test
public void post_payload_to_http_server() throws Exception {
- Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40),
+ Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, secure().nextAlphanumeric(40),
"my-webhook", server.url("/ping").toString(), null);
server.enqueue(new MockResponse().setBody("pong").setResponseCode(201));
@Test
public void sign_payload_if_secret_is_set() throws Exception {
- Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40),
+ Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, secure().nextAlphanumeric(40),
"my-webhook", server.url("/ping").toString(), "my_secret");
server.enqueue(new MockResponse().setBody("pong").setResponseCode(201));
@Test
public void silently_catch_error_when_external_server_does_not_answer() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null);
server.shutdown();
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
@Test
public void silently_catch_error_when_url_is_incorrect() {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", "this_is_not_an_url", null);
+ secure().nextAlphanumeric(40), "my-webhook", "this_is_not_an_url", null);
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
@Test
public void redirects_should_be_followed_with_POST_method() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", server.url("/redirect").toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", server.url("/redirect").toString(), null);
// /redirect redirects to /target
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target")));
public void credentials_are_propagated_to_POST_redirects() throws Exception {
HttpUrl url = server.url("/redirect").newBuilder().username("theLogin").password("thePassword").build();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url.toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", url.toString(), null);
// /redirect redirects to /target
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target")));
public void redirects_throws_ISE_if_header_Location_is_missing() {
HttpUrl url = server.url("/redirect");
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url.toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setResponseCode(307));
public void redirects_throws_ISE_if_header_Location_does_not_relate_to_a_supported_protocol() {
HttpUrl url = server.url("/redirect");
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url.toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", "ftp://foo"));
public void send_basic_authentication_header_if_url_contains_credentials() throws Exception {
HttpUrl url = server.url("/ping").newBuilder().username("theLogin").password("thePassword").build();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url.toString(), null);
+ secure().nextAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setBody("pong"));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
public void silently_catch_error_when_url_is_localhost(){
String url = server.url("/").toString();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url, null);
+ secure().nextAlphanumeric(40), "my-webhook", url, null);
WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD);
.thenReturn(ImmutableList.of(inetAddress));
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
- randomAlphanumeric(40), "my-webhook", url, null);
+ secure().nextAlphanumeric(40), "my-webhook", url, null);
WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD);
import org.sonar.server.issue.index.IssueDoc;
import org.sonar.server.issue.index.IssueScope;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
public class IssueDocTesting {
doc.setKey(Uuids.createFast());
doc.setRuleUuid(Uuids.createFast());
doc.setType(RuleType.CODE_SMELL);
- doc.setAssigneeUuid("assignee_uuid_" + randomAlphabetic(26));
- doc.setAuthorLogin("author_" + randomAlphabetic(5));
+ doc.setAssigneeUuid("assignee_uuid_" + secure().nextAlphabetic(26));
+ doc.setAuthorLogin("author_" + secure().nextAlphabetic(5));
doc.setScope(IssueScope.MAIN);
- doc.setLanguage("language_" + randomAlphabetic(5));
+ doc.setLanguage("language_" + secure().nextAlphabetic(5));
doc.setComponentUuid(Uuids.createFast());
- doc.setFilePath("filePath_" + randomAlphabetic(5));
- doc.setDirectoryPath("directory_" + randomAlphabetic(5));
+ doc.setFilePath("filePath_" + secure().nextAlphabetic(5));
+ doc.setDirectoryPath("directory_" + secure().nextAlphabetic(5));
doc.setProjectUuid(Uuids.createFast());
doc.setLine(RANDOM.nextInt(1_000) + 1);
doc.setStatus(STATUS_OPEN);
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
static ChangedIssue newChangedIssue(String key, Project project, Rule rule) {
return new ChangedIssue.Builder(key)
- .setNewStatus(randomAlphabetic(19))
+ .setNewStatus(secure().nextAlphabetic(19))
.setProject(project)
.setRule(rule)
.build();
}
static Rule newRule(String ruleName, RuleType ruleType) {
- return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName);
+ return new Rule(RuleKey.of(secure().nextAlphabetic(6), secure().nextAlphabetic(7)), ruleType, ruleName);
}
static Rule newRandomNotAHotspotRule(String ruleName) {
}
static UserChange newUserChange() {
- return new UserChange(new Random().nextLong(), new User(randomAlphabetic(4), randomAlphabetic(5), randomAlphabetic(6)));
+ return new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(4), secure().nextAlphabetic(5), secure().nextAlphabetic(6)));
}
static AnalysisChange newAnalysisChange() {
import org.sonar.updatecenter.common.Version;
import static java.util.Arrays.asList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.groups.Tuple.tuple;
@Test
void send_server_id_and_version() {
- String id = randomAlphanumeric(40);
- String version = randomAlphanumeric(10);
+ String id = secure().nextAlphanumeric(40);
+ String version = secure().nextAlphanumeric(10);
server.setId(id);
server.setVersion(version);
import java.util.Date;
import org.sonar.api.platform.Server;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
public class FakeServer extends Server {
private String id;
private String version;
public FakeServer() {
- this.id = randomAlphanumeric(20);
- this.version = randomAlphanumeric(10);
+ this.id = secure().nextAlphanumeric(20);
+ this.version = secure().nextAlphanumeric(10);
}
@Override
import org.sonar.server.util.DigestUtil;
import static java.util.stream.Collectors.joining;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
void writes_database() {
- String name = randomAlphabetic(12);
- String version = randomAlphabetic(10);
+ String name = secure().nextAlphabetic(12);
+ String version = secure().nextAlphabetic(10);
TelemetryData data = telemetryBuilder()
.setDatabase(new TelemetryData.Database(name, version))
.build();
@Test
void write_installation_version() {
- String installationVersion = randomAlphabetic(5);
+ String installationVersion = secure().nextAlphabetic(5);
TelemetryData data = telemetryBuilder()
.setInstallationVersion(installationVersion)
.build();
import org.sonar.db.rule.RuleTesting;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
@Test
public void findByKey_returns_null_when_repository_key_is_null() {
- assertThat(underTest.findByKey(null, randomAlphabetic(2))).isNull();
+ assertThat(underTest.findByKey(null, secure().nextAlphabetic(2))).isNull();
}
@Test
public void findByKey_returns_null_when_key_is_null() {
- assertThat(underTest.findByKey(randomAlphabetic(2), null)).isNull();
+ assertThat(underTest.findByKey(secure().nextAlphabetic(2), null)).isNull();
}
@Test
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase())))
.isNull();
- assertThat(underTest.find(RuleQuery.create().withRepositoryKey(randomAlphabetic(3))))
+ assertThat(underTest.find(RuleQuery.create().withRepositoryKey(secure().nextAlphabetic(3))))
.isNull();
}
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withKey(ruleKey.toLowerCase())))
.isNull();
- assertThat(underTest.find(RuleQuery.create().withKey(randomAlphabetic(3))))
+ assertThat(underTest.find(RuleQuery.create().withKey(secure().nextAlphabetic(3))))
.isNull();
}
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withConfigKey(configKey.toLowerCase())))
.isNull();
- assertThat(underTest.find(RuleQuery.create().withConfigKey(randomAlphabetic(3))))
+ assertThat(underTest.find(RuleQuery.create().withConfigKey(secure().nextAlphabetic(3))))
.isNull();
}
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase())))
.isEmpty();
- assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(randomAlphabetic(3))))
+ assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(secure().nextAlphabetic(3))))
.isEmpty();
}
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withKey(ruleKey.toLowerCase())))
.isEmpty();
- assertThat(underTest.findAll(RuleQuery.create().withKey(randomAlphabetic(3))))
+ assertThat(underTest.findAll(RuleQuery.create().withKey(secure().nextAlphabetic(3))))
.isEmpty();
}
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withConfigKey(configKey.toLowerCase())))
.isEmpty();
- assertThat(underTest.findAll(RuleQuery.create().withConfigKey(randomAlphabetic(3))))
+ assertThat(underTest.findAll(RuleQuery.create().withConfigKey(secure().nextAlphabetic(3))))
.isEmpty();
}
import java.util.Optional;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.sonar.server.exceptions.NotFoundException.checkFound;
public class NotFoundExceptionTest {
@Test
public void http_code_is_404() {
- NotFoundException underTest = new NotFoundException(randomAlphabetic(12));
+ NotFoundException underTest = new NotFoundException(secure().nextAlphabetic(12));
assertThat(underTest.httpCode()).isEqualTo(404);
}
@Test
public void message_is_constructor_argument() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
NotFoundException underTest = new NotFoundException(message);
assertThat(underTest.getMessage()).isEqualTo(message);
@Test
public void checkFound_type_throws_NotFoundException_if_parameter_is_null() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> checkFound(null, message))
.withMessage(message);
@Test
public void checkFound_return_parameter_if_parameter_is_not_null() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
Object o = new Object();
assertThat(checkFound(o, message)).isSameAs(o);
@Test
public void checkFoundWithOptional_throws_NotFoundException_if_empty() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> checkFoundWithOptional(Optional.empty(), message))
.withMessage(message);
@Test
public void checkFoundWithOptional_return_content_of_if_not_empty() {
- String message = randomAlphabetic(12);
+ String message = secure().nextAlphabetic(12);
Object o = new Object();
assertThat(checkFoundWithOptional(Optional.of(o), message)).isSameAs(o);
import org.sonar.core.platform.PluginInfo;
import org.sonar.updatecenter.common.Plugin;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void isEditionBundled_on_Plugin_returns_false_for_SonarSource_and_non_commercial_license() {
- Plugin plugin = newPlugin(randomizeCase("SonarSource"), randomAlphanumeric(3));
+ Plugin plugin = newPlugin(randomizeCase("SonarSource"), secure().nextAlphanumeric(3));
assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse();
}
@Test
public void isEditionBundled_on_Plugin_returns_false_for_license_SonarSource_and_non_SonarSource_organization() {
- Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("SonarSource"));
+ Plugin plugin = newPlugin(secure().nextAlphanumeric(3), randomizeCase("SonarSource"));
assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse();
}
@Test
public void isEditionBundled_on_Plugin_returns_false_for_license_Commercial_and_non_SonarSource_organization() {
- Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("Commercial"));
+ Plugin plugin = newPlugin(secure().nextAlphanumeric(3), randomizeCase("Commercial"));
assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse();
}
@Test
public void isEditionBundled_on_PluginInfo_returns_false_for_SonarSource_and_non_commercial_license() {
- PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomAlphanumeric(3));
+ PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), secure().nextAlphanumeric(3));
assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse();
}
@Test
public void isEditionBundled_on_PluginInfo_returns_false_for_license_SonarSource_and_non_SonarSource_organization() {
- PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("SonarSource"));
+ PluginInfo pluginInfo = newPluginInfo(secure().nextAlphanumeric(3), randomizeCase("SonarSource"));
assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse();
}
@Test
public void isEditionBundled_on_PluginInfo_returns_false_for_license_Commercial_and_non_SonarSource_organization() {
- PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("Commercial"));
+ PluginInfo pluginInfo = newPluginInfo(secure().nextAlphanumeric(3), randomizeCase("Commercial"));
assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse();
}
}
private PluginInfo newPluginInfo(String organization, String license) {
- PluginInfo pluginInfo = new PluginInfo(randomAlphanumeric(2));
+ PluginInfo pluginInfo = new PluginInfo(secure().nextAlphanumeric(2));
if (random.nextBoolean()) {
- pluginInfo.setName(randomAlphanumeric(3));
+ pluginInfo.setName(secure().nextAlphanumeric(3));
}
if (random.nextBoolean()) {
- pluginInfo.setOrganizationUrl(randomAlphanumeric(4));
+ pluginInfo.setOrganizationUrl(secure().nextAlphanumeric(4));
}
if (random.nextBoolean()) {
- pluginInfo.setIssueTrackerUrl(randomAlphanumeric(5));
+ pluginInfo.setIssueTrackerUrl(secure().nextAlphanumeric(5));
}
if (random.nextBoolean()) {
- pluginInfo.setIssueTrackerUrl(randomAlphanumeric(6));
+ pluginInfo.setIssueTrackerUrl(secure().nextAlphanumeric(6));
}
if (random.nextBoolean()) {
- pluginInfo.setBasePlugin(randomAlphanumeric(7));
+ pluginInfo.setBasePlugin(secure().nextAlphanumeric(7));
}
if (random.nextBoolean()) {
- pluginInfo.setHomepageUrl(randomAlphanumeric(8));
+ pluginInfo.setHomepageUrl(secure().nextAlphanumeric(8));
}
return pluginInfo
.setOrganizationName(organization)
}
private Plugin newPlugin(String organization, String license) {
- Plugin plugin = Plugin.factory(randomAlphanumeric(2));
+ Plugin plugin = Plugin.factory(secure().nextAlphanumeric(2));
if (random.nextBoolean()) {
- plugin.setName(randomAlphanumeric(3));
+ plugin.setName(secure().nextAlphanumeric(3));
}
if (random.nextBoolean()) {
- plugin.setOrganizationUrl(randomAlphanumeric(4));
+ plugin.setOrganizationUrl(secure().nextAlphanumeric(4));
}
if (random.nextBoolean()) {
- plugin.setTermsConditionsUrl(randomAlphanumeric(5));
+ plugin.setTermsConditionsUrl(secure().nextAlphanumeric(5));
}
if (random.nextBoolean()) {
- plugin.setIssueTrackerUrl(randomAlphanumeric(6));
+ plugin.setIssueTrackerUrl(secure().nextAlphanumeric(6));
}
if (random.nextBoolean()) {
- plugin.setCategory(randomAlphanumeric(7));
+ plugin.setCategory(secure().nextAlphanumeric(7));
}
if (random.nextBoolean()) {
- plugin.setHomepageUrl(randomAlphanumeric(8));
+ plugin.setHomepageUrl(secure().nextAlphanumeric(8));
}
return plugin
.setLicense(license)
import org.junit.Test;
import static java.util.Collections.emptyList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
@Test
public void constructor_throws_NPE_if_project_is_null() {
- assertThatThrownBy(() -> new RekeyedProject(null, randomAlphanumeric(3)))
+ assertThatThrownBy(() -> new RekeyedProject(null, secure().nextAlphanumeric(3)))
.isInstanceOf(NullPointerException.class)
.hasMessage("project can't be null");
}
@Test
public void verify_getters() {
Project project = newRandomProject();
- String previousKey = randomAlphanumeric(6);
+ String previousKey = secure().nextAlphanumeric(6);
RekeyedProject underTest = new RekeyedProject(project, previousKey);
assertThat(underTest.project()).isSameAs(project);
@Test
public void equals_is_based_on_project_and_previousKey() {
Project project = newRandomProject();
- String previousKey = randomAlphanumeric(6);
+ String previousKey = secure().nextAlphanumeric(6);
RekeyedProject underTest = new RekeyedProject(project, previousKey);
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new RekeyedProject(project, previousKey))
- .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11)))
+ .isNotEqualTo(new RekeyedProject(project, secure().nextAlphanumeric(11)))
.isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey))
.isNotEqualTo(new Object())
.isNotNull();
@Test
public void hashCode_is_based_on_project_and_previousKey() {
Project project = newRandomProject();
- String previousKey = randomAlphanumeric(6);
+ String previousKey = secure().nextAlphanumeric(6);
RekeyedProject underTest = new RekeyedProject(project, previousKey);
assertThat(underTest)
.hasSameHashCodeAs(underTest)
.hasSameHashCodeAs(new RekeyedProject(project, previousKey));
assertThat(underTest.hashCode())
- .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11)).hashCode())
+ .isNotEqualTo(new RekeyedProject(project, secure().nextAlphanumeric(11)).hashCode())
.isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey).hashCode())
.isNotEqualTo(new Object().hashCode());
}
private final QGChangeEventListener listener3 = mock(QGChangeEventListener.class);
private final List<QGChangeEventListener> listeners = Arrays.asList(listener1, listener2, listener3);
- private final String project1Uuid = RandomStringUtils.randomAlphabetic(6);
+ private final String project1Uuid = RandomStringUtils.secure().nextAlphabetic(6);
private final BranchDto project1 = newBranchDto(project1Uuid);
private final DefaultIssue component1Issue = newDefaultIssue(project1Uuid);
private final List<DefaultIssue> oneIssueOnComponent1 = singletonList(component1Issue);
import org.sonar.db.DbSession;
import org.sonar.db.property.InternalPropertiesDao;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DataProvider
public static Object[][] randomValidLockName() {
return new Object[][] {
- {randomAlphabetic(1 + new Random().nextInt(LOCK_NAME_MAX_LENGTH))}
+ {secure().nextAlphabetic(1 + new Random().nextInt(LOCK_NAME_MAX_LENGTH))}
};
}
import org.sonar.server.authentication.event.AuthenticationException;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void authentication_with_bcrypt_with_correct_password_should_work() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(BCRYPT.name())
@Test
public void authentication_with_sha1_should_throw_AuthenticationException() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
byte[] saltRandom = new byte[20];
RANDOM.nextBytes(saltRandom);
@Test
public void authentication_with_bcrypt_with_incorrect_password_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(BCRYPT.name())
@Test
public void authentication_upgrade_hash_function_when_BCRYPT_was_used() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto()
.setLogin("myself")
@Test
public void authentication_updates_db_if_PBKDF2_iterations_changes() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto().setLogin("myself");
db.users().insertUser(user);
@Test
public void authentication_with_pbkdf2_with_correct_password_should_work() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name());
settings.clear();
CredentialsLocalAuthentication underTest = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto user = newUserDto()
.setHashMethod(PBKDF2.name());
@Test
public void authentication_with_pbkdf2_with_invalid_hash_should_throw_AuthenticationException() {
DbSession dbSession = db.getSession();
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
UserDto userInvalidHash = newUserDto()
.setHashMethod(PBKDF2.name())
@Test
public void authentication_with_pbkdf2_with_empty_salt_should_throw_AuthenticationException() {
- String password = randomAlphanumeric(60);
+ String password = secure().nextAlphanumeric(60);
DbSession dbSession = db.getSession();
UserDto user = newUserDto()
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertNotNull;
@Test
public void fail_to_create_user_with_too_long_login() {
- NewUser newUser = newUserBuilder().setLogin(randomAlphabetic(256)).build();
+ NewUser newUser = newUserBuilder().setLogin(secure().nextAlphabetic(256)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
@Test
public void fail_to_create_user_with_too_long_name() {
- NewUser newUser = newUserBuilder().setName(randomAlphabetic(201)).build();
+ NewUser newUser = newUserBuilder().setName(secure().nextAlphabetic(201)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
@Test
public void fail_to_create_user_with_too_long_email() {
- NewUser newUser = newUserBuilder().setEmail(randomAlphabetic(101)).build();
+ NewUser newUser = newUserBuilder().setEmail(secure().nextAlphabetic(101)).build();
assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> {
}))
.isInstanceOf(BadRequestException.class)
}
void generateHashToAvoidEnumerationAttack(){
- String randomSalt = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
- String randomPassword = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
+ String randomSalt = RandomStringUtils.secure().nextAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
+ String randomPassword = RandomStringUtils.secure().nextAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE);
hashFunctions.get(HashMethod.PBKDF2).encryptPassword(randomSalt, randomPassword);
}
import org.junit.Test;
import org.sonar.db.user.GroupDto;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class GroupUuidOrAnyoneTest {
@Test
public void for_returns_isAnyone_false_if_id_is_not_null() {
- String uuid = randomAlphabetic(10);
+ String uuid = secure().nextAlphabetic(10);
GroupDto dto = new GroupDto();
dto.setUuid(uuid);
import org.sonar.server.project.DefaultBranchNameResolver;
import static java.util.stream.IntStream.rangeClosed;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
}
private void createComponent_shouldFail_whenCreatingComponentWithExistingKeyButDifferentCase(String qualifier) {
- String existingKey = randomAlphabetic(5).toUpperCase();
+ String existingKey = secure().nextAlphabetic(5).toUpperCase();
db.components().insertPrivateProject(component -> component.setKey(existingKey));
String newKey = existingKey.toLowerCase();
@Test
public void createComponent_shouldFail_whenCreatingComponentWithMultipleExistingKeyButDifferentCase() {
- String existingKey = randomAlphabetic(5).toUpperCase();
+ String existingKey = secure().nextAlphabetic(5).toUpperCase();
String existingKeyLowerCase = existingKey.toLowerCase();
db.components().insertPrivateProject(component -> component.setKey(existingKey));
db.components().insertPrivateProject(component -> component.setKey(existingKeyLowerCase));
@Test
public void createComponent_shouldFail_whenCreatingComponentWithMultipleExistingPortfolioKeysButDifferentCase() {
- String existingKey = randomAlphabetic(5).toUpperCase();
+ String existingKey = secure().nextAlphabetic(5).toUpperCase();
String existingKeyLowerCase = existingKey.toLowerCase();
db.components().insertPrivatePortfolio(portfolio -> portfolio.setKey(existingKey));
db.components().insertPrivatePortfolio(portfolio -> portfolio.setKey(existingKeyLowerCase));
@Inject
public UserAnonymizer(DbClient dbClient) {
- this(dbClient, () -> "sq-removed-" + RandomStringUtils.randomAlphanumeric(LOGIN_RANDOM_LENGTH));
+ this(dbClient, () -> "sq-removed-" + RandomStringUtils.secure().nextAlphanumeric(LOGIN_RANDOM_LENGTH));
}
public UserAnonymizer(DbClient dbClient, Supplier<String> randomNameGenerator) {
public class ProjectKeyGeneratorTest {
private static final int MAX_UUID_SIZE = 40;
- private static final String UUID_STRING = RandomStringUtils.randomAlphanumeric(MAX_UUID_SIZE);
+ private static final String UUID_STRING = RandomStringUtils.secure().nextAlphanumeric(MAX_UUID_SIZE);
@Mock
private UuidFactory uuidFactory;
@Test
public void generateUniqueProjectKey_shortProjectName_shouldAppendUuid() {
- String fullProjectName = RandomStringUtils.randomAlphanumeric(10);
+ String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(10);
assertThat(projectKeyGenerator.generateUniqueProjectKey(fullProjectName))
.isEqualTo(generateExpectedKeyName(fullProjectName));
@Test
public void generateUniqueProjectKey_projectNameEqualsToMaximumSize_shouldTruncateProjectNameAndPreserveUUID() {
- String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE);
+ String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(MAX_PROJECT_KEY_SIZE);
String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName);
assertThat(projectKey)
@Test
public void generateUniqueProjectKey_projectNameBiggerThanMaximumSize_shouldTruncateProjectNameAndPreserveUUID() {
- String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE + 50);
+ String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(MAX_PROJECT_KEY_SIZE + 50);
String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName);
assertThat(projectKey)
import static java.lang.String.format;
import static java.util.function.Function.identity;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public static Object[][] invalidGroupNames() {
return new Object[][] {
{"", "Group name cannot be empty"},
- {randomAlphanumeric(256), "Group name cannot be longer than 255 characters"},
+ {secure().nextAlphanumeric(256), "Group name cannot be longer than 255 characters"},
{"Anyone", "Anyone group cannot be used"},
};
}
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.of;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.process.cluster.health.NodeHealth.Status.GREEN;
import static org.sonar.process.cluster.health.NodeHealth.Status.RED;
import static org.sonar.process.cluster.health.NodeHealth.Status.YELLOW;
.setStatus(status)
.setDetails(NodeDetails.newNodeDetailsBuilder()
.setType(type)
- .setHost(randomAlphanumeric(32))
- .setName(randomAlphanumeric(32))
+ .setHost(secure().nextAlphanumeric(32))
+ .setName(secure().nextAlphanumeric(32))
.setPort(1 + random.nextInt(88))
.setStartedAt(1 + random.nextInt(54))
.build())
import org.mockito.Mockito;
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
-import org.sonar.server.common.health.EsStatusClusterCheck;
import org.sonar.server.es.EsClient;
import org.sonar.server.health.Health;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
.setStatus(status)
.setDetails(NodeDetails.newNodeDetailsBuilder()
.setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH)
- .setName(randomAlphanumeric(23))
- .setHost(randomAlphanumeric(23))
+ .setName(secure().nextAlphanumeric(23))
+ .setHost(secure().nextAlphanumeric(23))
.setPort(1 + random.nextInt(96))
.setStartedAt(1 + random.nextInt(966))
.build())
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.property.InternalProperties;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
@RunWith(DataProviderRunner.class)
public class ServerIdManagerIT {
- private static final ServerId WITH_DATABASE_ID_SERVER_ID = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(NOT_UUID_DATASET_ID_LENGTH));
- private static final String CHECKSUM_1 = randomAlphanumeric(12);
+ private static final ServerId WITH_DATABASE_ID_SERVER_ID = ServerId.of(secure().nextAlphanumeric(DATABASE_ID_LENGTH), secure().nextAlphanumeric(NOT_UUID_DATASET_ID_LENGTH));
+ private static final String CHECKSUM_1 = secure().nextAlphanumeric(12);
@Rule
public final DbTester dbTester = DbTester.create(System2.INSTANCE);
@Test
public void web_leader_creates_server_id_from_current_serverId_with_databaseId_if_checksum_fails() {
- ServerId currentServerId = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(UUID_DATASET_ID_LENGTH));
+ ServerId currentServerId = ServerId.of(secure().nextAlphanumeric(DATABASE_ID_LENGTH), secure().nextAlphanumeric(UUID_DATASET_ID_LENGTH));
insertServerId(currentServerId);
insertChecksum("does_not_match_WITH_DATABASE_ID_SERVER_ID");
mockChecksumOf(currentServerId, "matches_WITH_DATABASE_ID_SERVER_ID");
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.issue.impact.Severity;
import org.sonar.api.issue.impact.SoftwareQuality;
-import org.sonar.api.resources.Language;
-import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleScope;
import org.sonar.api.rule.RuleStatus;
import static java.lang.String.valueOf;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void insert_then_remove_rule() {
- String ruleKey = randomAlphanumeric(5);
+ String ruleKey = secure().nextAlphanumeric(5);
// register one rule
executeWithPluginRules(context -> {
NewRepository repo = context.createRepository("fake", "java");
repo.createRule(ruleKey)
- .setName(randomAlphanumeric(5))
- .setHtmlDescription(randomAlphanumeric(20));
+ .setName(secure().nextAlphanumeric(5))
+ .setHtmlDescription(secure().nextAlphanumeric(20));
repo.done();
});
IntStream.range(0, numberOfRules)
.mapToObj(i -> "rule-" + i)
.forEach(ruleKey -> repo.createRule(ruleKey)
- .setName(randomAlphanumeric(20))
- .setHtmlDescription(randomAlphanumeric(20)));
+ .setName(secure().nextAlphanumeric(20))
+ .setHtmlDescription(secure().nextAlphanumeric(20)));
repo.done();
});
}
private static RuleDescriptionSection createRuleDescriptionSection(String sectionKey, String description, @Nullable String contextKey) {
- Context context = Optional.ofNullable(contextKey).map(key -> new Context(contextKey, contextKey + randomAlphanumeric(10))).orElse(null);
+ Context context = Optional.ofNullable(contextKey).map(key -> new Context(contextKey, contextKey + secure().nextAlphanumeric(10))).orElse(null);
return RuleDescriptionSection.builder().sectionKey(sectionKey)
.htmlContent(description)
.context(context)
import static java.util.Collections.emptySet;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.of;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
Configuration configuration = mock(Configuration.class);
mockPayloadSupplierConsumedByWebhooks();
Map<String, String> properties = new HashMap<>();
- properties.put("sonar.analysis.test1", randomAlphanumeric(50));
- properties.put("sonar.analysis.test2", randomAlphanumeric(5000));
+ properties.put("sonar.analysis.test1", secure().nextAlphanumeric(50));
+ properties.put("sonar.analysis.test2", secure().nextAlphanumeric(5000));
insertPropertiesFor(analysis.getUuid(), properties);
QGChangeEvent qualityGateEvent = newQGChangeEvent(projectBranch, analysis, configuration, newQualityGate);
mockWebhookEnabled(qualityGateEvent.getProject());
import org.sonar.api.config.internal.MapSettings;
import org.sonar.core.platform.ServerId;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@RunWith(DataProviderRunner.class)
public class ServerIdFactoryImplTest {
- private static final ServerId A_SERVERID = ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH));
+ private static final ServerId A_SERVERID = ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH));
private MapSettings settings = new MapSettings();
private Configuration config = settings.asConfig();
public static Object[][] anyFormatServerId() {
return new Object[][] {
{ServerId.parse(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))},
- {ServerId.parse(randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))},
- {ServerId.parse(randomAlphabetic(UUID_DATASET_ID_LENGTH))},
- {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))},
- {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH))}
+ {ServerId.parse(secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH))},
+ {ServerId.parse(secure().nextAlphabetic(UUID_DATASET_ID_LENGTH))},
+ {ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH))},
+ {ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH))}
};
}
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
-import org.sonar.server.rule.registration.SingleDeprecatedRuleKey;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
public void test_creation_from_DeprecatedRuleKeyDto() {
// Creation from DeprecatedRuleKeyDto
DeprecatedRuleKeyDto deprecatedRuleKeyDto = new DeprecatedRuleKeyDto()
- .setOldRuleKey(randomAlphanumeric(50))
- .setOldRepositoryKey(randomAlphanumeric(50))
- .setRuleUuid(randomAlphanumeric(50))
- .setUuid(randomAlphanumeric(40));
+ .setOldRuleKey(secure().nextAlphanumeric(50))
+ .setOldRepositoryKey(secure().nextAlphanumeric(50))
+ .setRuleUuid(secure().nextAlphanumeric(50))
+ .setUuid(secure().nextAlphanumeric(40));
SingleDeprecatedRuleKey singleDeprecatedRuleKey = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto);
public void test_creation_from_RulesDefinitionRule() {
// Creation from RulesDefinition.Rule
ImmutableSet<RuleKey> deprecatedRuleKeys = ImmutableSet.of(
- RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)),
- RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)),
- RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)));
+ RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50)),
+ RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50)),
+ RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50)));
RulesDefinition.Repository repository = mock(RulesDefinition.Repository.class);
- when(repository.key()).thenReturn(randomAlphanumeric(50));
+ when(repository.key()).thenReturn(secure().nextAlphanumeric(50));
RulesDefinition.Rule rule = mock(RulesDefinition.Rule.class);
- when(rule.key()).thenReturn(randomAlphanumeric(50));
+ when(rule.key()).thenReturn(secure().nextAlphanumeric(50));
when(rule.deprecatedRuleKeys()).thenReturn(deprecatedRuleKeys);
when(rule.repository()).thenReturn(repository);
@Test
public void test_equality() {
DeprecatedRuleKeyDto deprecatedRuleKeyDto1 = new DeprecatedRuleKeyDto()
- .setOldRuleKey(randomAlphanumeric(50))
- .setOldRepositoryKey(randomAlphanumeric(50))
- .setUuid(randomAlphanumeric(40))
+ .setOldRuleKey(secure().nextAlphanumeric(50))
+ .setOldRepositoryKey(secure().nextAlphanumeric(50))
+ .setUuid(secure().nextAlphanumeric(40))
.setRuleUuid("some-uuid");
DeprecatedRuleKeyDto deprecatedRuleKeyDto1WithoutUuid = new DeprecatedRuleKeyDto()
.setOldRepositoryKey(deprecatedRuleKeyDto1.getOldRepositoryKey());
DeprecatedRuleKeyDto deprecatedRuleKeyDto2 = new DeprecatedRuleKeyDto()
- .setOldRuleKey(randomAlphanumeric(50))
- .setOldRepositoryKey(randomAlphanumeric(50))
- .setUuid(randomAlphanumeric(40));
+ .setOldRuleKey(secure().nextAlphanumeric(50))
+ .setOldRepositoryKey(secure().nextAlphanumeric(50))
+ .setUuid(secure().nextAlphanumeric(40));
SingleDeprecatedRuleKey singleDeprecatedRuleKey1 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1);
SingleDeprecatedRuleKey singleDeprecatedRuleKey2 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto2);
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@Test
public void markAsCompatible_has_no_effect_if_vendor_is_the_same() {
- String vendor = randomAlphabetic(12);
+ String vendor = secure().nextAlphabetic(12);
prepareEs(vendor);
prepareDb(vendor);
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.component.ComponentTesting.newBranchComponent;
@Test
void searchProjectStatistics_does_not_return_results_if_assignee_does_not_match() {
ComponentDto project = newPrivateProjectDto();
- String user1Uuid = randomAlphanumeric(40);
- String user2Uuid = randomAlphanumeric(40);
+ String user1Uuid = secure().nextAlphanumeric(40);
+ String user2Uuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L)));
@Test
void searchProjectStatistics_returns_results_if_assignee_matches() {
ComponentDto project = newPrivateProjectDto();
- String user1Uuid = randomAlphanumeric(40);
+ String user1Uuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L)));
@Test
void searchProjectStatistics_returns_results_if_functional_date_is_strictly_after_from_date() {
ComponentDto project = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)));
@Test
void searchProjectStatistics_does_not_return_results_if_functional_date_is_same_as_from_date() {
ComponentDto project = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from)));
@Test
void searchProjectStatistics_does_not_return_resolved_issues() {
ComponentDto project = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_FALSE_POSITIVE),
@Test
void searchProjectStatistics_does_not_return_results_if_functional_date_is_before_from_date() {
ComponentDto project = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from - 1000L)));
@Test
void searchProjectStatistics_returns_issue_count() {
ComponentDto project = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
ComponentDto project1 = newPrivateProjectDto();
ComponentDto project2 = newPrivateProjectDto();
ComponentDto project3 = newPrivateProjectDto();
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_000L;
indexIssues(
newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1_000L)),
void searchProjectStatistics_return_branch_issues() {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = newBranchComponent(project, newBranchDto(project).setKey("branch"));
- String userUuid = randomAlphanumeric(40);
+ String userUuid = secure().nextAlphanumeric(40);
long from = 1_111_234_567_890L;
indexIssues(
newDoc("issue1", project.uuid(), branch).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)),
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public void search_issue_from_branch() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
assertThat(underTest.create(new SearchRequest()
@Test
public void search_file_issue_from_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
@Test
public void search_issue_on_component_only_from_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
import org.sonarqube.ws.Common;
import static java.util.List.of;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY;
import static org.sonar.db.rule.RuleTesting.newCustomRule;
RuleParamDto rule1Param = db.rules().insertRuleParam(rule1);
ActiveRuleDto activeRule1 = db.qualityProfiles().activateRule(activatedQualityProfile, rule1);
- ActiveRuleParamDto activeRuleParam1 = ActiveRuleParamDto.createFor(rule1Param).setValue(randomAlphanumeric(20));
+ ActiveRuleParamDto activeRuleParam1 = ActiveRuleParamDto.createFor(rule1Param).setValue(secure().nextAlphanumeric(20));
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule1, activeRuleParam1);
db.getSession().commit();
RuleParamDto rule2Param = db.rules().insertRuleParam(rule2);
ActiveRuleDto activeRule2 = db.qualityProfiles().activateRule(deactivatedQualityProfile, rule2);
- ActiveRuleParamDto activeRuleParam2 = ActiveRuleParamDto.createFor(rule2Param).setValue(randomAlphanumeric(20));
+ ActiveRuleParamDto activeRuleParam2 = ActiveRuleParamDto.createFor(rule2Param).setValue(secure().nextAlphanumeric(20));
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule2, activeRuleParam2);
db.getSession().commit();
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
private Repository mockBitbucketServerRepo(Project project, BranchesList branchesList) {
Repository bbsResult = new Repository();
bbsResult.setProject(project);
- bbsResult.setSlug(randomAlphanumeric(5));
- bbsResult.setName(randomAlphanumeric(5));
+ bbsResult.setSlug(secure().nextAlphanumeric(5));
+ bbsResult.setName(secure().nextAlphanumeric(5));
bbsResult.setId(random.nextLong(100));
when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(bbsResult);
when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList);
private Project getGsonBBSProject() {
return new Project()
- .setKey(randomAlphanumeric(5))
+ .setKey(secure().nextAlphanumeric(5))
.setId(random.nextLong(100))
- .setName(randomAlphanumeric(5));
+ .setName(secure().nextAlphanumeric(5));
}
private ProjectDto getProjectDto(Projects.CreateWsResponse.Project result) {
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
@Test
@UseDataProvider("secretParams")
public void update_withSecretChange_shouldAuditDevOpsPlatformSecret(String secretParam) {
- buildTestRequestWithoutSecrets().setParam(secretParam, randomAlphanumeric(10)).execute();
+ buildTestRequestWithoutSecrets().setParam(secretParam, secure().nextAlphanumeric(10)).execute();
SecretNewValue expected = new SecretNewValue("DevOpsPlatform", GITHUB.getId());
ArgumentCaptor<SecretNewValue> captor = ArgumentCaptor.forClass(SecretNewValue.class);
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
userSession.registerProjects(projectData.getProjectDto());
MetricDto metric = createIntMetricAndMeasure(project, BUGS_KEY, 5_000);
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName));
db.measures().insertMeasure(branch, m -> m.addValue(metric.getKey(), 10_000d));
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
userSession.registerProjects(projectData.getProjectDto());
MetricDto metric = createQualityGateMetric();
db.measures().insertMeasure(project, m -> m.addValue(metric.getKey(), OK.name()));
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName));
db.measures().insertMeasure(branch, m -> m.addValue(metric.getKey(), ERROR.name()));
import org.sonar.db.user.UserDto;
import org.sonar.server.common.almsettings.DevOpsProjectCreatorFactory;
import org.sonar.server.common.almsettings.github.GithubProjectCreatorFactory;
-import org.sonar.server.component.ComponentCreationData;
import org.sonar.server.common.component.ComponentCreationParameters;
import org.sonar.server.common.component.ComponentUpdater;
+import org.sonar.server.common.permission.PermissionTemplateService;
+import org.sonar.server.common.project.ProjectCreator;
+import org.sonar.server.component.ComponentCreationData;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.favorite.FavoriteUpdater;
import org.sonar.server.management.ManagedInstanceService;
-import org.sonar.server.common.permission.PermissionTemplateService;
import org.sonar.server.project.ProjectDefaultVisibility;
import org.sonar.server.project.Visibility;
-import org.sonar.server.common.project.ProjectCreator;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Collections.emptyMap;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
}
private String mockSuccessfulPrepareSubmitCall() {
- String taskUuid = randomAlphabetic(12);
+ String taskUuid = secure().nextAlphabetic(12);
when(queue.prepareSubmit()).thenReturn(new CeTaskSubmit.Builder(taskUuid));
return taskUuid;
}
}
private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey) {
- return createComponentKeyOfBranch(projectKey, randomAlphabetic(5));
+ return createComponentKeyOfBranch(projectKey, secure().nextAlphabetic(5));
}
private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey, String branchKey) {
logInAsSystemAdministrator();
ProjectData project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project.getProjectDto());
- String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
SnapshotDto analysis = db.components().insertSnapshot(pullRequest);
CeActivityDto activity = insertActivity("T1", project.projectUuid(), project.getMainBranchComponent().uuid(), SUCCESS, analysis);
import org.sonarqube.ws.MediaTypes;
import static java.util.Collections.emptyList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public void branch_in_activity() {
ProjectData project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BRANCH).setKey(branchName));
SnapshotDto analysis = db.components().insertSnapshot(branch);
CeActivityDto activity = insertActivity("T1", project.getMainBranchComponent(), project.getProjectDto(), SUCCESS, analysis);
public void branch_in_queue_analysis() {
ProjectData project = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BRANCH).setKey(branchName));
CeQueueDto queue1 = insertQueue("T1", project.getMainBranchComponent(), project.getProjectDto(), IN_PROGRESS);
insertCharacteristic(queue1, CeTaskCharacteristics.BRANCH, branchName);
import org.sonarqube.ws.Common;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.web.UserRole.ADMIN;
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BRANCH).setKey(branchName));
db.components().insertSnapshot(branch);
CeActivityDto activity = createAndPersistArchivedTask(mainBranch);
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
@Test
public void branch() {
userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
userSession.addProjectBranchMapping(projectData.getProjectDto().getUuid(), branch);
ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src"));
@Test
public void component_and_branch_parameters_provided() {
userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
userSession.addProjectBranchMapping(projectData.projectUuid(), branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
public void component_and_pull_request_parameters_provided() {
userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto())
.registerBranches(projectData.getMainBranchDto());
- String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100);
ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
userSession.addProjectBranchMapping(projectData.projectUuid(), branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
import org.sonarqube.ws.Components.Component;
import org.sonarqube.ws.Components.ShowWsResponse;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
ComponentDto portfolio2 = db.components().insertPublicPortfolio();
ComponentDto subview = db.components().insertSubView(portfolio1);
- String pullRequestKey1 = randomAlphanumeric(100);
+ String pullRequestKey1 = secure().nextAlphanumeric(100);
ProjectData projectData1 = db.components().insertPrivateProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1)
ProjectData projectData2 = db.components().insertPrivateProject();
ComponentDto project2 = projectData2.getMainBranchComponent();
- String branchName2 = randomAlphanumeric(248);
+ String branchName2 = secure().nextAlphanumeric(248);
ComponentDto branch2 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(true).setKey(branchName2));
- String branchName3 = randomAlphanumeric(248);
+ String branchName3 = secure().nextAlphanumeric(248);
ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName3));
userSession.addProjectBranchMapping(projectData2.projectUuid(), projectData2.getMainBranchComponent());
userSession.addProjectBranchMapping(projectData2.projectUuid(), branch2);
ProjectData projectData3 = db.components().insertPrivateProject();
ComponentDto project3 = projectData3.getMainBranchComponent();
- String pullRequestKey4 = randomAlphanumeric(100);
+ String pullRequestKey4 = secure().nextAlphanumeric(100);
ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey4).setNeedIssueSync(false));
ComponentDto directoryOfBranch4 = db.components().insertComponent(newDirectoryOnBranch(branch4, "dir", project3.uuid()));
ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(project3.uuid(), branch4, directoryOfBranch4));
- String branchName5 = randomAlphanumeric(248);
+ String branchName5 = secure().nextAlphanumeric(248);
ComponentDto branch5 = db.components().insertProjectBranch(project3, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName5));
userSession.addProjectBranchMapping(projectData3.projectUuid(), projectData3.getMainBranchComponent());
userSession.addProjectBranchMapping(projectData3.projectUuid(), branch4);
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
-import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ProjectData;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.joining;
import static java.util.stream.IntStream.range;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.doReturn;
@Test
public void should_only_provide_project_for_certain_qualifiers() {
- String query = randomAlphabetic(10);
+ String query = secure().nextAlphabetic(10);
ProjectData appData = db.components().insertPublicApplication(v -> v.setName(query));
ComponentDto app = appData.getMainBranchComponent();
import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
userSession.addProjectPermission(USER, projectData.getProjectDto());
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
SnapshotDto projectAnalysis = insertAnalysis(mainBranch, 1_500_000_000_000L);
db.events().insertEvent(newQualityGateEvent(projectAnalysis).setDate(projectAnalysis.getCreatedAt()).setName("Passed"));
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
queueDto.setComponentUuid(mainBranchUuid);
- queueDto.setUuid(randomAlphanumeric(40));
+ queueDto.setUuid(secure().nextAlphanumeric(40));
queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE));
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setStatus(status);
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
queueDto.setComponentUuid(mainBranchUuid);
- queueDto.setUuid(randomAlphanumeric(40));
+ queueDto.setUuid(secure().nextAlphanumeric(40));
queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE));
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setStatus(status);
import static java.lang.String.format;
import static java.lang.String.join;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName));
insertSuccessfulActivity(project, 1_500_000_000_000L);
SnapshotDto branchAnalysis = insertSuccessfulActivity(branch, 1_500_000_000_000L);
CeQueueDto queueDto = new CeQueueDto();
queueDto.setTaskType(CeTaskTypes.REPORT);
queueDto.setComponentUuid(mainBranchUuid);
- queueDto.setUuid(randomAlphanumeric(40));
+ queueDto.setUuid(secure().nextAlphanumeric(40));
queueDto.setCreatedAt(ANY_TIMESTAMP);
CeActivityDto activityDto = new CeActivityDto(queueDto);
activityDto.setStatus(status);
import org.sonar.server.component.ComponentFinder;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.component.ComponentTesting.newFileDto;
@Test
public void duplication_on_branch() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file1 = db.components().insertComponent(newFileDto(branch, project.uuid()));
ComponentDto file2 = db.components().insertComponent(newFileDto(branch, project.uuid()));
@Test
public void duplication_on_pull_request() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
- String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
public void duplications_by_file_key_and_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
userSessionRule.addProjectBranchMapping(project.uuid(), branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
public void duplications_by_file_key_and_pull_request() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
userSessionRule.addProjectBranchMapping(project.uuid(), pullRequest);
ComponentDto file = db.components().insertComponent(newFileDto(pullRequest, project.uuid()));
import org.sonar.test.JsonAssert;
import static com.google.common.collect.Lists.newArrayList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
@Test
public void write_duplications_on_branch() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file1 = db.components().insertComponent(newFileDto(branch, project.uuid()));
ComponentDto file2 = db.components().insertComponent(newFileDto(branch, project.uuid()));
@Test
public void write_duplications_on_pull_request() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest));
ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest));
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@Test
public void fails_with_IAE_if_parameter_comment_is_missing() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key);
@Test
public void fails_with_NotFoundException_if_hotspot_does_not_exist() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
- .setParam("comment", randomAlphabetic(10));
+ .setParam("comment", secure().nextAlphabetic(10));
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
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));
+ TestRequest request = newRequest(notAHotspot, secure().nextAlphabetic(12));
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
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));
+ TestRequest request = newRequest(hotspot, secure().nextAlphabetic(12));
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
TestRequest request = newRequest(hotspot, comment);
assertThatThrownBy(request::execute)
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
newRequest(hotspot, comment).execute().assertNoContent();
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file);
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
newRequest(hotspot, comment).execute().assertNoContent();
}
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
RuleDto rule = dbTester.rules().insertHotspotRule();
IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(currentStatus).setResolution(currentResolution));
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
newRequest(hotspot, comment).execute().assertNoContent();
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
executeRequest(hotspot, assignee.getLogin(), null);
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setAssigneeUuid(assignee.getUuid()));
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), isNull(), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto me = insertUser(randomAlphanumeric(10));
+ UserDto me = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(me).registerProjects(projectData.getProjectDto());
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true);
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
- UserDto me = insertUser(randomAlphanumeric(10));
+ UserDto me = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(me).registerProjects(projectData.getProjectDto());
IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setAssigneeUuid(me.getUuid()));
ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
- insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
- UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto());
+ insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ UserDto assignee = insertUserWithProjectUserPermission(secure().nextAlphanumeric(15), project.getProjectDto());
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
public void wsExecution_whenUnassignedForPrivateProject() {
ProjectData project = dbTester.components().insertPrivateProject();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file, h -> h.setAssigneeUuid(assignee.getUuid()));
- insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), isNull(), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent().uuid()));
IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
- insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
userSessionRule.addProjectBranchMapping(project.projectUuid(), branch);
- UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto());
+ UserDto assignee = insertUserWithProjectUserPermission(secure().nextAlphanumeric(15), project.getProjectDto());
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
- insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent()));
IssueDto hotspot = dbTester.issues().insertHotspot(branch, file);
- insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
userSessionRule.addProjectBranchMapping(project.projectUuid(), branch);
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
- UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER);
+ UserDto me = insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER);
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(false);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH);
String projectUuid = "projectUuid";
when(branchDto.getProjectUuid()).thenReturn(projectUuid);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
when(branchDto.getBranchType()).thenReturn(BranchType.PULL_REQUEST);
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true);
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file);
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
- String notExistingUserLogin = randomAlphanumeric(10);
+ String notExistingUserLogin = secure().nextAlphanumeric(10);
assertThatThrownBy(() -> executeRequest(hotspot, notExistingUserLogin, null))
.isInstanceOf(NotFoundException.class)
h.setResolution(resolution);
});
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
String login = userSessionRule.getLogin();
h.setResolution(resolution);
});
- UserDto userDto = insertUser(randomAlphanumeric(10));
+ UserDto userDto = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto());
String login = userSessionRule.getLogin();
userSessionRule.anonymous();
- UserDto assignee = insertUser(randomAlphanumeric(15));
+ UserDto assignee = insertUser(secure().nextAlphanumeric(15));
String login = assignee.getLogin();
assertThatThrownBy(() -> executeRequest(hotspot, login, null))
ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent()));
IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file);
- UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.CODEVIEWER);
+ UserDto me = insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.CODEVIEWER);
when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true);
public void wsExecution_whenHotspotDoesNotExist_shouldFail() {
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
- UserDto me = insertUser(randomAlphanumeric(10));
+ UserDto me = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn().registerProjects(projectData.getProjectDto());
- String notExistingHotspotKey = randomAlphanumeric(10);
+ String notExistingHotspotKey = secure().nextAlphanumeric(10);
String login = me.getLogin();
assertThatThrownBy(() -> executeRequest(notExistingHotspotKey, login, null))
.isInstanceOf(NotFoundException.class)
.setStatus(status)
.setType(ruleType));
- UserDto me = insertUser(randomAlphanumeric(10));
+ UserDto me = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn().registerProjects(projectData.getProjectDto());
String login = me.getLogin();
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto issue = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED));
- UserDto me = insertUser(randomAlphanumeric(10));
+ UserDto me = insertUser(secure().nextAlphanumeric(10));
userSessionRule.logIn().registerProjects(projectData.getProjectDto());
String login = me.getLogin();
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@Test
public void fails_with_IAE_if_parameter_status_is_missing() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key);
@Test
@UseDataProvider("badStatuses")
public void fail_with_IAE_if_status_value_is_neither_REVIEWED_nor_TO_REVIEW(String badStatus) {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
Issue.STATUSES.stream()
.filter(t -> !t.equals(STATUS_TO_REVIEW))
.filter(t -> !t.equals(STATUS_REVIEWED)),
- Stream.of(randomAlphabetic(22), ""))
+ Stream.of(secure().nextAlphabetic(22), ""))
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
@UseDataProvider("badResolutions")
public void fail_with_IAE_if_resolution_value_is_neither_FIXED_nor_SAFE(String validStatus, String badResolution) {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
@Test
@UseDataProvider("validResolutions")
public void fail_with_IAE_if_status_is_TO_REVIEW_and_resolution_is_set(String resolution) {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
}
public void fail_with_IAE_if_status_is_RESOLVED_and_resolution_is_not_set() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
@Test
@UseDataProvider("validStatusAndResolutions")
public void fails_with_NotFoundException_if_hotspot_does_not_exist(String status, @Nullable String resolution) {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
userSessionRule.logIn();
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key)
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setStatus(currentStatus).setResolution(currentResolution));
when(transitionService.doTransition(any(), any(), any())).thenReturn(transitionDone);
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
newRequest(hotspot, newStatus, newResolution, comment).execute().assertNoContent();
.addProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN, projectData.getProjectDto());
ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setStatus(status).setResolution(resolution));
- String comment = randomAlphabetic(12);
+ String comment = secure().nextAlphabetic(12);
newRequest(hotspot, status, resolution, comment).execute().assertNoContent();
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
@Test
public void fail_with_IAE_if_parameter_branch_is_used_without_parameter_project() {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_HOTSPOTS, randomAlphabetic(2))
- .setParam(PARAM_BRANCH, randomAlphabetic(1));
+ .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(2))
+ .setParam(PARAM_BRANCH, secure().nextAlphabetic(1));
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
@Test
public void fail_with_IAE_if_parameter_pullRequest_is_used_without_parameter_project() {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_HOTSPOTS, randomAlphabetic(2))
- .setParam(PARAM_PULL_REQUEST, randomAlphabetic(1));
+ .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(2))
+ .setParam(PARAM_PULL_REQUEST, secure().nextAlphabetic(1));
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
@Test
public void fail_with_IAE_if_both_parameters_pullRequest_and_branch_are_provided() {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_PROJECT, randomAlphabetic(2))
- .setParam(PARAM_BRANCH, randomAlphabetic(1))
- .setParam(PARAM_PULL_REQUEST, randomAlphabetic(1));
+ .setParam(PARAM_PROJECT, secure().nextAlphabetic(2))
+ .setParam(PARAM_BRANCH, secure().nextAlphabetic(1))
+ .setParam(PARAM_PULL_REQUEST, secure().nextAlphabetic(1));
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
@UseDataProvider("badStatuses")
public void fails_with_IAE_if_status_parameter_is_neither_TO_REVIEW_or_REVIEWED(String badStatus) {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_PROJECT, randomAlphabetic(13))
+ .setParam(PARAM_PROJECT, secure().nextAlphabetic(13))
.setParam(PARAM_STATUS, badStatus);
assertThatThrownBy(request::execute)
public static Object[][] badStatuses() {
return Stream.concat(
Issue.STATUSES.stream(),
- Stream.of(randomAlphabetic(3)))
+ Stream.of(secure().nextAlphabetic(3)))
.filter(t -> !STATUS_REVIEWED.equals(t))
.filter(t -> !STATUS_TO_REVIEW.equals(t))
.map(t -> new Object[] {t})
@UseDataProvider("validStatusesAndResolutions")
public void fail_with_IAE_if_parameter_status_is_specified_with_hotspots_parameter(String status, @Nullable String notUsed) {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_HOTSPOTS, randomAlphabetic(12))
+ .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(12))
.setParam(PARAM_STATUS, status);
assertThatThrownBy(request::execute)
@UseDataProvider("badResolutions")
public void fails_with_IAE_if_resolution_parameter_is_neither_FIXED_nor_SAFE(String badResolution) {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_PROJECT, randomAlphabetic(13))
+ .setParam(PARAM_PROJECT, secure().nextAlphabetic(13))
.setParam(PARAM_STATUS, STATUS_TO_REVIEW)
.setParam(PARAM_RESOLUTION, badResolution);
return Stream.of(
Issue.RESOLUTIONS.stream(),
Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(),
- Stream.of(randomAlphabetic(4)))
+ Stream.of(secure().nextAlphabetic(4)))
.flatMap(t -> t)
.filter(t -> !RESOLUTION_TYPES.contains(t))
.map(t -> new Object[] {t})
@UseDataProvider("fixedOrSafeResolution")
public void fails_with_IAE_if_resolution_is_provided_with_status_TO_REVIEW(String resolution) {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_PROJECT, randomAlphabetic(13))
+ .setParam(PARAM_PROJECT, secure().nextAlphabetic(13))
.setParam(PARAM_STATUS, STATUS_TO_REVIEW)
.setParam(PARAM_RESOLUTION, resolution);
@UseDataProvider("fixedOrSafeResolution")
public void fails_with_IAE_if_resolution_is_provided_with_hotspots_parameter(String resolution) {
TestRequest request = actionTester.newRequest()
- .setParam(PARAM_HOTSPOTS, randomAlphabetic(13))
+ .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(13))
.setParam(PARAM_RESOLUTION, resolution);
assertThatThrownBy(request::execute)
@Test
public void fails_with_NotFoundException_if_project_does_not_exist() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
TestRequest request = actionTester.newRequest()
.setParam(PARAM_PROJECT, key);
IssueDto[] assigneeHotspots = IntStream.range(0, 1 + RANDOM.nextInt(10))
.mapToObj(i -> {
RuleDto rule = newRule(SECURITY_HOTSPOT);
- insertHotspot(rule, project1, file1, randomAlphabetic(5));
+ insertHotspot(rule, project1, file1, secure().nextAlphabetic(5));
return insertHotspot(rule, project1, file1, assigneeUuid);
})
.toArray(IssueDto[]::new);
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)));
+ IssueDto badlyResolved = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_TO_REVIEW).setResolution(secure().nextAlphabetic(5)));
IssueDto badlyReviewed = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_REVIEWED).setResolution(null));
IssueDto badlyClosedHotspot = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setResolution(null));
indexIssues();
RuleDto rule = newRule(SECURITY_HOTSPOT);
IssueDto hotspot = insertHotspot(rule, project, file,
t -> t
- .setStatus(randomAlphabetic(11))
+ .setStatus(secure().nextAlphabetic(11))
.setLine(RANDOM.nextInt(230))
- .setMessage(randomAlphabetic(10))
- .setAssigneeUuid(randomAlphabetic(9))
- .setAuthorLogin(randomAlphabetic(8))
+ .setMessage(secure().nextAlphabetic(10))
+ .setAssigneeUuid(secure().nextAlphabetic(9))
+ .setAuthorLogin(secure().nextAlphabetic(8))
.setStatus(status)
.setResolution(resolution));
indexIssues();
public void returns_branch_field_of_components_of_branch() {
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchName));
userSessionRule.registerProjects(projectData.getProjectDto());
indexPermissions();
public void returns_pullRequest_field_of_components_of_pullRequest() {
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto project = projectData.getMainBranchComponent();
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST)
.setKey(pullRequestKey));
userSessionRule.registerProjects(projectData.getProjectDto());
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
+import org.sonar.server.common.avatar.AvatarResolver;
+import org.sonar.server.common.avatar.AvatarResolverImpl;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.common.avatar.AvatarResolver;
-import org.sonar.server.common.avatar.AvatarResolverImpl;
import org.sonar.server.issue.IssueChangeWSSupport;
import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext;
import org.sonar.server.issue.IssueChangeWSSupport.Load;
import org.sonarqube.ws.Hotspots;
import static java.util.Collections.emptySet;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
@Test
public void fails_with_NotFoundException_if_hotspot_does_not_exist() {
- String key = randomAlphabetic(12);
+ String key = secure().nextAlphabetic(12);
TestRequest request = actionTester.newRequest()
.setParam("hotspot", key);
return RuleDescriptionSectionDto.builder()
.uuid(uuidFactory.create())
.key(assessTheProblemSectionKey)
- .content(randomAlphabetic(200))
+ .content(secure().nextAlphabetic(200))
.build();
}
userSessionRule.registerProjects(projectData.getProjectDto());
ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
RuleDto rule = newRule(SECURITY_HOTSPOT);
- IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(randomAlphabetic(10)));
+ IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(secure().nextAlphabetic(10)));
mockChangelogAndCommentsFormattingContext();
Hotspots.ShowWsResponse response = newRequest(hotspot)
userSessionRule.registerProjects(projectData.getProjectDto());
ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent));
RuleDto rule = newRule(SECURITY_HOTSPOT);
- String authorLogin = randomAlphabetic(10);
+ String authorLogin = secure().nextAlphabetic(10);
IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(authorLogin));
mockChangelogAndCommentsFormattingContext();
public void returns_branch_but_no_pullRequest_on_component_and_project_on_non_main_branch() {
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = dbTester.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName));
userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), branch);
ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid()));
public void returns_pullRequest_but_no_branch_on_component_and_project_on_pullRequest() {
ProjectData projectData = dbTester.components().insertPublicProject();
ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto pullRequest = dbTester.components().insertProjectBranch(mainBranchComponent,
t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), pullRequest);
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.api.utils.DateUtils.formatDateTime;
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser();
UserDto user3 = dbTester.users().insertUser();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto fieldChangeUser1 = newFieldChange(issue)
.setUserUuid(user1.getUuid())
.setChangeData(new FieldDiffs().setDiff("f_change_user_1", null, null).toEncodedString());
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser();
UserDto user3 = dbTester.users().insertUser();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid());
IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid());
IssueChangeDto issueChangeUser2b = newComment(issue).setUserUuid(user2.getUuid());
UserDto user2 = dbTester.users().insertUser();
UserDto user3 = dbTester.users().insertUser();
UserDto user4 = dbTester.users().insertUser();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid());
IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid());
IssueChangeDto issueChangeUser2b = newComment(issue).setUserUuid(user2.getUuid());
ComponentDto file3 = insertFile();
ComponentDto file4 = insertFile();
ComponentDto file5 = insertFile();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto fileChangeFile1 = newFieldChange(issue)
.setChangeData(new FieldDiffs().setDiff("file", file1.uuid(), null).toEncodedString());
IssueChangeDto fileChangeFile2 = newFieldChange(issue)
public void newFormattingContext_comments_without_userUuid_or_with_unknown_userUuid_are_not_updatable(Load load) {
IssueDto issue = dbTester.issues().insertIssue();
UserDto user1 = dbTester.users().insertUser();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto issueChangeUser1 = newComment(issue);
IssueChangeDto issueChangeUserUnknown = newComment(issue).setUserUuid(uuid);
insertInRandomOrder(Arrays.asList(issueChangeUser1, issueChangeUserUnknown));
IssueDto issue = dbTester.issues().insertIssue();
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser();
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid());
IssueChangeDto issueChangeUser2 = newComment(issue).setUserUuid(user2.getUuid());
IssueChangeDto issueChangeUserUnknown = newComment(issue).setUserUuid(uuid);
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser();
userSessionRule.logIn(user2);
- String uuid = randomAlphabetic(30);
+ String uuid = secure().nextAlphabetic(30);
IssueChangeDto issueChangeUser1a = newComment(issue).setUserUuid(user1.getUuid());
IssueChangeDto issueChangeUser1b = newComment(issue).setUserUuid(user1.getUuid());
IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid());
IssueDto issue1 = dbTester.issues().insertIssue();
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser(t -> t.setActive(false));
- String uuid = randomAlphabetic(22);
+ String uuid = secure().nextAlphabetic(22);
dbTester.issues().insertChange(newFieldChange(issue1)
.setUserUuid(user1.getUuid())
.setChangeData(new FieldDiffs()
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
RuleDto javaRule = db.rules().insert(r -> r.setRepositoryKey("javasecurity"));
RuleDto javaScriptRule = db.rules().insert(r -> r.setRepositoryKey("javascript"));
- String ruledescriptionContextKey = randomAlphabetic(6);
+ String ruledescriptionContextKey = secure().nextAlphabetic(6);
IssueDto issueDto = issueDbTester.insertIssue(p -> p.setSeverity("MINOR")
.setManualSeverity(true)
.setMessage("openIssue")
import org.sonarqube.ws.Issues.Issue;
import org.sonarqube.ws.Issues.SearchWsResponse;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.api.resources.Qualifiers.APP;
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insertIssue(rule, project, file);
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName));
ComponentDto branchFile = db.components().insertComponent(newFileDto(branch, project.uuid()));
IssueDto branchIssue = db.issues().insertIssue(rule, branch, branchFile);
ComponentDto project = projectData.getMainBranchComponent();
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName));
ComponentDto branchFile = db.components().insertComponent(newFileDto(branch, project.uuid()));
IssueDto branchIssue = db.issues().insertIssue(rule, branch, branchFile);
ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto pullRequestFile = db.components().insertComponent(newFileDto(pullRequest, project.uuid()));
IssueDto pullRequestIssue = db.issues().insertIssue(rule, pullRequest, pullRequestFile);
@Test
public void fail_when_analysis_is_new_code_period_baseline() {
- String analysisUuid = RandomStringUtils.randomAlphabetic(12);
+ String analysisUuid = RandomStringUtils.secure().nextAlphabetic(12);
ProjectData project = db.components().insertPrivateProject();
SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project.getMainBranchDto()).setUuid(analysisUuid).setLast(false));
db.newCodePeriods().insert(new NewCodePeriodDto()
import static java.lang.String.format;
import static java.lang.String.valueOf;
-import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
private void insertARandomCondition(QualityGateDto qualityGate) {
QualityGateConditionDto condition = new QualityGateConditionDto()
- .setUuid(randomAlphanumeric(40))
- .setMetricUuid(randomAlphanumeric(40))
+ .setUuid(secure().nextAlphanumeric(40))
+ .setMetricUuid(secure().nextAlphanumeric(40))
.setQualityGateUuid(qualityGate.getUuid());
db.getDbClient().gateConditionDao().insert(condition, db.getSession());
db.commit();
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public void return_live_status_when_branch_is_referenced_by_its_key() throws IOException {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
dbClient.snapshotDao().insert(dbSession, newAnalysis(branch)
public void return_live_status_when_pull_request_is_referenced_by_its_key() throws IOException {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String pullRequestKey = RandomStringUtils.randomAlphanumeric(100);
+ String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100);
ComponentDto pr = db.components().insertProjectBranch(mainBranch, branch -> branch.setBranchType(BranchType.PULL_REQUEST)
.setKey(pullRequestKey));
import static java.util.Map.entry;
import static java.util.Map.of;
import static java.util.Map.ofEntries;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
@Test
void bulk_activation() {
int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100);
- String language = randomAlphanumeric(10);
- String repositoryKey = randomAlphanumeric(10);
+ String language = secure().nextAlphanumeric(10);
+ String repositoryKey = secure().nextAlphanumeric(10);
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language));
List<RuleDto> rules = new ArrayList<>();
@Test
void bulk_deactivation() {
int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100);
- String language = randomAlphanumeric(10);
- String repositoryKey = randomAlphanumeric(10);
+ String language = secure().nextAlphanumeric(10);
+ String repositoryKey = secure().nextAlphanumeric(10);
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language));
List<RuleDto> rules = new ArrayList<>();
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
}
private static String newLanguageKey() {
- return randomAlphanumeric(20).toLowerCase();
+ return secure().nextAlphanumeric(20).toLowerCase();
}
}
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
- .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE));
+ .setParam(PARAM_KEY, secure().nextAlphanumeric(UUID_SIZE));
assertThatThrownBy(() -> request.execute())
.isInstanceOf(UnauthorizedException.class);
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
- .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE));
+ .setParam(PARAM_TARGET_KEY, secure().nextAlphanumeric(UUID_SIZE));
assertThatThrownBy(() -> request.execute())
.isInstanceOf(UnauthorizedException.class);
import org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters;
import static java.util.Arrays.asList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
private RuleIndexer ruleIndexer;
private ActiveRuleIndexer activeRuleIndexer;
private WsActionTester ws;
- private Language language = LanguageTesting.newLanguage(randomAlphanumeric(20));
- private String ruleRepository = randomAlphanumeric(5);
+ private Language language = LanguageTesting.newLanguage(secure().nextAlphanumeric(20));
+ private String ruleRepository = secure().nextAlphanumeric(5);
private QProfileTreeImpl qProfileTree;
private SonarQubeVersion sonarQubeVersion;
}
private RuleDto createRule() {
- RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, randomAlphanumeric(5)))
+ RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, secure().nextAlphanumeric(5)))
.setLanguage(language.getKey())
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY);
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
- .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE));
+ .setParam(PARAM_KEY, secure().nextAlphanumeric(UUID_SIZE));
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
public void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
- .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE));
+ .setParam(PARAM_TARGET_KEY, secure().nextAlphanumeric(UUID_SIZE));
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
@Test
public void return_lang_key_field_when_language_name_is_not_available() {
- String unknownLanguage = "unknown_" + randomAlphanumeric(5);
+ String unknownLanguage = "unknown_" + secure().nextAlphanumeric(5);
RuleDto rule = db.rules().insert(r -> r.setLanguage(unknownLanguage));
indexRules();
tuple(ruleParam1.getName(), ruleParam1.getDefaultValue()),
tuple(ruleParam2.getName(), ruleParam2.getDefaultValue()));
- String unknownProfile = "unknown_profile" + randomAlphanumeric(5);
+ String unknownProfile = "unknown_profile" + secure().nextAlphanumeric(5);
assertThatThrownBy(() -> {
ws.newRequest()
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
public void branch() {
ProjectData project = db.components().insertPrivateProject();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.mainBranchUuid()));
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
public void pull_request() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
- String pullRequestKey = randomAlphanumeric(100);
+ String pullRequestKey = secure().nextAlphanumeric(100);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentTesting.newFileDto;
public void raw_from_branch_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.CODEVIEWER, project);
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
userSession.addProjectBranchMapping(project.uuid(), branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Users.CurrentWsResponse;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public void return_homepage_when_set_to_a_branch() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto project = projectData.getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter(branch.uuid()));
userSessionRule.logIn(user).addProjectPermission(USER, projectData.getProjectDto());
import org.sonar.server.ws.WsActionTester;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.user.ws.SetHomepageAction.PARAM_COMPONENT;
@Test
public void set_branch_homepage() {
ComponentDto mainBranch = db.components().insertPublicProject().getMainBranchComponent();
- String branchName = randomAlphanumeric(248);
+ String branchName = secure().nextAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
UserDto user = db.users().insertUser();
userSession.logIn(user);
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void getETag_should_start_with_W_SLASH() {
- assertThat(ETagUtils.getETag(randomAlphanumeric(15))).startsWith("W/");
+ assertThat(ETagUtils.getETag(secure().nextAlphanumeric(15))).startsWith("W/");
}
@Test
public void getETag_should_return_same_value_for_same_input() {
- String input = randomAlphanumeric(200);
+ String input = secure().nextAlphanumeric(200);
assertThat(ETagUtils.getETag(input)).isEqualTo(ETagUtils.getETag(input));
}
}
import org.sonar.db.component.ComponentDto;
import org.sonar.server.ce.queue.BranchSupport.ComponentKey;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@Test
public void createComponentKey_of_main_branch() {
- String projectKey = randomAlphanumeric(12);
+ String projectKey = secure().nextAlphanumeric(12);
ComponentKey componentKey = underTestNoBranch.createComponentKey(projectKey, NO_CHARACTERISTICS);
@Test
public void createComponentKey_whenCharacteristicsIsRandom_returnsComponentKey() {
- String projectKey = randomAlphanumeric(12);
+ String projectKey = secure().nextAlphanumeric(12);
Map<String, String> nonEmptyMap = newRandomNonEmptyMap();
ComponentKey componentKey = underTestWithBranch.createComponentKey(projectKey, nonEmptyMap);
@Test
public void createComponentKey_whenCharacteristicsIsBranchRelated_delegates() {
- String projectKey = randomAlphanumeric(12);
+ String projectKey = secure().nextAlphanumeric(12);
Map<String, String> nonEmptyMap = Map.of(PULL_REQUEST, "PR-2");
ComponentKey expected = mock(ComponentKey.class);
when(branchSupportDelegate.createComponentKey(projectKey, nonEmptyMap)).thenReturn(expected);
public static Object[][] nullOrNonEmpty() {
return new Object[][] {
{null},
- {randomAlphabetic(5)},
+ {secure().nextAlphabetic(5)},
};
}
import org.sonar.server.common.component.NewComponent;
import static com.google.common.base.Strings.repeat;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.resources.Qualifiers.PROJECT;
public void isProject_shouldReturnFalse_whenQualifierIsNotProject() {
NewComponent newComponent = underTest.setKey(KEY)
.setName(NAME)
- .setQualifier(randomAlphabetic(4))
+ .setQualifier(secure().nextAlphabetic(4))
.build();
assertThat(newComponent.isProject()).isFalse();
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonarqube.ws.client.component.ComponentsWsParameters.CONTROLLER_COMPONENTS;
public class ComponentsWsTest {
- private final String actionKey = randomAlphanumeric(10);
+ private final String actionKey = secure().nextAlphanumeric(10);
private final ComponentsWsAction action = new ComponentsWsAction() {
@Override
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.concat;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder;
private Health randomHealth() {
Health.Builder healthBuilder = Health.builder();
healthBuilder.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]);
- IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).forEach(healthBuilder::addCause);
+ IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).forEach(healthBuilder::addCause);
return healthBuilder.build();
}
.setDetails(
NodeDetails.newNodeDetailsBuilder()
.setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION)
- .setName(randomAlphanumeric(3))
- .setHost(randomAlphanumeric(4))
+ .setName(secure().nextAlphanumeric(3))
+ .setHost(secure().nextAlphanumeric(4))
.setPort(1 + random.nextInt(344))
.setStartedAt(1 + random.nextInt(999))
.build())
return NodeDetails.newNodeDetailsBuilder()
.setType(NodeDetails.Type.APPLICATION)
.setName(nodeName)
- .setHost(randomAlphanumeric(4))
+ .setHost(secure().nextAlphanumeric(4))
.setPort(3000)
.setStartedAt(1_000L)
.build();
import org.sonar.server.common.health.NodeHealthCheck;
import org.sonar.server.platform.NodeInformation;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.same;
@Test
public void checkNode_returns_causes_of_all_NodeHealthCheck_whichever_their_status() {
NodeHealthCheck[] nodeHealthChecks = IntStream.range(0, 1 + random.nextInt(20))
- .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new)))
+ .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).toArray(String[]::new)))
.map(NodeHealthCheck.class::cast)
.toArray(NodeHealthCheck[]::new);
String[] expected = Arrays.stream(nodeHealthChecks).map(NodeHealthCheck::check).flatMap(s -> s.getCauses().stream()).toArray(String[]::new);
public void checkCluster_returns_causes_of_all_ClusterHealthChecks_whichever_their_status() {
when(nodeInformation.isStandalone()).thenReturn(false);
List<String[]> causesGroups = IntStream.range(0, 1 + random.nextInt(20))
- .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new))
+ .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).toArray(String[]::new))
.toList();
ClusterHealthCheck[] clusterHealthChecks = causesGroups.stream()
.map(HardcodedHealthClusterCheck::new)
.setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)])
.setDetails(newNodeDetailsBuilder()
.setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH)
- .setName(randomAlphanumeric(10))
- .setHost(randomAlphanumeric(5))
+ .setName(secure().nextAlphanumeric(10))
+ .setHost(secure().nextAlphanumeric(5))
.setPort(1 + random.nextInt(333))
.setStartedAt(1 + random.nextInt(444))
.build())
import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Test;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.ThrowableAssert.ThrowingCallable;
private final Random random = new Random();
private final Health.Status anyStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)];
- private final Set<String> randomCauses = IntStream.range(0, random.nextInt(5)).mapToObj(s -> randomAlphanumeric(3)).collect(Collectors.toSet());
+ private final Set<String> randomCauses = IntStream.range(0, random.nextInt(5)).mapToObj(s -> secure().nextAlphanumeric(3)).collect(Collectors.toSet());
@Test
public void build_throws_NPE_if_status_is_null() {
import org.sonar.process.cluster.hz.HazelcastMember;
import static java.lang.String.valueOf;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
Server server = mock(Server.class);
NetworkUtils networkUtils = mock(NetworkUtils.class);
// settings required by NodeHealthProvider
- mapSettings.setProperty("sonar.cluster.node.name", randomAlphanumeric(3));
+ mapSettings.setProperty("sonar.cluster.node.name", secure().nextAlphanumeric(3));
mapSettings.setProperty("sonar.cluster.node.port", valueOf(1 + random.nextInt(10)));
when(server.getStartedAt()).thenReturn(new Date());
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(12));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(12));
// upper level dependencies
container.add(
mock(System2.class),
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@Test
public void constructor_thows_NPE_if_NetworkUtils_getHostname_returns_null() {
- mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils))
.isInstanceOf(NullPointerException.class);
@Test
public void constructor_throws_ISE_if_node_port_property_is_not_set() {
- mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23));
+ mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(23));
assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils))
.isInstanceOf(IllegalStateException.class)
public void get_returns_HEALTH_status_and_causes_from_HealthChecker_checkNode() {
setRequiredPropertiesForConstructor();
setStartedAt();
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4));
Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)];
- String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> randomAlphabetic(55)).toArray(String[]::new);
+ String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> secure().nextAlphabetic(55)).toArray(String[]::new);
Health.Builder healthBuilder = Health.builder()
.setStatus(randomStatus);
Arrays.stream(expected).forEach(healthBuilder::addCause);
public void get_returns_APPLICATION_type() {
setRequiredPropertiesForConstructor();
setStartedAt();
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(23));
when(healthChecker.checkNode()).thenReturn(Health.builder()
.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)])
.build());
@Test
public void get_returns_name_and_port_from_properties_at_constructor_time() {
- String name = randomAlphanumeric(3);
+ String name = secure().nextAlphanumeric(3);
int port = 1 + random.nextInt(4);
mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), name);
mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), port);
when(healthChecker.checkNode()).thenReturn(Health.builder()
.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)])
.build());
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(3));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(3));
NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils);
NodeHealth nodeHealth = underTest.get();
@Test
public void get_returns_host_from_property_if_set_at_constructor_time() {
- String host = randomAlphanumeric(4);
- mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ String host = secure().nextAlphanumeric(4);
+ mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4));
mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), host);
setStartedAt();
assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host);
// change values in properties
- mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(66));
+ mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(66));
NodeHealth newNodeHealth = underTest.get();
}
private void getReturnsHostnameFromNetworkUtils(String hostPropertyValue) {
- String host = randomAlphanumeric(3);
+ String host = secure().nextAlphanumeric(3);
setRequiredPropertiesForConstructor();
if (hostPropertyValue != null) {
mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue);
assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host);
// change hostname
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4));
NodeHealth newNodeHealth = underTest.get();
@Test
public void get_returns_started_from_server_startedAt_at_constructor_time() {
setRequiredPropertiesForConstructor();
- when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4));
+ when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4));
Date date = new Date();
when(server.getStartedAt()).thenReturn(date);
when(healthChecker.checkNode()).thenReturn(Health.builder()
}
private void setRequiredPropertiesForConstructor() {
- mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
+ mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3));
mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4));
}
}
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class HotspotsWsTest {
@Test
public void define_controller() {
String[] actionKeys = IntStream.range(0, 1 + new Random().nextInt(12))
- .mapToObj(i -> i + randomAlphanumeric(10))
+ .mapToObj(i -> i + secure().nextAlphanumeric(10))
.toArray(String[]::new);
HotspotsWsAction[] actions = Arrays.stream(actionKeys)
.map(actionKey -> new HotspotsWsAction() {
import static java.lang.System.currentTimeMillis;
import static java.util.stream.Collectors.toList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentMatchers.any;
private static IssueDto createIssue() {
RuleDto ruleDto = newRule();
- String projectUuid = "project_uuid_" + randomAlphanumeric(5);
+ String projectUuid = "project_uuid_" + secure().nextAlphanumeric(5);
ComponentDto projectDto = newPrivateProjectDto();
projectDto.setBranchUuid(projectUuid);
- return newIssue(ruleDto, projectUuid, "project_key_" + randomAlphanumeric(5), projectDto);
+ return newIssue(ruleDto, projectUuid, "project_key_" + secure().nextAlphanumeric(5), projectDto);
}
@Test
void formatOperation_should_add_branch_on_issue() {
- String branchName = randomAlphanumeric(5);
+ String branchName = secure().nextAlphanumeric(5);
searchResponseData = newSearchResponseDataBranch(branchName);
Operation result = searchResponseFormat.formatOperation(searchResponseData, true);
assertThat(result.getIssue().getBranch()).isEqualTo(branchName);
@Test
void formatOperation_should_add_external_rule_engine_on_issue() {
issueDto.setExternal(true);
- String expected = randomAlphanumeric(5);
- issueDto.setRuleKey(EXTERNAL_RULE_REPO_PREFIX + expected, randomAlphanumeric(5));
+ String expected = secure().nextAlphanumeric(5);
+ issueDto.setRuleKey(EXTERNAL_RULE_REPO_PREFIX + expected, secure().nextAlphanumeric(5));
Operation result = searchResponseFormat.formatOperation(searchResponseData, true);
@Test
void formatOperation_should_add_scope_main_on_issue_when_not_unit_test_file() {
- componentDto.setQualifier(randomAlphanumeric(5));
+ componentDto.setQualifier(secure().nextAlphanumeric(5));
Operation result = searchResponseFormat.formatOperation(searchResponseData, true);
issueDto = newIssue(ruleDto, component.branchUuid(), component.getKey(), component)
.setType(CODE_SMELL)
.setCleanCodeAttribute(CleanCodeAttribute.CLEAR)
- .setRuleDescriptionContextKey("context_key_" + randomAlphanumeric(5))
+ .setRuleDescriptionContextKey("context_key_" + secure().nextAlphanumeric(5))
.setAssigneeUuid(userDto.getUuid())
- .setResolution("resolution_" + randomAlphanumeric(5))
+ .setResolution("resolution_" + secure().nextAlphanumeric(5))
.setIssueCreationDate(new Date(currentTimeMillis() - 2_000))
.setIssueUpdateDate(new Date(currentTimeMillis() - 1_000))
.setIssueCloseDate(new Date(currentTimeMillis()));
import org.sonar.api.server.ws.WebService;
import org.sonar.core.documentation.DocumentationLinkGenerator;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class NewCodePeriodsWsTest {
- private String actionKey = randomAlphanumeric(10);
+ private String actionKey = secure().nextAlphanumeric(10);
private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class);
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.ThrowableAssert.ThrowingCallable;
Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)];
Health.Builder builder = Health.builder()
.setStatus(randomStatus);
- IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause);
+ IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.secure().nextAlphanumeric(3)).forEach(builder::addCause);
Health health = builder.build();
when(healthChecker.checkNode()).thenReturn(health);
when(nodeInformation.isStandalone()).thenReturn(true);
public void response_contains_status_and_causes_from_HealthChecker_checkCluster_when_standalone() {
authenticateWithRandomMethod();
Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)];
- String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new);
+ String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new);
Health.Builder healthBuilder = Health.builder()
.setStatus(randomStatus);
Arrays.stream(causes).forEach(healthBuilder::addCause);
private NodeHealth randomNodeHealth() {
NodeHealth.Builder builder = newNodeHealthBuilder()
.setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]);
- IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause);
+ IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause);
return builder.setDetails(
newNodeDetailsBuilder()
.setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH)
- .setName(randomAlphanumeric(3))
- .setHost(randomAlphanumeric(4))
+ .setName(secure().nextAlphanumeric(3))
+ .setHost(secure().nextAlphanumeric(4))
.setPort(1 + random.nextInt(3))
.setStartedAt(1 + random.nextInt(23))
.build())
private NodeHealth randomNodeHealth(NodeDetails.Type type, String name, String host, int port, long started) {
NodeHealth.Builder builder = newNodeHealthBuilder()
.setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]);
- IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause);
+ IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause);
return builder.setDetails(
newNodeDetailsBuilder()
.setType(type)
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.System;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)];
Health.Builder builder = Health.builder()
.setStatus(randomStatus);
- IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause);
+ IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.secure().nextAlphanumeric(3)).forEach(builder::addCause);
Health health = builder.build();
when(healthChecker.checkNode()).thenReturn(health);
TestRequest request = underTest.newRequest();
public void response_contains_status_and_causes_from_HealthChecker_checkCluster() {
authenticateWithPasscode();
Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)];
- String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new);
+ String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new);
Health.Builder healthBuilder = Health.builder()
.setStatus(randomStatus);
Arrays.stream(causes).forEach(healthBuilder::addCause);
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Before
public void setUp() {
- when(server.getPublicRootUrl()).thenReturn("http://" + randomAlphanumeric(10));
+ when(server.getPublicRootUrl()).thenReturn("http://" + secure().nextAlphanumeric(10));
}
@Test
@Test
public void notification_contains_many_profiles() {
- String profileName1 = "profile1_" + randomAlphanumeric(20);
- String languageKey1 = "langkey1_" + randomAlphanumeric(20);
- String languageName1 = "langName1_" + randomAlphanumeric(20);
- String profileName2 = "profile2_" + randomAlphanumeric(20);
- String languageKey2 = "langkey2_" + randomAlphanumeric(20);
- String languageName2 = "langName2_" + randomAlphanumeric(20);
+ String profileName1 = "profile1_" + secure().nextAlphanumeric(20);
+ String languageKey1 = "langkey1_" + secure().nextAlphanumeric(20);
+ String languageName1 = "langName1_" + secure().nextAlphanumeric(20);
+ String profileName2 = "profile2_" + secure().nextAlphanumeric(20);
+ String languageKey2 = "langkey2_" + secure().nextAlphanumeric(20);
+ String languageName2 = "langName2_" + secure().nextAlphanumeric(20);
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName1)
@Test
public void notification_contains_profiles_sorted_by_language_then_by_profile_name() {
- String languageKey1 = "langkey1_" + randomAlphanumeric(20);
- String languageName1 = "langName1_" + randomAlphanumeric(20);
- String languageKey2 = "langKey2_" + randomAlphanumeric(20);
- String languageName2 = "langName2_" + randomAlphanumeric(20);
- String profileName1 = "profile1_" + randomAlphanumeric(20);
- String profileName2 = "profile2_" + randomAlphanumeric(20);
- String profileName3 = "profile3_" + randomAlphanumeric(20);
+ String languageKey1 = "langkey1_" + secure().nextAlphanumeric(20);
+ String languageName1 = "langName1_" + secure().nextAlphanumeric(20);
+ String languageKey2 = "langKey2_" + secure().nextAlphanumeric(20);
+ String languageName2 = "langName2_" + secure().nextAlphanumeric(20);
+ String profileName1 = "profile1_" + secure().nextAlphanumeric(20);
+ String profileName2 = "profile2_" + secure().nextAlphanumeric(20);
+ String profileName3 = "profile3_" + secure().nextAlphanumeric(20);
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder().setProfileName(profileName3).setLanguageKey(languageKey2).setLanguageName(languageName2).build())
.addProfile(Profile.newBuilder().setProfileName(profileName2).setLanguageKey(languageKey1).setLanguageName(languageName1).build())
}
private static String newProfileName() {
- return "profileName_" + randomAlphanumeric(20);
+ return "profileName_" + secure().nextAlphanumeric(20);
}
private static String newLanguageName() {
- return "languageName_" + randomAlphanumeric(20);
+ return "languageName_" + secure().nextAlphanumeric(20);
}
private static String newLanguageKey() {
- return "languageKey_" + randomAlphanumeric(20);
+ return "languageKey_" + secure().nextAlphanumeric(20);
}
}
import org.sonar.api.notifications.Notification;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
@Test
public void serialize_and_parse_single_profile() {
- String profileName = randomAlphanumeric(20);
- String languageKey = randomAlphanumeric(20);
- String languageName = randomAlphanumeric(20);
+ String profileName = secure().nextAlphanumeric(20);
+ String languageKey = secure().nextAlphanumeric(20);
+ String languageName = secure().nextAlphanumeric(20);
int newRules = RANDOM.nextInt(5000);
int updatedRules = RANDOM.nextInt(5000);
int removedRules = RANDOM.nextInt(5000);
@Test
public void serialize_and_parse_multiple_profiles() {
- String profileName1 = randomAlphanumeric(20);
- String languageKey1 = randomAlphanumeric(20);
- String languageName1 = randomAlphanumeric(20);
- String profileName2 = randomAlphanumeric(20);
- String languageKey2 = randomAlphanumeric(20);
- String languageName2 = randomAlphanumeric(20);
+ String profileName1 = secure().nextAlphanumeric(20);
+ String languageKey1 = secure().nextAlphanumeric(20);
+ String languageName1 = secure().nextAlphanumeric(20);
+ String profileName2 = secure().nextAlphanumeric(20);
+ String languageKey2 = secure().nextAlphanumeric(20);
+ String languageName2 = secure().nextAlphanumeric(20);
BuiltInQPChangeNotification notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
@Test
public void serialize_and_parse_max_values() {
- String profileName = randomAlphanumeric(20);
- String languageKey = randomAlphanumeric(20);
- String languageName = randomAlphanumeric(20);
+ String profileName = secure().nextAlphanumeric(20);
+ String languageKey = secure().nextAlphanumeric(20);
+ String languageName = secure().nextAlphanumeric(20);
int newRules = Integer.MAX_VALUE;
int updatedRules = Integer.MAX_VALUE;
int removedRules = Integer.MAX_VALUE;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
import static java.util.Arrays.asList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
}
private static String randomLowerCaseText() {
- return randomAlphanumeric(20).toLowerCase();
+ return secure().nextAlphanumeric(20).toLowerCase();
}
private void enableNotificationInGlobalSettings() {
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.ServletFilterHandler;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class UsersWsTest {
@Override
public void define(WebService.NewController context) {
- context.createAction(randomAlphanumeric(10)).setHandler(ServletFilterHandler.INSTANCE);
+ context.createAction(secure().nextAlphanumeric(10)).setHandler(ServletFilterHandler.INSTANCE);
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.apache.commons.lang3.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DataProvider
public static Object[][] wrongFormatWithDatabaseId() {
String onlySplitChar = repeat(SPLIT_CHARACTER + "", DATABASE_ID_LENGTH);
- String startWithSplitChar = SPLIT_CHARACTER + randomAlphabetic(DATABASE_ID_LENGTH - 1);
+ String startWithSplitChar = SPLIT_CHARACTER + secure().nextAlphabetic(DATABASE_ID_LENGTH - 1);
Stream<String> databaseIds = Stream.of(
OLD_UUID_FORMAT,
- randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH),
- randomAlphabetic(UUID_DATASET_ID_LENGTH),
+ secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH),
+ secure().nextAlphabetic(UUID_DATASET_ID_LENGTH),
repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH),
repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH));
.flatMap(datasetId -> Stream.of(
startWithSplitChar + SPLIT_CHARACTER + datasetId,
onlySplitChar + SPLIT_CHARACTER + datasetId,
- startWithSplitChar + randomAlphabetic(1) + datasetId,
- onlySplitChar + randomAlphabetic(1) + datasetId))
+ startWithSplitChar + secure().nextAlphabetic(1) + datasetId,
+ onlySplitChar + secure().nextAlphabetic(1) + datasetId))
.flatMap(serverId -> Stream.of(
serverId,
" " + serverId,
public static Object[][] validOldFormatServerIds() {
return new Object[][] {
{OLD_UUID_FORMAT},
- {randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
{repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)},
- {randomAlphabetic(UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)},
{repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)}
};
}
@DataProvider
public static Object[][] validServerIdWithDatabaseId() {
return new Object[][] {
- {randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
- {randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)},
- {randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)},
- {randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)},
- {randomAlphabetic(DATABASE_ID_LENGTH), OLD_UUID_FORMAT},
+ {secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)},
+ {secure().nextAlphabetic(DATABASE_ID_LENGTH), OLD_UUID_FORMAT},
};
}
@Test
public void parse_does_not_support_deprecated_server_id_with_database_id() {
- assertThatThrownBy(() -> ServerId.parse(randomAlphabetic(DATABASE_ID_LENGTH) + SPLIT_CHARACTER + randomAlphabetic(DEPRECATED_SERVER_ID_LENGTH)))
+ assertThatThrownBy(() -> ServerId.parse(secure().nextAlphabetic(DATABASE_ID_LENGTH) + SPLIT_CHARACTER + secure().nextAlphabetic(DEPRECATED_SERVER_ID_LENGTH)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("serverId does not have a supported length");
}
@Test
public void of_throws_NPE_if_datasetId_is_null() {
- assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), null))
+ assertThatThrownBy(() -> ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void of_throws_IAE_if_datasetId_is_empty() {
- assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), ""))
+ assertThatThrownBy(() -> ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal datasetId length (0)");
}
@Test
public void of_throws_IAE_if_databaseId_is_empty() {
- assertThatThrownBy(() -> ServerId.of("", randomAlphabetic(UUID_DATASET_ID_LENGTH)))
+ assertThatThrownBy(() -> ServerId.of("", secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal databaseId length (0)");
}
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void of_accepts_null_databaseId(int datasetIdLength) {
- String datasetId = randomAlphabetic(datasetIdLength);
+ String datasetId = secure().nextAlphabetic(datasetIdLength);
ServerId serverId = ServerId.of(null, datasetId);
assertThat(serverId.getDatabaseId()).isEmpty();
@Test
@UseDataProvider("illegalDatabaseIdLengths")
public void of_throws_IAE_if_databaseId_length_is_not_8(int illegalDatabaseIdLengths) {
- String databaseId = randomAlphabetic(illegalDatabaseIdLengths);
- String datasetId = randomAlphabetic(UUID_DATASET_ID_LENGTH);
+ String databaseId = secure().nextAlphabetic(illegalDatabaseIdLengths);
+ String datasetId = secure().nextAlphabetic(UUID_DATASET_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(databaseId, datasetId))
.isInstanceOf(IllegalArgumentException.class)
@Test
@UseDataProvider("illegalDatasetIdLengths")
public void of_throws_IAE_if_datasetId_length_is_not_8(int illegalDatasetIdLengths) {
- String datasetId = randomAlphabetic(illegalDatasetIdLengths);
- String databaseId = randomAlphabetic(DATABASE_ID_LENGTH);
+ String datasetId = secure().nextAlphabetic(illegalDatasetIdLengths);
+ String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(databaseId, datasetId))
.isInstanceOf(IllegalArgumentException.class)
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void equals_is_based_on_databaseId_and_datasetId(int datasetIdLength) {
- String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
- String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
- String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a';
- String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b';
+ String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
+ String otherDatabaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
+ String datasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'a';
+ String otherDatasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'b';
ServerId newServerId = ServerId.of(databaseId, datasetId);
assertThat(newServerId)
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void hashcode_is_based_on_databaseId_and_datasetId(int datasetIdLength) {
- String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
- String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
- String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a';
- String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b';
+ String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
+ String otherDatabaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
+ String datasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'a';
+ String otherDatasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'b';
ServerId newServerId = ServerId.of(databaseId, datasetId);
assertThat(newServerId)
import org.sonar.api.utils.System2;
import static java.util.Collections.singletonList;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.ThrowableAssert.ThrowingCallable;
public void set_throws_NPE_if_key_is_null() {
MapSettings underTest = new MapSettings();
- expectKeyNullNPE(() -> underTest.set(null, randomAlphanumeric(3)));
+ expectKeyNullNPE(() -> underTest.set(null, secure().nextAlphanumeric(3)));
}
@Test
public void set_throws_NPE_if_value_is_null() {
MapSettings underTest = new MapSettings();
- assertThatThrownBy(() -> underTest.set(randomAlphanumeric(3), null))
+ assertThatThrownBy(() -> underTest.set(secure().nextAlphanumeric(3), null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
public void set_accepts_empty_value_and_trims_it() {
MapSettings underTest = new MapSettings();
Random random = new Random();
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
underTest.set(key, blank(random));
@Test
public void set_property_string_throws_NPE_if_key_is_null() {
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build())));
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
setPropertyCaller.accept(underTest, blankBefore + key + blankAfter);
@Test
public void set_property_string_array_trims_key() {
- String key = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build())));
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
- String key = randomAlphanumeric(3);
- String value = randomAlphanumeric(3);
+ String key = secure().nextAlphanumeric(3);
+ String value = secure().nextAlphanumeric(3);
underTest.setProperty(key, blankBefore + value + blankAfter);
import org.junit.runner.RunWith;
import static java.util.function.UnaryOperator.identity;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;
@DataProvider
public static Object[][] plains() {
return new Object[][] {
- {randomAlphanumeric(1)},
- {randomAlphanumeric(2)},
- {randomAlphanumeric(3 + new Random().nextInt(5))}
+ {secure().nextAlphanumeric(1)},
+ {secure().nextAlphanumeric(2)},
+ {secure().nextAlphanumeric(3 + new Random().nextInt(5))}
};
}
@Test
public void trimAccordingToStringTrim() {
- String str = randomAlphanumeric(4);
+ String str = secure().nextAlphanumeric(4);
for (int i = 0; i <= ' '; i++) {
String prefixed = (char) i + str;
String suffixed = (char) i + str;
String threePlusEmpty = randomTrimmedChars(3 + random.nextInt(5), random);
String onePlusEmpty = randomTrimmedChars(1 + random.nextInt(5), random);
- String plain = randomAlphanumeric(1);
- String plainWithtrimmable = randomAlphanumeric(2) + onePlusEmpty + randomAlphanumeric(3);
- String quotedWithSeparator = '"' + randomAlphanumeric(3) + ',' + randomAlphanumeric(2) + '"';
- String quotedWithDoubleSeparator = '"' + randomAlphanumeric(3) + ",," + randomAlphanumeric(2) + '"';
- String quotedWithtrimmable = '"' + randomAlphanumeric(3) + onePlusEmpty + randomAlphanumeric(2) + '"';
+ String plain = secure().nextAlphanumeric(1);
+ String plainWithtrimmable = secure().nextAlphanumeric(2) + onePlusEmpty + secure().nextAlphanumeric(3);
+ String quotedWithSeparator = '"' + secure().nextAlphanumeric(3) + ',' + secure().nextAlphanumeric(2) + '"';
+ String quotedWithDoubleSeparator = '"' + secure().nextAlphanumeric(3) + ",," + secure().nextAlphanumeric(2) + '"';
+ String quotedWithtrimmable = '"' + secure().nextAlphanumeric(3) + onePlusEmpty + secure().nextAlphanumeric(2) + '"';
String[] empties = {oneEmpty, twoEmpty, threePlusEmpty};
String[] strings = {plain, plainWithtrimmable,
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
@Test
void fail_with_too_long_version() {
- String version = randomAlphabetic(101);
+ String version = secure().nextAlphabetic(101);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, version);
@Test
void fail_with_too_long_buildString() {
- String buildString = randomAlphabetic(101);
+ String buildString = secure().nextAlphabetic(101);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString);
@Test
void getProjectVersion_contains_value_of_property() {
- String value = RandomStringUtils.randomAlphabetic(10);
+ String value = RandomStringUtils.secure().nextAlphabetic(10);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, value);
@Test
void getBuildString_contains_value_of_property() {
- String value = RandomStringUtils.randomAlphabetic(10);
+ String value = RandomStringUtils.secure().nextAlphabetic(10);
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01");
settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, value);
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.issue.impact.Severity.BLOCKER;
ExternalIssueReport.Issue input = new ExternalIssueReport.Issue();
input.primaryLocation = new ExternalIssueReport.Location();
input.primaryLocation.filePath = sourceFile.getProjectRelativePath();
- input.primaryLocation.message = randomAlphabetic(5);
+ input.primaryLocation.message = secure().nextAlphabetic(5);
runOn(input);
input.type = "BUG";
input.primaryLocation = new ExternalIssueReport.Location();
input.primaryLocation.filePath = sourceFile.getProjectRelativePath();
- input.primaryLocation.message = randomAlphabetic(5);
+ input.primaryLocation.message = secure().nextAlphabetic(5);
report.issues = new ExternalIssueReport.Issue[]{input};
ExternalIssueImporter underTest = new ExternalIssueImporter(this.context, report);
private ExternalIssueReport.Issue newIssue(@Nullable ExternalIssueReport.TextRange textRange) {
ExternalIssueReport.Issue input = new ExternalIssueReport.Issue();
- input.engineId = randomAlphabetic(5);
- input.ruleId = randomAlphabetic(5);
+ input.engineId = secure().nextAlphabetic(5);
+ input.ruleId = secure().nextAlphabetic(5);
input.severity = "CRITICAL";
input.type = "BUG";
input.effortMinutes = random.nextInt(Integer.MAX_VALUE);
input.primaryLocation = new ExternalIssueReport.Location();
input.primaryLocation.filePath = sourceFile.getProjectRelativePath();
- input.primaryLocation.message = randomAlphabetic(5);
+ input.primaryLocation.message = secure().nextAlphabetic(5);
input.primaryLocation.textRange = textRange;
return input;
}
import org.sonar.scanner.scm.ScmRevision;
import static java.util.Collections.emptyMap;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
@DataProvider
public static Object[][] projectVersions() {
- String version = randomAlphabetic(15);
+ String version = secure().nextAlphabetic(15);
return new Object[][] {
{null, ""},
{"", ""},
@DataProvider
public static Object[][] buildStrings() {
- String randomBuildString = randomAlphabetic(15);
+ String randomBuildString = secure().nextAlphabetic(15);
return new Object[][] {
{null, ""},
{"", ""},
import org.sonar.api.batch.fs.internal.SensorStrategy;
import static org.apache.commons.lang3.RandomStringUtils.random;
-import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
+import static org.apache.commons.lang3.RandomStringUtils.secure;
import static org.assertj.core.api.Assertions.assertThat;
public class ChangedFileTest {
random(5),
InputFile.Type.MAIN,
random(5),
- Integer.parseInt(randomNumeric(5)),
+ Integer.parseInt(secure().nextNumeric(5)),
new SensorStrategy(),
oldRelativePath);
}
@Test
public void systemPassCode_sets_header_when_value_is_not_null() throws InterruptedException {
answerHelloWorld();
- String systemPassCode = new Random().nextBoolean() ? "" : RandomStringUtils.randomAlphanumeric(21);
+ String systemPassCode = new Random().nextBoolean() ? "" : RandomStringUtils.secure().nextAlphanumeric(21);
underTest = HttpConnector.newBuilder()
.url(serverUrl)
.systemPassCode(systemPassCode)