repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.config.internal;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.util.function.UnaryOperator.identity;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
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;
import static org.sonar.api.config.internal.MultivalueProperty.trimFieldsAndRemoveEmptyFields;
@RunWith(DataProviderRunner.class)
public class MultivaluePropertyTest {
private static final String[] EMPTY_STRING_ARRAY = {};
@Test
@UseDataProvider("testParseAsCsv")
public void parseAsCsv_for_coverage(String value, String[] expected) {
// parseAsCsv is extensively tested in org.sonar.server.config.ConfigurationProviderTest
assertThat(parseAsCsv("key", value))
.isEqualTo(parseAsCsv("key", value, identity()))
.isEqualTo(expected);
}
@Test
public void parseAsCsv_fails_with_ISE_if_value_can_not_be_parsed() {
assertThatThrownBy(() -> parseAsCsv("multi", "\"a ,b"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Property: 'multi' doesn't contain a valid CSV value: '\"a ,b'");
}
@DataProvider
public static Object[][] testParseAsCsv() {
return new Object[][] {
{"a", arrayOf("a")},
{" a", arrayOf("a")},
{"a ", arrayOf("a")},
{" a, b", arrayOf("a", "b")},
{"a,b ", arrayOf("a", "b")},
{"a,,,b,c,,d", arrayOf("a", "b", "c", "d")},
{" , \n ,, \t", EMPTY_STRING_ARRAY},
{"\" a\"", arrayOf(" a")},
{"\",\"", arrayOf(",")},
// escaped quote in quoted field
{"\"\"\"\"", arrayOf("\"")}
};
}
private static String[] arrayOf(String... strs) {
return strs;
}
@Test
public void trimFieldsAndRemoveEmptyFields_throws_NPE_if_arg_is_null() {
assertThatThrownBy(() -> trimFieldsAndRemoveEmptyFields(null))
.isInstanceOf(NullPointerException.class);
}
@Test
@UseDataProvider("plains")
public void trimFieldsAndRemoveEmptyFields_ignores_EmptyFields(String str) {
assertThat(trimFieldsAndRemoveEmptyFields("")).isEmpty();
assertThat(trimFieldsAndRemoveEmptyFields(str)).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str)).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ',')).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(",,," + str)).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ",,,")).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ',' + str)).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ",,," + str)).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str + ',' + str)).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields("," + str + ",,," + str)).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(",,," + str + ",,," + str)).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ',' + str + ',')).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ",,," + str + ",")).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ",,," + str + ",,")).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str + ',' + str + ',')).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(",," + str + ',' + str + ',')).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str + ",," + str + ',')).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str + ',' + str + ",,")).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(",,," + str + ",,," + str + ",,")).isEqualTo(str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ',' + str + ',' + str)).isEqualTo(str + ',' + str + ',' + str);
assertThat(trimFieldsAndRemoveEmptyFields(str + ',' + str + ',' + str)).isEqualTo(str + ',' + str + ',' + str);
}
@DataProvider
public static Object[][] plains() {
return new Object[][] {
{randomAlphanumeric(1)},
{randomAlphanumeric(2)},
{randomAlphanumeric(3 + new Random().nextInt(5))}
};
}
@Test
@UseDataProvider("emptyAndtrimmable")
public void trimFieldsAndRemoveEmptyFields_ignores_empty_fields_and_trims_fields(String empty, String trimmable) {
String expected = trimmable.trim();
assertThat(empty.trim()).isEmpty();
assertThat(trimFieldsAndRemoveEmptyFields(trimmable)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ',' + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ",," + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ',' + trimmable)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ",," + trimmable)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ',' + trimmable + ',' + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ",," + trimmable + ",,," + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ',' + empty + ',' + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ",," + empty + ",,," + empty)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ',' + empty + ',' + trimmable)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(empty + ",,,," + empty + ",," + trimmable)).isEqualTo(expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ',' + trimmable)).isEqualTo(expected + ',' + expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + ',' + trimmable + ',' + trimmable)).isEqualTo(expected + ',' + expected + ',' + expected);
assertThat(trimFieldsAndRemoveEmptyFields(trimmable + "," + trimmable + ',' + trimmable)).isEqualTo(expected + ',' + expected + ',' + expected);
}
@Test
public void trimAccordingToStringTrim() {
String str = randomAlphanumeric(4);
for (int i = 0; i <= ' '; i++) {
String prefixed = (char) i + str;
String suffixed = (char) i + str;
String both = (char) i + str + (char) i;
assertThat(trimFieldsAndRemoveEmptyFields(prefixed)).isEqualTo(prefixed.trim());
assertThat(trimFieldsAndRemoveEmptyFields(suffixed)).isEqualTo(suffixed.trim());
assertThat(trimFieldsAndRemoveEmptyFields(both)).isEqualTo(both.trim());
}
}
@DataProvider
public static Object[][] emptyAndtrimmable() {
Random random = new Random();
String oneEmpty = randomTrimmedChars(1, random);
String twoEmpty = randomTrimmedChars(2, random);
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[] empties = {oneEmpty, twoEmpty, threePlusEmpty};
String[] strings = {plain, plainWithtrimmable,
onePlusEmpty + plain, plain + onePlusEmpty, onePlusEmpty + plain + onePlusEmpty,
onePlusEmpty + plainWithtrimmable, plainWithtrimmable + onePlusEmpty, onePlusEmpty + plainWithtrimmable + onePlusEmpty,
onePlusEmpty + quotedWithSeparator, quotedWithSeparator + onePlusEmpty, onePlusEmpty + quotedWithSeparator + onePlusEmpty,
onePlusEmpty + quotedWithDoubleSeparator, quotedWithDoubleSeparator + onePlusEmpty, onePlusEmpty + quotedWithDoubleSeparator + onePlusEmpty,
onePlusEmpty + quotedWithtrimmable, quotedWithtrimmable + onePlusEmpty, onePlusEmpty + quotedWithtrimmable + onePlusEmpty
};
Object[][] res = new Object[empties.length * strings.length][2];
int i = 0;
for (String empty : empties) {
for (String string : strings) {
res[i][0] = empty;
res[i][1] = string;
i++;
}
}
return res;
}
@Test
@UseDataProvider("emptys")
public void trimFieldsAndRemoveEmptyFields_quotes_allow_to_preserve_fields(String empty) {
String quotedEmpty = '"' + empty + '"';
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty)).isEqualTo(quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(',' + quotedEmpty)).isEqualTo(quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty + ',')).isEqualTo(quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(',' + quotedEmpty + ',')).isEqualTo(quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty + ',' + quotedEmpty)).isEqualTo(quotedEmpty + ',' + quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty + ",," + quotedEmpty)).isEqualTo(quotedEmpty + ',' + quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty + ',' + quotedEmpty + ',' + quotedEmpty)).isEqualTo(quotedEmpty + ',' + quotedEmpty + ',' + quotedEmpty);
}
@DataProvider
public static Object[][] emptys() {
Random random = new Random();
return new Object[][] {
{randomTrimmedChars(1, random)},
{randomTrimmedChars(2, random)},
{randomTrimmedChars(3 + random.nextInt(5), random)}
};
}
@Test
public void trimFieldsAndRemoveEmptyFields_supports_escaped_quote_in_quotes() {
assertThat(trimFieldsAndRemoveEmptyFields("\"f\"\"oo\"")).isEqualTo("\"f\"\"oo\"");
assertThat(trimFieldsAndRemoveEmptyFields("\"f\"\"oo\",\"bar\"\"\"")).isEqualTo("\"f\"\"oo\",\"bar\"\"\"");
}
@Test
public void trimFieldsAndRemoveEmptyFields_does_not_fail_on_unbalanced_quotes() {
assertThat(trimFieldsAndRemoveEmptyFields("\"")).isEqualTo("\"");
assertThat(trimFieldsAndRemoveEmptyFields("\"foo")).isEqualTo("\"foo");
assertThat(trimFieldsAndRemoveEmptyFields("foo\"")).isEqualTo("foo\"");
assertThat(trimFieldsAndRemoveEmptyFields("\"foo\",\"")).isEqualTo("\"foo\",\"");
assertThat(trimFieldsAndRemoveEmptyFields("\",\"foo\"")).isEqualTo("\",\"foo\"");
assertThat(trimFieldsAndRemoveEmptyFields("\"foo\",\", ")).isEqualTo("\"foo\",\", ");
assertThat(trimFieldsAndRemoveEmptyFields(" a ,,b , c, \"foo\",\" ")).isEqualTo("a,b,c,\"foo\",\" ");
assertThat(trimFieldsAndRemoveEmptyFields("\" a ,,b , c, ")).isEqualTo("\" a ,,b , c, ");
}
private static final char[] SOME_PRINTABLE_TRIMMABLE_CHARS = {
' ', '\t', '\n', '\r'
};
/**
* Result of randomTrimmedChars being used as arguments to JUnit test method through the DataProvider feature, they
* are printed to surefire report. Some of those chars breaks the parsing of the surefire report during sonar analysis.
* Therefor, we only use a subset of the trimmable chars.
*/
private static String randomTrimmedChars(int length, Random random) {
char[] chars = new char[length];
for (int i = 0; i < chars.length; i++) {
chars[i] = SOME_PRINTABLE_TRIMMABLE_CHARS[random.nextInt(SOME_PRINTABLE_TRIMMABLE_CHARS.length)];
}
return new String(chars);
}
}
| 12,510 | 47.119231 | 163 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/AlwaysIncreasingSystem2Test.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import javax.annotation.Nullable;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AlwaysIncreasingSystem2Test {
@Test
public void default_constructor_makes_now_start_with_random_number_and_increase_returned_value_by_100_with_each_call() {
AlwaysIncreasingSystem2 underTest = new AlwaysIncreasingSystem2();
verifyValuesReturnedByNow(underTest, null, 100);
}
@Test
public void constructor_with_increment_makes_now_start_with_random_number_and_increase_returned_value_by_specified_value_with_each_call() {
AlwaysIncreasingSystem2 underTest = new AlwaysIncreasingSystem2(663);
verifyValuesReturnedByNow(underTest, null, 663);
}
@Test
public void constructor_with_initial_value_and_increment_makes_now_start_with_specified_value_and_increase_returned_value_by_specified_value_with_each_call() {
AlwaysIncreasingSystem2 underTest = new AlwaysIncreasingSystem2(777777L, 96);
verifyValuesReturnedByNow(underTest, 777777L, 96);
}
@Test
public void constructor_with_initial_value_and_increment_throws_IAE_if_initial_value_is_less_than_0() {
assertThatThrownBy(() -> new AlwaysIncreasingSystem2(-1, 100))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Initial value must be >= 0");
}
@Test
public void constructor_with_initial_value_and_increment_accepts_initial_value_0() {
AlwaysIncreasingSystem2 underTest = new AlwaysIncreasingSystem2(0, 100);
verifyValuesReturnedByNow(underTest, 0L, 100);
}
@Test
public void constructor_with_initial_value_and_increment_throws_IAE_if_increment_is_0() {
assertThatThrownBy(() -> new AlwaysIncreasingSystem2(10, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("increment must be > 0");
}
@Test
public void constructor_with_initial_value_and_increment_throws_IAE_if_increment_is_less_than_0() {
assertThatThrownBy(() -> new AlwaysIncreasingSystem2(10, -66))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("increment must be > 0");
}
@Test
public void constructor_with_increment_throws_IAE_if_increment_is_0() {
assertThatThrownBy(() -> new AlwaysIncreasingSystem2(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("increment must be > 0");
}
@Test
public void constructor_with_increment_throws_IAE_if_increment_is_less_than_0() {
assertThatThrownBy(() -> new AlwaysIncreasingSystem2(-20))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("increment must be > 0");
}
private void verifyValuesReturnedByNow(AlwaysIncreasingSystem2 underTest, @Nullable Long initialValue, int increment) {
long previousValue = -1;
for (int i = 0; i < 333; i++) {
if (previousValue == -1) {
long now = underTest.now();
if (initialValue != null) {
assertThat(now).isEqualTo(initialValue);
} else {
assertThat(now).isNotNegative();
}
previousValue = now;
} else {
long now = underTest.now();
assertThat(now).isEqualTo(previousValue + increment);
previousValue = now;
}
}
}
}
| 4,125 | 36.171171 | 161 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/DefaultTempFolderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DefaultTempFolderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private static StringBuilder tooLong = new StringBuilder("tooooolong");
@BeforeClass
public static void setUp() {
for (int i = 0; i < 50; i++) {
tooLong.append("tooooolong");
}
}
@Test
public void createTempFolderAndFile() throws Exception {
File rootTempFolder = temp.newFolder();
DefaultTempFolder underTest = new DefaultTempFolder(rootTempFolder);
File dir = underTest.newDir();
assertThat(dir).exists().isDirectory();
File file = underTest.newFile();
assertThat(file).exists().isFile();
underTest.clean();
assertThat(rootTempFolder).doesNotExist();
}
@Test
public void createTempFolderWithName() throws Exception {
File rootTempFolder = temp.newFolder();
DefaultTempFolder underTest = new DefaultTempFolder(rootTempFolder);
File dir = underTest.newDir("sample");
assertThat(dir).exists().isDirectory();
assertThat(new File(rootTempFolder, "sample")).isEqualTo(dir);
underTest.clean();
assertThat(rootTempFolder).doesNotExist();
}
@Test
public void newDir_throws_ISE_if_name_is_not_valid() throws Exception {
File rootTempFolder = temp.newFolder();
DefaultTempFolder underTest = new DefaultTempFolder(rootTempFolder);
assertThatThrownBy(() -> underTest.newDir(tooLong.toString()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to create temp directory");
}
@Test
public void newFile_throws_ISE_if_name_is_not_valid() throws Exception {
File rootTempFolder = temp.newFolder();
DefaultTempFolder underTest = new DefaultTempFolder(rootTempFolder);
assertThatThrownBy(() -> underTest.newFile(tooLong.toString(), ".txt"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Failed to create temp file");
}
@Test
public void clean_deletes_non_empty_directory() throws Exception {
File dir = temp.newFolder();
FileUtils.touch(new File(dir, "foo.txt"));
DefaultTempFolder underTest = new DefaultTempFolder(dir);
underTest.clean();
assertThat(dir).doesNotExist();
}
@Test
public void clean_does_not_fail_if_directory_has_already_been_deleted() throws Exception {
File dir = temp.newFolder();
DefaultTempFolder underTest = new DefaultTempFolder(dir);
underTest.clean();
assertThat(dir).doesNotExist();
// second call does not fail, nor log ERROR logs
underTest.clean();
assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
}
| 3,898 | 31.22314 | 92 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/JUnitTempFolderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import org.junit.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
public class JUnitTempFolderTest {
@Test
public void apply() throws Throwable {
JUnitTempFolder temp = new JUnitTempFolder();
temp.before();
File dir1 = temp.newDir();
assertThat(dir1).isDirectory().exists();
File dir2 = temp.newDir("foo");
assertThat(dir2).isDirectory().exists();
File file1 = temp.newFile();
assertThat(file1).isFile().exists();
File file2 = temp.newFile("foo", "txt");
assertThat(file2).isFile().exists();
temp.after();
assertThat(dir1).doesNotExist();
assertThat(dir2).doesNotExist();
assertThat(file1).doesNotExist();
assertThat(file2).doesNotExist();
}
}
| 1,633 | 29.259259 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/ScannerUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ScannerUtilsTest {
@Test
public void test_pluralize() {
assertThat(ScannerUtils.pluralize("string", 0)).isEqualTo("strings");
assertThat(ScannerUtils.pluralize("string", 1)).isEqualTo("string");
assertThat(ScannerUtils.pluralize("string", 2)).isEqualTo("strings");
}
@Test
public void cleanKeyForFilename() {
assertThat(ScannerUtils.cleanKeyForFilename("project 1")).isEqualTo("project1");
assertThat(ScannerUtils.cleanKeyForFilename("project:1")).isEqualTo("project_1");
}
@Test
public void describe() {
assertThat(ScannerUtils.describe(new Object())).isEqualTo("java.lang.Object");
assertThat(ScannerUtils.describe(new TestClass())).isEqualTo("overridden");
}
static class TestClass {
@Override
public String toString() {
return "overridden";
}
}
}
| 1,796 | 32.90566 | 85 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/TestSystem2Test.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class TestSystem2Test {
private TestSystem2 underTest;
@Before
public void setup() {
underTest = new TestSystem2();
}
@Test
public void test_tick() {
underTest.setNow(1000L);
underTest.tick();
assertThat(underTest.now()).isEqualTo(1001L);
}
@Test
public void test_now() {
underTest.setNow(1000L);
assertThat(underTest.now()).isEqualTo(1000L);
}
@Test
public void test_default_time_zone() {
underTest.setDefaultTimeZone(TimeZone.getDefault());
TimeZone result = underTest.getDefaultTimeZone();
assertThat(result.getID()).isEqualTo(TimeZone.getDefault().getID());
}
@Test
public void throw_ISE_if_now_equal_zero() {
underTest.setNow(0);
assertThatThrownBy(() -> underTest.now())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Method setNow() was not called by test");
}
@Test
public void throw_ISE_if_now_lesser_than_zero() {
underTest.setNow(-1);
assertThatThrownBy(() -> underTest.now())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Method setNow() was not called by test");
}
@Test
public void throw_ISE_if_now_equal_zero_and_try_to_tick() {
underTest.setNow(0);
assertThatThrownBy(() -> underTest.tick())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Method setNow() was not called by test");
}
@Test
public void throw_ISE_if_now_lesser_than_zero_and_try_to_tick() {
underTest.setNow(-1);
assertThatThrownBy(() -> underTest.tick())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Method setNow() was not called by test");
}
}
| 2,732 | 27.768421 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/utils/WorkDurationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.utils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class WorkDurationTest {
static final int HOURS_IN_DAY = 8;
static final Long ONE_MINUTE = 1L;
static final Long ONE_HOUR_IN_MINUTES = ONE_MINUTE * 60;
static final Long ONE_DAY_IN_MINUTES = ONE_HOUR_IN_MINUTES * HOURS_IN_DAY;
@Test
public void create_from_days_hours_minutes() {
WorkDuration workDuration = WorkDuration.create(1, 1, 1, HOURS_IN_DAY);
assertThat(workDuration.days()).isOne();
assertThat(workDuration.hours()).isOne();
assertThat(workDuration.minutes()).isOne();
assertThat(workDuration.toMinutes()).isEqualTo(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE);
assertThat(workDuration.hoursInDay()).isEqualTo(HOURS_IN_DAY);
}
@Test
public void create_from_value_and_unit() {
WorkDuration result = WorkDuration.createFromValueAndUnit(1, WorkDuration.UNIT.DAYS, HOURS_IN_DAY);
assertThat(result.days()).isOne();
assertThat(result.hours()).isZero();
assertThat(result.minutes()).isZero();
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
assertThat(result.toMinutes()).isEqualTo(ONE_DAY_IN_MINUTES);
assertThat(WorkDuration.createFromValueAndUnit(1, WorkDuration.UNIT.DAYS, HOURS_IN_DAY).toMinutes()).isEqualTo(ONE_DAY_IN_MINUTES);
assertThat(WorkDuration.createFromValueAndUnit(1, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toMinutes()).isEqualTo(ONE_HOUR_IN_MINUTES);
assertThat(WorkDuration.createFromValueAndUnit(1, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toMinutes()).isEqualTo(ONE_MINUTE);
}
@Test
public void create_from_minutes() {
WorkDuration workDuration = WorkDuration.createFromMinutes(ONE_MINUTE, HOURS_IN_DAY);
assertThat(workDuration.days()).isZero();
assertThat(workDuration.hours()).isZero();
assertThat(workDuration.minutes()).isOne();
workDuration = WorkDuration.createFromMinutes(ONE_HOUR_IN_MINUTES, HOURS_IN_DAY);
assertThat(workDuration.days()).isZero();
assertThat(workDuration.hours()).isOne();
assertThat(workDuration.minutes()).isZero();
workDuration = WorkDuration.createFromMinutes(ONE_DAY_IN_MINUTES, HOURS_IN_DAY);
assertThat(workDuration.days()).isOne();
assertThat(workDuration.hours()).isZero();
assertThat(workDuration.minutes()).isZero();
}
@Test
public void create_from_working_long() {
// 1 minute
WorkDuration workDuration = WorkDuration.createFromLong(1L, HOURS_IN_DAY);
assertThat(workDuration.days()).isZero();
assertThat(workDuration.hours()).isZero();
assertThat(workDuration.minutes()).isOne();
// 1 hour
workDuration = WorkDuration.createFromLong(100L, HOURS_IN_DAY);
assertThat(workDuration.days()).isZero();
assertThat(workDuration.hours()).isOne();
assertThat(workDuration.minutes()).isZero();
// 1 day
workDuration = WorkDuration.createFromLong(10000L, HOURS_IN_DAY);
assertThat(workDuration.days()).isOne();
assertThat(workDuration.hours()).isZero();
assertThat(workDuration.minutes()).isZero();
}
@Test
public void convert_to_seconds() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_MINUTE);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_HOUR_IN_MINUTES);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.DAYS, HOURS_IN_DAY).toMinutes()).isEqualTo(2L * ONE_DAY_IN_MINUTES);
}
@Test
public void convert_to_working_days() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toWorkingDays()).isEqualTo(2d / 60d / 8d);
assertThat(WorkDuration.createFromValueAndUnit(240, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toWorkingDays()).isEqualTo(0.5);
assertThat(WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toWorkingDays()).isEqualTo(0.5);
assertThat(WorkDuration.createFromValueAndUnit(8, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toWorkingDays()).isEqualTo(1d);
assertThat(WorkDuration.createFromValueAndUnit(16, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toWorkingDays()).isEqualTo(2d);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.DAYS, HOURS_IN_DAY).toWorkingDays()).isEqualTo(2d);
}
@Test
public void convert_to_working_long() {
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).toLong()).isEqualTo(2L);
assertThat(WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toLong()).isEqualTo(400L);
assertThat(WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toLong()).isEqualTo(10200L);
assertThat(WorkDuration.createFromValueAndUnit(8, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).toLong()).isEqualTo(10000L);
assertThat(WorkDuration.createFromValueAndUnit(2, WorkDuration.UNIT.DAYS, HOURS_IN_DAY).toLong()).isEqualTo(20000L);
}
@Test
public void add() {
// 4h + 5h = 1d 1h
WorkDuration result = WorkDuration.createFromValueAndUnit(4, WorkDuration.UNIT.HOURS, HOURS_IN_DAY)
.add(WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY));
assertThat(result.days()).isOne();
assertThat(result.hours()).isOne();
assertThat(result.minutes()).isZero();
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
// 40 m + 30m = 1h 10m
result = WorkDuration.createFromValueAndUnit(40, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).add(WorkDuration.createFromValueAndUnit(30, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY));
assertThat(result.days()).isZero();
assertThat(result.hours()).isOne();
assertThat(result.minutes()).isEqualTo(10);
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
// 10 m + 20m = 30m
assertThat(WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).add(
WorkDuration.createFromValueAndUnit(20, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY)
).minutes()).isEqualTo(30);
assertThat(WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).add(null).minutes()).isEqualTo(10);
}
@Test
public void subtract() {
// 1d 1h - 5h = 4h
WorkDuration result = WorkDuration.create(1, 1, 0, HOURS_IN_DAY).subtract(WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY));
assertThat(result.days()).isZero();
assertThat(result.hours()).isEqualTo(4);
assertThat(result.minutes()).isZero();
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
// 1h 10m - 30m = 40m
result = WorkDuration.create(0, 1, 10, HOURS_IN_DAY).subtract(WorkDuration.createFromValueAndUnit(30, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY));
assertThat(result.days()).isZero();
assertThat(result.hours()).isZero();
assertThat(result.minutes()).isEqualTo(40);
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
// 30m - 20m = 10m
assertThat(
WorkDuration.createFromValueAndUnit(30, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).subtract(WorkDuration.createFromValueAndUnit(20, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY))
.minutes()).isEqualTo(10);
assertThat(WorkDuration.createFromValueAndUnit(10, WorkDuration.UNIT.MINUTES, HOURS_IN_DAY).subtract(null).minutes()).isEqualTo(10);
}
@Test
public void multiply() {
// 5h * 2 = 1d 2h
WorkDuration result = WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY).multiply(2);
assertThat(result.days()).isOne();
assertThat(result.hours()).isEqualTo(2);
assertThat(result.minutes()).isZero();
assertThat(result.hoursInDay()).isEqualTo(HOURS_IN_DAY);
}
@Test
public void test_equals_and_hashcode() {
WorkDuration duration = WorkDuration.createFromLong(28800, HOURS_IN_DAY);
WorkDuration durationWithSameValue = WorkDuration.createFromLong(28800, HOURS_IN_DAY);
WorkDuration durationWithDifferentValue = WorkDuration.createFromLong(14400, HOURS_IN_DAY);
assertThat(duration)
.isNotNull()
.hasSameHashCodeAs(duration)
.isEqualTo(duration);
assertThat(durationWithSameValue)
.hasSameHashCodeAs(duration)
.isEqualTo(duration);
assertThat(durationWithDifferentValue).isNotEqualTo(duration);
assertThat(durationWithDifferentValue.hashCode()).isNotEqualTo(duration.hashCode());
}
@Test
public void test_toString() {
assertThat(WorkDuration.createFromLong(28800, HOURS_IN_DAY).toString()).isNotNull();
}
}
| 9,475 | 45.45098 | 180 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/SimpleGetRequestTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.ws;
import java.io.InputStream;
import org.junit.Test;
import org.sonar.api.server.ws.Request;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
public class SimpleGetRequestTest {
org.sonar.api.impl.ws.SimpleGetRequest underTest = new SimpleGetRequest();
@Test
public void method() {
assertThat(underTest.method()).isEqualTo("GET");
underTest.setParam("foo", "bar");
assertThat(underTest.param("foo")).isEqualTo("bar");
assertThat(underTest.param("unknown")).isNull();
}
@Test
public void has_param() {
assertThat(underTest.method()).isEqualTo("GET");
underTest.setParam("foo", "bar");
assertThat(underTest.hasParam("foo")).isTrue();
assertThat(underTest.hasParam("unknown")).isFalse();
}
@Test
public void get_part() {
InputStream inputStream = mock(InputStream.class);
underTest.setPart("key", inputStream, "filename");
Request.Part part = underTest.paramAsPart("key");
assertThat(part.getInputStream()).isEqualTo(inputStream);
assertThat(part.getFileName()).isEqualTo("filename");
assertThat(underTest.paramAsPart("unknown")).isNull();
}
@Test
public void getMediaType() {
underTest.setMediaType("JSON");
assertThat(underTest.getMediaType()).isEqualTo("JSON");
}
@Test
public void multiParam_with_one_element() {
underTest.setParam("foo", "bar");
assertThat(underTest.multiParam("foo")).containsExactly("bar");
}
@Test
public void multiParam_without_any_element() {
assertThat(underTest.multiParam("42")).isEmpty();
}
@Test
public void getParams() {
underTest
.setParam("foo", "bar")
.setParam("fee", "beer");
assertThat(underTest.getParams()).containsOnly(
entry("foo", new String[] {"bar"}),
entry("fee", new String[] {"beer"}));
}
@Test
public void header_returns_empty_if_header_is_not_present() {
assertThat(underTest.header("foo")).isEmpty();
}
@Test
public void header_returns_value_of_header_if_present() {
underTest.setHeader("foo", "bar");
assertThat(underTest.header("foo")).hasValue("bar");
}
@Test
public void header_returns_empty_string_value_if_header_is_present_without_value() {
underTest.setHeader("foo", "");
assertThat(underTest.header("foo")).hasValue("");
}
}
| 3,268 | 28.45045 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/impl/ws/StaticResourcesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.impl.ws;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StaticResourcesTest {
@Test
public void patterns_shouldNotBeEmpty() {
assertThat(StaticResources.patterns()).isNotEmpty();
}
} | 1,107 | 34.741935 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/internal/MetadataLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.internal;
import java.io.File;
import java.net.MalformedURLException;
import org.junit.Test;
import org.sonar.api.SonarEdition;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MetadataLoaderTest {
private final System2 system = mock(System2.class);
@Test
public void load_api_version_from_file_in_classpath() {
Version version = MetadataLoader.loadApiVersion(System2.INSTANCE);
assertThat(version).isNotNull();
assertThat(version.major()).isGreaterThanOrEqualTo(5);
}
@Test
public void load_sq_version_from_file_in_classpath() {
Version version = MetadataLoader.loadSQVersion(System2.INSTANCE);
assertThat(version).isNotNull();
assertThat(version.major()).isGreaterThanOrEqualTo(5);
}
@Test
public void load_edition_from_file_in_classpath() {
SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE);
assertThat(edition).isNotNull();
}
@Test
public void load_edition_defaults_to_community_if_file_not_found() throws MalformedURLException {
when(system.getResource(anyString())).thenReturn(new File("target/unknown").toURI().toURL());
SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE);
assertThat(edition).isEqualTo(SonarEdition.COMMUNITY);
}
@Test
public void throw_ISE_if_edition_is_invalid() {
assertThatThrownBy(() -> MetadataLoader.parseEdition("trash"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Invalid edition found in '/sonar-edition.txt': 'TRASH'");
}
@Test
public void throw_ISE_if_fail_to_load_version() throws Exception {
when(system.getResource(anyString())).thenReturn(new File("target/unknown").toURI().toURL());
assertThatThrownBy(() -> MetadataLoader.loadApiVersion(system))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Can not load /sonar-api-version.txt from classpath");
}
}
| 3,048 | 36.182927 | 99 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/internal/SonarRuntimeImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.internal;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarProduct;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.utils.Version;
import static org.assertj.core.api.Assertions.assertThat;
public class SonarRuntimeImplTest {
private static final Version A_VERSION = Version.parse("6.0");
@Test
public void sonarQube_environment() {
SonarRuntime apiVersion = SonarRuntimeImpl.forSonarQube(A_VERSION, SonarQubeSide.SCANNER, SonarEdition.COMMUNITY);
assertThat(apiVersion.getApiVersion()).isEqualTo(A_VERSION);
assertThat(apiVersion.getProduct()).isEqualTo(SonarProduct.SONARQUBE);
assertThat(apiVersion.getSonarQubeSide()).isEqualTo(SonarQubeSide.SCANNER);
}
@Test
public void sonarLint_environment() {
SonarRuntime apiVersion = SonarRuntimeImpl.forSonarLint(A_VERSION);
assertThat(apiVersion.getApiVersion()).isEqualTo(A_VERSION);
assertThat(apiVersion.getProduct()).isEqualTo(SonarProduct.SONARLINT);
try {
apiVersion.getSonarQubeSide();
Assertions.fail("Expected exception");
} catch (Exception e) {
assertThat(e).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test(expected = IllegalArgumentException.class)
public void sonarqube_requires_side() {
SonarRuntimeImpl.forSonarQube(A_VERSION, null, null);
}
}
| 2,292 | 34.828125 | 118 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.Priority;
import org.apache.commons.io.FileUtils;
import org.junit.rules.ExternalResource;
import org.sonar.api.Plugin;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarProduct;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.impl.server.RulesDefinitionContext;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinition.Repository;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.Version;
import org.sonar.batch.bootstrapper.Batch;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonar.batch.bootstrapper.LogOutput;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.cache.AnalysisCacheLoader;
import org.sonar.scanner.protocol.internal.SensorCacheData;
import org.sonar.scanner.report.CeTaskReportDataHolder;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.MetricsRepository;
import org.sonar.scanner.repository.MetricsRepositoryLoader;
import org.sonar.scanner.repository.NewCodePeriodLoader;
import org.sonar.scanner.repository.ProjectRepositories;
import org.sonar.scanner.repository.ProjectRepositoriesLoader;
import org.sonar.scanner.repository.QualityProfileLoader;
import org.sonar.scanner.repository.SingleProjectRepository;
import org.sonar.scanner.repository.settings.GlobalSettingsLoader;
import org.sonar.scanner.repository.settings.ProjectSettingsLoader;
import org.sonar.scanner.rule.ActiveRulesLoader;
import org.sonar.scanner.rule.RulesLoader;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchConfigurationLoader;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.scanner.scan.branch.ProjectBranches;
import org.sonarqube.ws.NewCodePeriods;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import org.sonarqube.ws.Rules.ListResponse.Rule;
import static java.util.Collections.emptySet;
/**
* Main utility class for writing scanner medium tests.
*/
public class ScannerMediumTester extends ExternalResource {
private static Path userHome = null;
private final Map<String, String> globalProperties = new HashMap<>();
private final FakeMetricsRepositoryLoader globalRefProvider = new FakeMetricsRepositoryLoader();
private final FakeBranchConfigurationLoader branchConfigurationLoader = new FakeBranchConfigurationLoader();
private final FakeBranchConfiguration branchConfiguration = new FakeBranchConfiguration();
private final FakeProjectRepositoriesLoader projectRefProvider = new FakeProjectRepositoriesLoader();
private final FakePluginInstaller pluginInstaller = new FakePluginInstaller();
private final FakeGlobalSettingsLoader globalSettingsLoader = new FakeGlobalSettingsLoader();
private final FakeProjectSettingsLoader projectSettingsLoader = new FakeProjectSettingsLoader();
private final FakeNewCodePeriodLoader newCodePeriodLoader = new FakeNewCodePeriodLoader();
private final FakeAnalysisCacheLoader analysisCacheLoader = new FakeAnalysisCacheLoader();
private final FakeRulesLoader rulesLoader = new FakeRulesLoader();
private final FakeQualityProfileLoader qualityProfiles = new FakeQualityProfileLoader();
private final FakeActiveRulesLoader activeRules = new FakeActiveRulesLoader();
private final FakeSonarRuntime sonarRuntime = new FakeSonarRuntime();
private final CeTaskReportDataHolder reportMetadataHolder = new CeTaskReportDataHolderExt();
private LogOutput logOutput = null;
private static void createWorkingDirs() throws IOException {
destroyWorkingDirs();
userHome = java.nio.file.Files.createTempDirectory("mediumtest-userHome");
}
private static void destroyWorkingDirs() throws IOException {
if (userHome != null) {
FileUtils.deleteDirectory(userHome.toFile());
userHome = null;
}
}
public ScannerMediumTester setLogOutput(LogOutput logOutput) {
this.logOutput = logOutput;
return this;
}
public ScannerMediumTester registerPlugin(String pluginKey, File location) {
return registerPlugin(pluginKey, location, 1L);
}
public ScannerMediumTester registerPlugin(String pluginKey, File location, long lastUpdatedAt) {
pluginInstaller.add(pluginKey, location, lastUpdatedAt);
return this;
}
public ScannerMediumTester registerPlugin(String pluginKey, Plugin instance) {
return registerPlugin(pluginKey, instance, 1L);
}
public ScannerMediumTester registerPlugin(String pluginKey, Plugin instance, long lastUpdatedAt) {
pluginInstaller.add(pluginKey, instance, lastUpdatedAt);
return this;
}
public ScannerMediumTester registerCoreMetrics() {
for (Metric<?> m : CoreMetrics.getMetrics()) {
registerMetric(m);
}
return this;
}
public ScannerMediumTester registerMetric(Metric<?> metric) {
globalRefProvider.add(metric);
return this;
}
public ScannerMediumTester addQProfile(String language, String name) {
qualityProfiles.add(language, name);
return this;
}
public ScannerMediumTester addRule(Rule rule) {
rulesLoader.addRule(rule);
return this;
}
public ScannerMediumTester addRule(String key, String repoKey, String internalKey, String name) {
Rule.Builder builder = Rule.newBuilder();
builder.setKey(key);
builder.setRepository(repoKey);
if (internalKey != null) {
builder.setInternalKey(internalKey);
}
builder.setName(name);
rulesLoader.addRule(builder.build());
return this;
}
public ScannerMediumTester addRules(RulesDefinition rulesDefinition) {
RulesDefinition.Context context = new RulesDefinitionContext();
rulesDefinition.define(context);
List<Repository> repositories = context.repositories();
for (Repository repo : repositories) {
for (RulesDefinition.Rule rule : repo.rules()) {
this.addRule(rule.key(), rule.repository().key(), rule.internalKey(), rule.name());
}
}
return this;
}
public ScannerMediumTester addDefaultQProfile(String language, String name) {
addQProfile(language, name);
return this;
}
public ScannerMediumTester bootstrapProperties(Map<String, String> props) {
globalProperties.putAll(props);
return this;
}
public ScannerMediumTester activateRule(LoadedActiveRule activeRule) {
activeRules.addActiveRule(activeRule);
return this;
}
public ScannerMediumTester addActiveRule(String repositoryKey, String ruleKey, @Nullable String templateRuleKey, String name, @Nullable String severity,
@Nullable String internalKey, @Nullable String language) {
LoadedActiveRule r = new LoadedActiveRule();
r.setInternalKey(internalKey);
r.setRuleKey(RuleKey.of(repositoryKey, ruleKey));
r.setName(name);
r.setTemplateRuleKey(templateRuleKey);
r.setLanguage(language);
r.setSeverity(severity);
r.setDeprecatedKeys(emptySet());
activeRules.addActiveRule(r);
return this;
}
public ScannerMediumTester addFileData(String path, FileData fileData) {
projectRefProvider.addFileData(path, fileData);
return this;
}
public ScannerMediumTester addGlobalServerSettings(String key, String value) {
globalSettingsLoader.getGlobalSettings().put(key, value);
return this;
}
public ScannerMediumTester addProjectServerSettings(String key, String value) {
projectSettingsLoader.getProjectSettings().put(key, value);
return this;
}
public ScannerMediumTester setNewCodePeriod(NewCodePeriods.NewCodePeriodType type, String value) {
newCodePeriodLoader.set(NewCodePeriods.ShowWSResponse.newBuilder().setType(type).setValue(value).build());
return this;
}
@Override
protected void before() {
try {
createWorkingDirs();
} catch (IOException e) {
throw new IllegalStateException(e);
}
registerCoreMetrics();
globalProperties.put(GlobalAnalysisMode.MEDIUM_TEST_ENABLED, "true");
globalProperties.put(ScanProperties.KEEP_REPORT_PROP_KEY, "true");
globalProperties.put("sonar.userHome", userHome.toString());
}
@Override
protected void after() {
try {
destroyWorkingDirs();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public AnalysisBuilder newAnalysis() {
return new AnalysisBuilder(this);
}
public AnalysisBuilder newAnalysis(File sonarProps) {
Properties prop = new Properties();
try (Reader reader = new InputStreamReader(new FileInputStream(sonarProps), StandardCharsets.UTF_8)) {
prop.load(reader);
} catch (Exception e) {
throw new IllegalStateException("Unable to read configuration file", e);
}
AnalysisBuilder builder = new AnalysisBuilder(this);
builder.property("sonar.projectBaseDir", sonarProps.getParentFile().getAbsolutePath());
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
builder.property(entry.getKey().toString(), entry.getValue().toString());
}
return builder;
}
public static class AnalysisBuilder {
private final Map<String, String> taskProperties = new HashMap<>();
private final ScannerMediumTester tester;
public AnalysisBuilder(ScannerMediumTester tester) {
this.tester = tester;
}
public AnalysisResult execute() {
AnalysisResult result = new AnalysisResult();
Map<String, String> props = new HashMap<>();
props.putAll(tester.globalProperties);
props.putAll(taskProperties);
Batch.Builder builder = Batch.builder()
.setGlobalProperties(props)
.setEnableLoggingConfiguration(true)
.addComponents(new EnvironmentInformation("mediumTest", "1.0"),
tester.pluginInstaller,
tester.globalRefProvider,
tester.qualityProfiles,
tester.rulesLoader,
tester.branchConfigurationLoader,
tester.projectRefProvider,
tester.activeRules,
tester.globalSettingsLoader,
tester.projectSettingsLoader,
tester.newCodePeriodLoader,
tester.analysisCacheLoader,
tester.sonarRuntime,
tester.reportMetadataHolder,
result);
if (tester.logOutput != null) {
builder.setLogOutput(tester.logOutput);
} else {
builder.setEnableLoggingConfiguration(false);
}
builder.build().execute();
return result;
}
public AnalysisBuilder properties(Map<String, String> props) {
taskProperties.putAll(props);
return this;
}
public AnalysisBuilder property(String key, String value) {
taskProperties.put(key, value);
return this;
}
}
@Priority(1)
private static class FakeRulesLoader implements RulesLoader {
private List<Rule> rules = new LinkedList<>();
public FakeRulesLoader addRule(Rule rule) {
rules.add(rule);
return this;
}
@Override
public List<Rule> load() {
return rules;
}
}
@Priority(1)
private static class FakeActiveRulesLoader implements ActiveRulesLoader {
private List<LoadedActiveRule> activeRules = new LinkedList<>();
public void addActiveRule(LoadedActiveRule activeRule) {
this.activeRules.add(activeRule);
}
@Override
public List<LoadedActiveRule> load(String qualityProfileKey) {
return activeRules;
}
}
@Priority(1)
private static class FakeMetricsRepositoryLoader implements MetricsRepositoryLoader {
private int metricId = 1;
private List<Metric> metrics = new ArrayList<>();
@Override
public MetricsRepository load() {
return new MetricsRepository(metrics);
}
public FakeMetricsRepositoryLoader add(Metric<?> metric) {
metric.setUuid("metric" + metricId++);
metrics.add(metric);
metricId++;
return this;
}
}
@Priority(1)
private static class FakeProjectRepositoriesLoader implements ProjectRepositoriesLoader {
private Map<String, FileData> fileDataMap = new HashMap<>();
@Override
public ProjectRepositories load(String projectKey, @Nullable String branchBase) {
return new SingleProjectRepository(fileDataMap);
}
public FakeProjectRepositoriesLoader addFileData(String path, FileData fileData) {
fileDataMap.put(path, fileData);
return this;
}
}
@Priority(1)
private static class FakeBranchConfiguration implements BranchConfiguration {
private BranchType branchType = BranchType.BRANCH;
private String branchName = null;
private String branchTarget = null;
private String referenceBranchName = null;
@Override
public BranchType branchType() {
return branchType;
}
@CheckForNull
@Override
public String branchName() {
return branchName;
}
@CheckForNull
@Override
public String targetBranchName() {
return branchTarget;
}
@CheckForNull
@Override
public String referenceBranchName() {
return referenceBranchName;
}
@Override
public String pullRequestKey() {
return "1'";
}
}
@Priority(1)
private static class FakeSonarRuntime implements SonarRuntime {
private SonarEdition edition;
FakeSonarRuntime() {
this.edition = SonarEdition.COMMUNITY;
}
@Override
public Version getApiVersion() {
return Version.create(7, 8);
}
@Override
public SonarProduct getProduct() {
return SonarProduct.SONARQUBE;
}
@Override
public SonarQubeSide getSonarQubeSide() {
return SonarQubeSide.SCANNER;
}
@Override
public SonarEdition getEdition() {
return edition;
}
public void setEdition(SonarEdition edition) {
this.edition = edition;
}
}
public ScannerMediumTester setBranchType(BranchType branchType) {
branchConfiguration.branchType = branchType;
return this;
}
public ScannerMediumTester setBranchName(String branchName) {
this.branchConfiguration.branchName = branchName;
return this;
}
public ScannerMediumTester setBranchTarget(String branchTarget) {
this.branchConfiguration.branchTarget = branchTarget;
return this;
}
public ScannerMediumTester setReferenceBranchName(String referenceBranchNam) {
this.branchConfiguration.referenceBranchName = referenceBranchNam;
return this;
}
public ScannerMediumTester setEdition(SonarEdition edition) {
this.sonarRuntime.setEdition(edition);
return this;
}
@Priority(1)
private class FakeBranchConfigurationLoader implements BranchConfigurationLoader {
@Override
public BranchConfiguration load(Map<String, String> projectSettings, ProjectBranches branches) {
return branchConfiguration;
}
}
@Priority(1)
private static class FakeQualityProfileLoader implements QualityProfileLoader {
private List<QualityProfile> qualityProfiles = new LinkedList<>();
public void add(String language, String name) {
qualityProfiles.add(QualityProfile.newBuilder()
.setLanguage(language)
.setKey(name)
.setName(name)
.setRulesUpdatedAt(DateUtils.formatDateTime(new Date(1234567891212L)))
.build());
}
@Override
public List<QualityProfile> load(String projectKey) {
return qualityProfiles;
}
}
@Priority(1)
private static class FakeAnalysisCacheLoader implements AnalysisCacheLoader {
@Override
public Optional<SensorCacheData> load() {
return Optional.empty();
}
}
@Priority(1)
private static class FakeGlobalSettingsLoader implements GlobalSettingsLoader {
private Map<String, String> globalSettings = new HashMap<>();
public Map<String, String> getGlobalSettings() {
return globalSettings;
}
@Override
public Map<String, String> loadGlobalSettings() {
return Collections.unmodifiableMap(globalSettings);
}
}
@Priority(1)
private static class FakeNewCodePeriodLoader implements NewCodePeriodLoader {
private NewCodePeriods.ShowWSResponse response;
@Override
public NewCodePeriods.ShowWSResponse load(String projectKey, String branchName) {
return response;
}
public void set(NewCodePeriods.ShowWSResponse response) {
this.response = response;
}
}
@Priority(1)
private static class FakeProjectSettingsLoader implements ProjectSettingsLoader {
private Map<String, String> projectSettings = new HashMap<>();
public Map<String, String> getProjectSettings() {
return projectSettings;
}
@Override
public Map<String, String> loadProjectSettings() {
return Collections.unmodifiableMap(projectSettings);
}
}
@Priority(1)
private static class CeTaskReportDataHolderExt extends CeTaskReportDataHolder {
}
}
| 18,418 | 30.378194 | 154 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/branch/BranchMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.branch;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import org.sonarqube.ws.NewCodePeriods;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class BranchMediumIT {
private static final String PROJECT_KEY = "sample";
private static final String FILE_PATH = "HelloJava.xoo";
private static final String FILE_CONTENT = "xoooo";
public static final String ONE_ISSUE_PER_LINE_IS_RESTRICTED_TO_CHANGED_FILES_ONLY = "Sensor One Issue Per Line is restricted to changed files only";
private File baseDir;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo");
@Before
public void prepare() throws IOException {
logTester.setLevel(Level.DEBUG);
baseDir = temp.newFolder();
Path filepath = baseDir.toPath().resolve(FILE_PATH);
Files.write(filepath, FILE_CONTENT.getBytes());
Path xooUtCoverageFile = baseDir.toPath().resolve(FILE_PATH + ".coverage");
FileUtils.write(xooUtCoverageFile.toFile(), "1:2:2:1", StandardCharsets.UTF_8);
String md5sum = new FileMetadata(mock(AnalysisWarnings.class))
.readMetadata(Files.newInputStream(filepath), StandardCharsets.UTF_8, FILE_PATH)
.hash();
tester.addFileData(FILE_PATH, new FileData(md5sum, "1.1"));
tester.setNewCodePeriod(NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION, "");
}
@Test
public void should_not_skip_report_for_unchanged_files_in_pr() {
// sanity check, normally report gets generated
AnalysisResult result = getResult(tester);
final DefaultInputFile file = (DefaultInputFile) result.inputFile(FILE_PATH);
assertThat(getResult(tester).getReportComponent(file)).isNotNull();
int fileId = file.scannerId();
assertThat(result.getReportReader().readChangesets(fileId)).isNotNull();
assertThat(result.getReportReader().hasCoverage(fileId)).isTrue();
assertThat(result.getReportReader().readFileSource(fileId)).isNotNull();
// file is not skipped for pull requests (need coverage, duplications coming soon)
AnalysisResult result2 = getResult(tester.setBranchType(BranchType.PULL_REQUEST));
final DefaultInputFile fileInPr = (DefaultInputFile) result2.inputFile(FILE_PATH);
assertThat(result2.getReportComponent(fileInPr)).isNotNull();
fileId = fileInPr.scannerId();
assertThat(result2.getReportReader().readChangesets(fileId)).isNull();
assertThat(result2.getReportReader().hasCoverage(fileId)).isTrue();
assertThat(result2.getReportReader().readFileSource(fileId)).isNull();
}
@Test
public void shouldSkipSensorForUnchangedFilesOnPr() {
AnalysisResult result = getResult(tester
.setBranchName("myBranch")
.setBranchTarget("main")
.setBranchType(BranchType.PULL_REQUEST));
final DefaultInputFile file = (DefaultInputFile) result.inputFile(FILE_PATH);
List<ScannerReport.Issue> issues = result.issuesFor(file);
assertThat(issues).isEmpty();
assertThat(logTester.logs()).contains(ONE_ISSUE_PER_LINE_IS_RESTRICTED_TO_CHANGED_FILES_ONLY);
}
@Test
public void shouldNotSkipSensorForUnchangedFilesOnBranch() throws Exception {
AnalysisResult result = getResult(tester
.setBranchName("myBranch")
.setBranchTarget("main")
.setBranchType(BranchType.BRANCH));
final DefaultInputFile file = (DefaultInputFile) result.inputFile(FILE_PATH);
List<ScannerReport.Issue> issues = result.issuesFor(file);
assertThat(issues).isNotEmpty();
assertThat(logTester.logs()).doesNotContain(ONE_ISSUE_PER_LINE_IS_RESTRICTED_TO_CHANGED_FILES_ONLY);
}
@Test
public void verify_metadata() {
String branchName = "feature";
String branchTarget = "branch-1.x";
AnalysisResult result = getResult(tester
.setBranchName(branchName)
.setBranchTarget(branchTarget)
.setReferenceBranchName(branchTarget)
.setBranchType(BranchType.BRANCH));
ScannerReport.Metadata metadata = result.getReportReader().readMetadata();
assertThat(metadata.getBranchName()).isEqualTo(branchName);
assertThat(metadata.getBranchType()).isEqualTo(ScannerReport.Metadata.BranchType.BRANCH);
assertThat(metadata.getReferenceBranchName()).isEqualTo(branchTarget);
}
private AnalysisResult getResult(ScannerMediumTester tester) {
return tester
.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", PROJECT_KEY)
.put("sonar.scm.provider", "xoo")
.build())
.execute();
}
}
| 6,756 | 39.704819 | 150 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/branch/DeprecatedBranchMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.branch;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DeprecatedBranchMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addRules(new XooRulesDefinition())
// active a rule just to be sure that xoo files are published
.addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null)
.addDefaultQProfile("xoo", "Sonar Way");
private File baseDir;
private Map<String, String> commonProps;
@Before
public void prepare() {
baseDir = temp.getRoot();
commonProps = ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build();
}
@Test
public void scanProjectWithBranch() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
assertThatThrownBy(() -> tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.putAll(commonProps)
.put("sonar.branch", "branch")
.build())
.execute())
.isInstanceOf(MessageException.class)
.hasMessage("The 'sonar.branch' parameter is no longer supported. You should stop using it. " +
"Branch analysis is available in Developer Edition and above. See https://www.sonarsource.com/plans-and-pricing/developer/ for more information.");
}
}
| 3,191 | 34.865169 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/coverage/CoverageMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.coverage;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
public class CoverageMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Before
public void prepare() throws IOException {
logTester.setLevel(Level.DEBUG);
}
@Test
public void singleReport() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xooUtCoverageFile = new File(srcDir, "sample.xoo.coverage");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFile, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.coverageFor(file, 2).getHits()).isTrue();
assertThat(result.coverageFor(file, 2).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(file, 2).getCoveredConditions()).isOne();
}
@Test
public void twoReports() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
File xooUtCoverageFile = new File(srcDir, "sample.xoo.coverage");
FileUtils.write(xooUtCoverageFile, "2:2:2:2\n4:0", StandardCharsets.UTF_8);
File xooItCoverageFile = new File(srcDir, "sample.xoo.itcoverage");
FileUtils.write(xooItCoverageFile, "2:0:2:1\n3:1\n5:0", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.coverageFor(file, 2).getHits()).isTrue();
assertThat(result.coverageFor(file, 2).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(file, 2).getCoveredConditions()).isEqualTo(2);
assertThat(result.coverageFor(file, 3).getHits()).isTrue();
}
@Test
public void exclusionsForSimpleProject() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xooUtCoverageFile = new File(srcDir, "sample.xoo.coverage");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFile, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.coverage.exclusions", "**/sample.xoo")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.coverageFor(file, 2)).isNull();
}
@Test
public void warn_user_for_outdated_inherited_scanner_side_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
File xooUtCoverageFileA = new File(srcDirA, "sampleA.xoo.coverage");
FileUtils.write(xooFileA, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileA, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
File xooUtCoverageFileB = new File(srcDirB, "sampleB.xoo.coverage");
FileUtils.write(xooFileB, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileB, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.coverage.exclusions", "src/sampleA.xoo")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sampleA.xoo");
assertThat(result.coverageFor(fileA, 2)).isNull();
InputFile fileB = result.inputFile("moduleB/src/sampleB.xoo");
assertThat(result.coverageFor(fileB, 2)).isNotNull();
assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
}
@Test
public void module_level_exclusions_override_parent_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
File xooUtCoverageFileA = new File(srcDirA, "sampleA.xoo.coverage");
FileUtils.write(xooFileA, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileA, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
File xooUtCoverageFileB = new File(srcDirB, "sampleB.xoo.coverage");
FileUtils.write(xooFileB, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileB, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.coverage.exclusions", "**/*.xoo")
.put("moduleA.sonar.coverage.exclusions", "**/*.nothing")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sampleA.xoo");
assertThat(result.coverageFor(fileA, 2)).isNotNull();
InputFile fileB = result.inputFile("moduleB/src/sampleB.xoo");
assertThat(result.coverageFor(fileB, 2)).isNull();
}
@Test
public void warn_user_for_outdated_server_side_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sample.xoo");
File xooUtCoverageFileA = new File(srcDirA, "sample.xoo.coverage");
FileUtils.write(xooFileA, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileA, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sample.xoo");
File xooUtCoverageFileB = new File(srcDirB, "sample.xoo.coverage");
FileUtils.write(xooFileB, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(xooUtCoverageFileB, "2:2:2:1\n3:1", StandardCharsets.UTF_8);
tester.addProjectServerSettings("sonar.coverage.exclusions", "src/sample.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sample.xoo");
assertThat(result.coverageFor(fileA, 2)).isNull();
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(result.coverageFor(fileB, 2)).isNull();
assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
@Test
public void fallbackOnExecutableLines() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File measuresFile = new File(srcDir, "sample.xoo.measures");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile, "executable_lines_data:2=1;3=1;4=0", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.coverageFor(file, 1)).isNull();
assertThat(result.coverageFor(file, 2).getHits()).isFalse();
assertThat(result.coverageFor(file, 2).getConditions()).isZero();
assertThat(result.coverageFor(file, 2).getCoveredConditions()).isZero();
assertThat(result.coverageFor(file, 3).getHits()).isFalse();
assertThat(result.coverageFor(file, 4)).isNull();
assertThat(result.allMeasures().get(file.key()))
.extracting(ScannerReport.Measure::getMetricKey, m -> m.getStringValue().getValue())
.contains(tuple("executable_lines_data", "2=1;3=1;4=0"));
}
// SONAR-11641
@Test
public void dontFallbackOnExecutableLinesIfNoCoverageSaved() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File measuresFile = new File(srcDir, "sample.xoo.measures");
File coverageFile = new File(srcDir, "sample.xoo.coverage");
FileUtils.write(xooFile, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile, "# The code analyzer disagree with the coverage tool and consider some lines to be executable\nexecutable_lines_data:2=1;3=1;4=0",
StandardCharsets.UTF_8);
FileUtils.write(coverageFile, "# No lines to cover in this file according to the coverage tool", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.coverageFor(file, 1)).isNull();
assertThat(result.coverageFor(file, 2)).isNull();
assertThat(result.coverageFor(file, 3)).isNull();
assertThat(result.coverageFor(file, 4)).isNull();
}
// SONAR-9557
@Test
public void exclusionsAndForceToZeroOnModules() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "module1/src");
srcDir.mkdir();
File xooFile1 = new File(srcDir, "sample1.xoo");
File measuresFile1 = new File(srcDir, "sample1.xoo.measures");
FileUtils.write(xooFile1, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile1, "executable_lines_data:2=1;3=1;4=0", StandardCharsets.UTF_8);
File xooFile2 = new File(srcDir, "sample2.xoo");
File measuresFile2 = new File(srcDir, "sample2.xoo.measures");
FileUtils.write(xooFile2, "function foo() {\n if (a && b) {\nalert('hello');\n}\n}", StandardCharsets.UTF_8);
FileUtils.write(measuresFile2, "executable_lines_data:2=1;3=1;4=0", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "module1")
.put("sonar.sources", "src")
.put("sonar.coverage.exclusions", "**/sample2.xoo")
.build())
.execute();
InputFile file1 = result.inputFile("module1/src/sample1.xoo");
assertThat(result.coverageFor(file1, 1)).isNull();
assertThat(result.coverageFor(file1, 2).getHits()).isFalse();
assertThat(result.coverageFor(file1, 2).getConditions()).isZero();
assertThat(result.coverageFor(file1, 2).getCoveredConditions()).isZero();
assertThat(result.coverageFor(file1, 3).getHits()).isFalse();
assertThat(result.coverageFor(file1, 4)).isNull();
InputFile file2 = result.inputFile("module1/src/sample2.xoo");
assertThat(result.coverageFor(file2, 1)).isNull();
assertThat(result.coverageFor(file2, 2)).isNull();
assertThat(result.coverageFor(file2, 3)).isNull();
assertThat(result.coverageFor(file2, 4)).isNull();
}
}
| 16,044 | 41.786667 | 165 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/coverage/GenericCoverageMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.coverage;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
public class GenericCoverageMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Test
public void singleReport() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml")
.execute();
InputFile noConditions = result.inputFile("xources/hello/NoConditions.xoo");
assertThat(result.coverageFor(noConditions, 6).getHits()).isTrue();
assertThat(result.coverageFor(noConditions, 6).getConditions()).isZero();
assertThat(result.coverageFor(noConditions, 6).getCoveredConditions()).isZero();
assertThat(result.coverageFor(noConditions, 7).getHits()).isFalse();
InputFile withConditions = result.inputFile("xources/hello/WithConditions.xoo");
assertThat(result.coverageFor(withConditions, 3).getHits()).isTrue();
assertThat(result.coverageFor(withConditions, 3).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(withConditions, 3).getCoveredConditions()).isOne();
assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
}
@Test
public void twoReports() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml,coverage2.xml")
.execute();
InputFile noConditions = result.inputFile("xources/hello/NoConditions.xoo");
assertThat(result.coverageFor(noConditions, 6).getHits()).isTrue();
assertThat(result.coverageFor(noConditions, 6).getConditions()).isZero();
assertThat(result.coverageFor(noConditions, 6).getCoveredConditions()).isZero();
assertThat(result.coverageFor(noConditions, 7).getHits()).isTrue();
InputFile withConditions = result.inputFile("xources/hello/WithConditions.xoo");
assertThat(result.coverageFor(withConditions, 3).getHits()).isTrue();
assertThat(result.coverageFor(withConditions, 3).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(withConditions, 3).getCoveredConditions()).isEqualTo(2);
assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
}
}
| 3,814 | 39.585106 | 102 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/cpd/CpdMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.cpd;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class CpdMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private File baseDir;
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
// active a rule just to be sure that xoo files are published
.addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null);
private ImmutableMap.Builder<String, String> builder;
@Before
public void prepare() {
logTester.setLevel(Level.DEBUG);
baseDir = temp.getRoot();
builder = ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project");
}
@Test
public void testCrossModuleDuplications() throws IOException {
builder.put("sonar.modules", "module1,module2")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.verbose", "true");
// module 1
builder.put("module1.sonar.projectKey", "module1");
builder.put("module1.sonar.projectName", "Module 1");
builder.put("module1.sonar.sources", ".");
// module2
builder.put("module2.sonar.projectKey", "module2");
builder.put("module2.sonar.projectName", "Module 2");
builder.put("module2.sonar.sources", ".");
File module1Dir = new File(baseDir, "module1");
File module2Dir = new File(baseDir, "module2");
module1Dir.mkdir();
module2Dir.mkdir();
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
// create duplicated file in both modules
File xooFile1 = new File(module1Dir, "sample1.xoo");
FileUtils.write(xooFile1, duplicatedStuff);
File xooFile2 = new File(module2Dir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff);
AnalysisResult result = tester.newAnalysis().properties(builder.build()).execute();
assertThat(result.inputFiles()).hasSize(2);
InputFile inputFile1 = result.inputFile("module1/sample1.xoo");
InputFile inputFile2 = result.inputFile("module2/sample2.xoo");
// One clone group on each file
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).hasSize(1);
ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0);
assertThat(cloneGroupFile1.getOriginPosition().getStartLine()).isOne();
assertThat(cloneGroupFile1.getOriginPosition().getEndLine()).isEqualTo(17);
assertThat(cloneGroupFile1.getDuplicateList()).hasSize(1);
assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(inputFile2).getRef());
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).hasSize(1);
ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0);
assertThat(cloneGroupFile2.getOriginPosition().getStartLine()).isOne();
assertThat(cloneGroupFile2.getOriginPosition().getEndLine()).isEqualTo(17);
assertThat(cloneGroupFile2.getDuplicateList()).hasSize(1);
assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(inputFile1).getRef());
assertThat(result.duplicationBlocksFor(inputFile1)).isEmpty();
}
@Test
public void testCrossFileDuplications() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, duplicatedStuff, StandardCharsets.UTF_8);
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff, StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.verbose", "true")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
InputFile inputFile1 = result.inputFile("src/sample1.xoo");
InputFile inputFile2 = result.inputFile("src/sample2.xoo");
// One clone group on each file
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).hasSize(1);
ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0);
assertThat(cloneGroupFile1.getOriginPosition().getStartLine()).isOne();
assertThat(cloneGroupFile1.getOriginPosition().getEndLine()).isEqualTo(17);
assertThat(cloneGroupFile1.getDuplicateList()).hasSize(1);
assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(inputFile2).getRef());
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).hasSize(1);
ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0);
assertThat(cloneGroupFile2.getOriginPosition().getStartLine()).isOne();
assertThat(cloneGroupFile2.getOriginPosition().getEndLine()).isEqualTo(17);
assertThat(cloneGroupFile2.getDuplicateList()).hasSize(1);
assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(inputFile1).getRef());
assertThat(result.duplicationBlocksFor(inputFile1)).isEmpty();
}
@Test
public void testFilesWithoutBlocks() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
String file1 = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
String file2 = "string\n";
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, file1, StandardCharsets.UTF_8);
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, file2, StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.verbose", "true")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
assertThat(logTester.logs()).contains("Not enough content in 'src/sample2.xoo' to have CPD blocks, it will not be part of the duplication detection");
assertThat(logTester.logs()).contains("CPD Executor 1 file had no CPD blocks");
}
@Test
public void testExclusions() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, duplicatedStuff);
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, duplicatedStuff);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.cpd.exclusions", "src/sample1.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
InputFile inputFile1 = result.inputFile("src/sample1.xoo");
InputFile inputFile2 = result.inputFile("src/sample2.xoo");
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).isEmpty();
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).isEmpty();
}
@Test
public void cross_module_duplication() throws IOException {
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, duplicatedStuff, StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, duplicatedStuff, StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.cpd.xoo.minimumTokens", "10")
.build())
.execute();
InputFile inputFile1 = result.inputFile("moduleA/src/sampleA.xoo");
InputFile inputFile2 = result.inputFile("moduleB/src/sampleB.xoo");
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).isNotEmpty();
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).isNotEmpty();
}
@Test
public void warn_user_for_outdated_inherited_scanner_side_exclusions_for_multi_module_project() throws IOException {
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, duplicatedStuff, StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, duplicatedStuff, StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.cpd.exclusions", "src/sampleA.xoo")
.build())
.execute();
InputFile inputFile1 = result.inputFile("moduleA/src/sampleA.xoo");
InputFile inputFile2 = result.inputFile("moduleB/src/sampleB.xoo");
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).isEmpty();
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).isEmpty();
assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.cpd.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
}
@Test
public void module_level_exclusions_override_parent_for_multi_module_project() throws IOException {
String duplicatedStuff = "Sample xoo\ncontent\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti\n"
+ "bar\ntoto\ntiti\n"
+ "foo\nbar\ntoto\ntiti";
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, duplicatedStuff, StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, duplicatedStuff, StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.cpd.xoo.minimumTokens", "10")
.put("sonar.cpd.exclusions", "**/*")
.put("moduleA.sonar.cpd.exclusions", "**/*.nothing")
.put("moduleB.sonar.cpd.exclusions", "**/*.nothing")
.build())
.execute();
InputFile inputFile1 = result.inputFile("moduleA/src/sampleA.xoo");
InputFile inputFile2 = result.inputFile("moduleB/src/sampleB.xoo");
List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1);
assertThat(duplicationGroupsFile1).isNotEmpty();
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).isNotEmpty();
}
@Test
public void enableCrossProjectDuplication() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
String duplicatedStuff = "Sample xoo\ncontent\nfoo\nbar\ntoto\ntiti\nfoo";
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, duplicatedStuff);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "1")
.put("sonar.cpd.xoo.minimumLines", "5")
.put("sonar.verbose", "true")
.put("sonar.cpd.cross_project", "true")
.build())
.execute();
InputFile inputFile1 = result.inputFile("src/sample1.xoo");
List<ScannerReport.CpdTextBlock> duplicationBlocks = result.duplicationBlocksFor(inputFile1);
assertThat(duplicationBlocks).hasSize(3);
assertThat(duplicationBlocks.get(0).getStartLine()).isOne();
assertThat(duplicationBlocks.get(0).getEndLine()).isEqualTo(5);
assertThat(duplicationBlocks.get(0).getStartTokenIndex()).isOne();
assertThat(duplicationBlocks.get(0).getEndTokenIndex()).isEqualTo(6);
assertThat(duplicationBlocks.get(0).getHash()).isNotEmpty();
assertThat(duplicationBlocks.get(1).getStartLine()).isEqualTo(2);
assertThat(duplicationBlocks.get(1).getEndLine()).isEqualTo(6);
assertThat(duplicationBlocks.get(1).getStartTokenIndex()).isEqualTo(3);
assertThat(duplicationBlocks.get(1).getEndTokenIndex()).isEqualTo(7);
assertThat(duplicationBlocks.get(0).getHash()).isNotEmpty();
assertThat(duplicationBlocks.get(2).getStartLine()).isEqualTo(3);
assertThat(duplicationBlocks.get(2).getEndLine()).isEqualTo(7);
assertThat(duplicationBlocks.get(2).getStartTokenIndex()).isEqualTo(4);
assertThat(duplicationBlocks.get(2).getEndTokenIndex()).isEqualTo(8);
assertThat(duplicationBlocks.get(0).getHash()).isNotEmpty();
}
@Test
public void testIntraFileDuplications() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
String content = "Sample xoo\ncontent\nfoo\nbar\nSample xoo\ncontent\n";
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, content);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.cpd.xoo.minimumTokens", "2")
.put("sonar.cpd.xoo.minimumLines", "2")
.put("sonar.verbose", "true")
.build())
.execute();
InputFile inputFile = result.inputFile("src/sample.xoo");
// One clone group
List<ScannerReport.Duplication> duplicationGroups = result.duplicationsFor(inputFile);
assertThat(duplicationGroups).hasSize(1);
ScannerReport.Duplication cloneGroup = duplicationGroups.get(0);
assertThat(cloneGroup.getOriginPosition().getStartLine()).isOne();
assertThat(cloneGroup.getOriginPosition().getEndLine()).isEqualTo(2);
assertThat(cloneGroup.getDuplicateList()).hasSize(1);
assertThat(cloneGroup.getDuplicate(0).getRange().getStartLine()).isEqualTo(5);
assertThat(cloneGroup.getDuplicate(0).getRange().getEndLine()).isEqualTo(6);
}
}
| 18,684 | 38.336842 | 160 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/fs/FileSystemMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.fs;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarEdition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.PathUtils;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.global.DeprecatedGlobalSensor;
import org.sonar.xoo.global.GlobalProjectSensor;
import org.sonar.xoo.rule.XooRulesDefinition;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
public class FileSystemMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.setEdition(SonarEdition.COMMUNITY)
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addDefaultQProfile("xoo2", "Sonar Way");
private File baseDir;
private ImmutableMap.Builder<String, String> builder;
@Before
public void prepare() throws IOException {
logTester.setLevel(Level.DEBUG);
baseDir = temp.newFolder().getCanonicalFile();
builder = ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project");
}
@Test
public void scan_project_without_name() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
int ref = result.getReportReader().readMetadata().getRootComponentRef();
assertThat(result.getReportReader().readComponent(ref).getName()).isEmpty();
assertThat(result.inputFiles()).hasSize(1);
DefaultInputFile file = (DefaultInputFile) result.inputFile("src/sample.xoo");
assertThat(file.type()).isEqualTo(InputFile.Type.MAIN);
assertThat(file.relativePath()).isEqualTo("src/sample.xoo");
assertThat(file.language()).isEqualTo("xoo");
// file was published, since language matched xoo
assertThat(file.isPublished()).isTrue();
assertThat(result.getReportComponent(file.scannerId())).isNotNull();
}
@Test
public void log_branch_name_and_type() {
builder.put("sonar.branch.name", "my-branch");
File srcDir = new File(baseDir, "src");
assertThat(srcDir.mkdir()).isTrue();
// Using sonar.branch.name when the branch plugin is not installed is an error.
assertThatThrownBy(() -> tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute())
.isInstanceOf(MessageException.class);
}
@Test
public void only_generate_metadata_if_needed() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDir, "sample.java", "Sample xoo\ncontent");
logTester.setLevel(LoggerLevel.DEBUG);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs()).contains("2 files indexed");
assertThat(logTester.logs()).contains("'src/sample.xoo' generated metadata with charset 'UTF-8'");
assertThat(String.join("\n", logTester.logs())).doesNotContain("'src/sample.java' generated metadata");
}
@Test
public void preload_file_metadata() throws IOException {
builder.put("sonar.preloadFileMetadata", "true");
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDir, "sample.java", "Sample xoo\ncontent");
logTester.setLevel(LoggerLevel.DEBUG);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs()).contains("2 files indexed");
assertThat(logTester.logs()).contains("'src/sample.xoo' generated metadata with charset 'UTF-8'");
assertThat(logTester.logs()).contains("'src/sample.java' generated metadata with charset 'UTF-8'");
}
@Test
public void dont_publish_files_without_detected_language() throws IOException {
Path mainDir = baseDir.toPath().resolve("src").resolve("main");
Files.createDirectories(mainDir);
Path testDir = baseDir.toPath().resolve("src").resolve("test");
Files.createDirectories(testDir);
writeFile(testDir.toFile(), "sample.java", "Sample xoo\ncontent");
writeFile(mainDir.toFile(), "sample.xoo", "Sample xoo\ncontent");
writeFile(mainDir.toFile(), "sample.java", "Sample xoo\ncontent");
logTester.setLevel(LoggerLevel.DEBUG);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src/main")
.put("sonar.tests", "src/test")
.build())
.execute();
assertThat(logTester.logs()).containsAnyOf("'src/main/sample.java' indexed with no language", "'src\\main\\sample.java' indexed with no language");
assertThat(logTester.logs()).contains("3 files indexed");
assertThat(logTester.logs()).contains("'src/main/sample.xoo' generated metadata with charset 'UTF-8'");
assertThat(logTester.logs()).doesNotContain("'src/main/sample.java' generated metadata", "'src\\main\\sample.java' generated metadata");
assertThat(logTester.logs()).doesNotContain("'src/test/sample.java' generated metadata", "'src\\test\\sample.java' generated metadata");
DefaultInputFile javaInputFile = (DefaultInputFile) result.inputFile("src/main/sample.java");
assertThatThrownBy(() -> result.getReportComponent(javaInputFile))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unable to find report for component");
}
@Test
public void create_issue_on_any_file() throws IOException {
tester
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerUnknownFile", null, "OneIssuePerUnknownFile", "MAJOR", null, "xoo");
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.unknown", "Sample xoo\ncontent");
logTester.setLevel(LoggerLevel.DEBUG);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs()).contains("1 file indexed");
assertThat(logTester.logs()).contains("'src" + File.separator + "sample.unknown' indexed with no language");
assertThat(logTester.logs()).contains("'src/sample.unknown' generated metadata with charset 'UTF-8'");
DefaultInputFile inputFile = (DefaultInputFile) result.inputFile("src/sample.unknown");
assertThat(result.getReportComponent(inputFile)).isNotNull();
}
@Test
public void lazyIssueExclusion() throws IOException {
tester
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerFile", null, "OneIssuePerFile", "MAJOR", null, "xoo");
builder.put("sonar.issue.ignore.allfile", "1")
.put("sonar.issue.ignore.allfile.1.fileRegexp", "pattern");
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
File unknownFile = new File(srcDir, "myfile.binary");
byte[] b = new byte[512];
new Random().nextBytes(b);
FileUtils.writeByteArrayToFile(unknownFile, b);
logTester.setLevel(LoggerLevel.DEBUG);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs()).containsOnlyOnce("'src" + File.separator + "myfile.binary' indexed with no language");
assertThat(logTester.logs()).doesNotContain("Evaluate issue exclusions for 'src/myfile.binary'");
assertThat(logTester.logs()).containsOnlyOnce("Evaluate issue exclusions for 'src/sample.xoo'");
}
@Test
public void preloadIssueExclusions() throws IOException {
builder.put("sonar.issue.ignore.allfile", "1")
.put("sonar.issue.ignore.allfile.1.fileRegexp", "pattern")
.put("sonar.preloadFileMetadata", "true");
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\npattern");
writeFile(srcDir, "myfile.binary", "some text");
logTester.setLevel(LoggerLevel.DEBUG);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs()).containsSequence("Evaluate issue exclusions for 'src/sample.xoo'",
" - Exclusion pattern 'pattern': all issues in this file will be ignored.");
}
@Test
public void publishFilesWithIssues() throws IOException {
tester
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssueOnDirPerFile", null, "OneIssueOnDirPerFile", "MAJOR", null, "xoo");
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
DefaultInputFile file = (DefaultInputFile) result.inputFile("src/sample.xoo");
assertThat(file.isPublished()).isTrue();
assertThat(result.getReportComponent(file)).isNotNull();
}
@Test
public void scanProjectWithSourceDir() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(result.inputFile("src/sample.xoo").type()).isEqualTo(InputFile.Type.MAIN);
assertThat(result.inputFile("src/sample.xoo").relativePath()).isEqualTo("src/sample.xoo");
}
@Test
public void scanBigProject() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
int nbFiles = 100;
int ruleCount = 100000;
for (int nb = 1; nb <= nbFiles; nb++) {
File xooFile = new File(srcDir, "sample" + nb + ".xoo");
FileUtils.write(xooFile, StringUtils.repeat(StringUtils.repeat("a", 100) + "\n", ruleCount / 1000));
}
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(100);
}
@Test
public void scanProjectWithTestDir() throws IOException {
File test = new File(baseDir, "test");
test.mkdir();
writeFile(test, "sampleTest.xoo", "Sample test xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "")
.put("sonar.tests", "test")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(result.inputFile("test/sampleTest.xoo").type()).isEqualTo(InputFile.Type.TEST);
}
/**
* SONAR-5419
*/
@Test
public void scanProjectWithMixedSourcesAndTests() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(baseDir, "another.xoo", "Sample xoo 2\ncontent");
File testDir = new File(baseDir, "test");
testDir.mkdir();
writeFile(baseDir, "sampleTest2.xoo", "Sample test xoo\ncontent");
writeFile(testDir, "sampleTest.xoo", "Sample test xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,another.xoo")
.put("sonar.tests", "test,sampleTest2.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(4);
}
@Test
public void fileInclusionsExclusions() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(baseDir, "another.xoo", "Sample xoo 2\ncontent");
File testDir = new File(baseDir, "test");
testDir.mkdir();
writeFile(baseDir, "sampleTest2.xoo", "Sample test xoo\ncontent");
writeFile(testDir, "sampleTest.xoo", "Sample test xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,another.xoo")
.put("sonar.tests", "test,sampleTest2.xoo")
.put("sonar.inclusions", "src/**")
.put("sonar.exclusions", "**/another.*")
.put("sonar.test.inclusions", "**/sampleTest*.*")
.put("sonar.test.exclusions", "**/sampleTest2.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
}
@Test
public void ignoreFilesWhenGreaterThanDefinedSize() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File fileGreaterThanLimit = writeFile(srcDir, "sample.xoo", 1024 * 1024 + 1);
writeFile(srcDir, "another.xoo", "Sample xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
// set limit to 1MB
.put("sonar.filesize.limit", "1")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(logTester.logs())
.contains(format("File '%s' is bigger than 1MB and as consequence is removed from the analysis scope.", fileGreaterThanLimit.getAbsolutePath()));
}
@Test
public void analysisFailsSymbolicLinkWithoutTargetIsInTheFolder() throws IOException {
assumeFalse(SystemUtils.IS_OS_WINDOWS);
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File target = writeFile(srcDir, "target.xoo", 1024 * 1024 + 1);
Path link = Paths.get(srcDir.getPath(), "target_link.xoo");
Files.createSymbolicLink(link, target.toPath());
Files.delete(target.toPath());
AnalysisBuilder analysis = tester.newAnalysis()
.properties(builder.build());
assertThatThrownBy(analysis::execute)
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessageEndingWith(format("Unable to read file %s", link));
}
@Test
public void test_inclusions_on_multi_modules() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "tests");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "tests");
srcDirB.mkdirs();
writeFile(srcDirA, "sampleTestA.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sampleTestB.xoo", "Sample xoo\ncontent");
final ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "")
.put("sonar.tests", "tests")
.put("sonar.modules", "moduleA,moduleB");
AnalysisResult result = tester.newAnalysis()
.properties(builder.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
InputFile fileA = result.inputFile("moduleA/tests/sampleTestA.xoo");
assertThat(fileA).isNotNull();
InputFile fileB = result.inputFile("moduleB/tests/sampleTestB.xoo");
assertThat(fileB).isNotNull();
result = tester.newAnalysis()
.properties(builder
.put("sonar.test.inclusions", "moduleA/tests/**")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
fileA = result.inputFile("moduleA/tests/sampleTestA.xoo");
assertThat(fileA).isNotNull();
fileB = result.inputFile("moduleB/tests/sampleTestB.xoo");
assertThat(fileB).isNull();
}
@Test
public void test_module_level_inclusions_override_parent_on_multi_modules() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sampleA.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sampleB.xoo", "Sample xoo\ncontent");
final ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.inclusions", "**/*.php");
AnalysisResult result = tester.newAnalysis()
.properties(builder.build())
.execute();
assertThat(result.inputFiles()).isEmpty();
result = tester.newAnalysis()
.properties(builder
.put("moduleA.sonar.inclusions", "**/*.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
InputFile fileA = result.inputFile("moduleA/src/sampleA.xoo");
assertThat(fileA).isNotNull();
}
@Test
public void warn_user_for_outdated_scanner_side_inherited_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.exclusions", "src/sample.xoo")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sample.xoo");
assertThat(fileA).isNull();
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
assertThat(logTester.logs(Level.WARN))
.contains("Specifying module-relative paths at project level in the property 'sonar.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
@Test
public void support_global_server_side_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sample.xoo", "Sample xoo\ncontent");
tester.addGlobalServerSettings(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sample.xoo");
assertThat(fileA).isNull();
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
}
@Test
public void support_global_server_side_global_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sample.xoo", "Sample xoo\ncontent");
tester.addGlobalServerSettings(CoreProperties.GLOBAL_EXCLUSIONS_PROPERTY, "**/*.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sample.xoo");
assertThat(fileA).isNull();
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
}
@Test
public void warn_user_for_outdated_server_side_inherited_exclusions_for_multi_module_project() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sample.xoo", "Sample xoo\ncontent");
tester.addProjectServerSettings("sonar.exclusions", "src/sample.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.build())
.execute();
InputFile fileA = result.inputFile("moduleA/src/sample.xoo");
assertThat(fileA).isNull();
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
assertThat(logTester.logs(Level.WARN))
.contains("Specifying module-relative paths at project level in the property 'sonar.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
@Test
public void failForDuplicateInputFile() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
assertThatThrownBy(() -> tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,src/sample.xoo")
.build())
.execute())
.isInstanceOf(MessageException.class)
.hasMessage("File src/sample.xoo can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files");
}
// SONAR-9574
@Test
public void failForDuplicateInputFileInDifferentModules() throws IOException {
File srcDir = new File(baseDir, "module1/src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
assertThatThrownBy(() -> tester.newAnalysis()
.properties(builder
.put("sonar.sources", "module1/src")
.put("sonar.modules", "module1")
.put("module1.sonar.sources", "src")
.build())
.execute())
.isInstanceOf(MessageException.class)
.hasMessage("File module1/src/sample.xoo can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files");
}
// SONAR-5330
@Test
public void scanProjectWithSourceSymlink() {
assumeTrue(!System2.INSTANCE.isOsWindows());
File projectDir = new File("test-resources/mediumtest/xoo/sample-with-symlink");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.exclusions", "**/*.xoo.measures,**/*.xoo.scm")
.property("sonar.test.exclusions", "**/*.xoo.measures,**/*.xoo.scm")
.property("sonar.scm.exclusions.disabled", "true")
.execute();
assertThat(result.inputFiles()).hasSize(3);
// check that symlink was not resolved to target
assertThat(result.inputFiles()).extractingResultOf("path").toString().startsWith(projectDir.toString());
}
// SONAR-6719
@Test
public void scanProjectWithWrongCase() {
// To please the quality gate, don't use assumeTrue, or the test will be reported as skipped
File projectDir = new File("test-resources/mediumtest/xoo/sample");
AnalysisBuilder analysis = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.sources", "XOURCES")
.property("sonar.tests", "TESTX")
.property("sonar.scm.exclusions.disabled", "true");
if (System2.INSTANCE.isOsWindows()) { // Windows is file path case-insensitive
AnalysisResult result = analysis.execute();
assertThat(result.inputFiles()).hasSize(8);
assertThat(result.inputFiles()).extractingResultOf("relativePath").containsOnly(
"testx/ClassOneTest.xoo.measures",
"xources/hello/helloscala.xoo.measures",
"xources/hello/HelloJava.xoo.measures",
"testx/ClassOneTest.xoo",
"xources/hello/HelloJava.xoo.scm",
"xources/hello/helloscala.xoo",
"testx/ClassOneTest.xoo.scm",
"xources/hello/HelloJava.xoo");
} else if (System2.INSTANCE.isOsMac()) {
AnalysisResult result = analysis.execute();
assertThat(result.inputFiles()).hasSize(8);
assertThat(result.inputFiles()).extractingResultOf("relativePath").containsOnly(
"TESTX/ClassOneTest.xoo.measures",
"XOURCES/hello/helloscala.xoo.measures",
"XOURCES/hello/HelloJava.xoo.measures",
"TESTX/ClassOneTest.xoo",
"XOURCES/hello/HelloJava.xoo.scm",
"XOURCES/hello/helloscala.xoo",
"TESTX/ClassOneTest.xoo.scm",
"XOURCES/hello/HelloJava.xoo");
} else {
assertThatThrownBy(() -> analysis.execute())
.isInstanceOf(MessageException.class)
.hasMessageContaining("The folder 'TESTX' does not exist for 'sample'");
}
}
@Test
public void indexAnyFile() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDir, "sample.other", "Sample other\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
assertThat(result.inputFile("src/sample.other").type()).isEqualTo(InputFile.Type.MAIN);
assertThat(result.inputFile("src/sample.other").relativePath()).isEqualTo("src/sample.other");
assertThat(result.inputFile("src/sample.other").language()).isNull();
}
@Test
public void scanMultiModuleProject() {
File projectDir = new File("test-resources/mediumtest/xoo/multi-modules-sample");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute();
assertThat(result.inputFiles()).hasSize(4);
}
@Test
public void deprecated_global_sensor_should_see_project_relative_paths() {
File projectDir = new File("test-resources/mediumtest/xoo/multi-modules-sample");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property(DeprecatedGlobalSensor.ENABLE_PROP, "true")
.execute();
assertThat(result.inputFiles()).hasSize(4);
assertThat(logTester.logs(Level.INFO)).contains(
"Deprecated Global Sensor: module_a/module_a1/src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo",
"Deprecated Global Sensor: module_a/module_a2/src/main/xoo/com/sonar/it/samples/modules/a2/HelloA2.xoo",
"Deprecated Global Sensor: module_b/module_b1/src/main/xoo/com/sonar/it/samples/modules/b1/HelloB1.xoo",
"Deprecated Global Sensor: module_b/module_b2/src/main/xoo/com/sonar/it/samples/modules/b2/HelloB2.xoo");
}
@Test
public void global_sensor_should_see_project_relative_paths() {
File projectDir = new File("test-resources/mediumtest/xoo/multi-modules-sample");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property(GlobalProjectSensor.ENABLE_PROP, "true")
.execute();
assertThat(result.inputFiles()).hasSize(4);
assertThat(logTester.logs(Level.INFO)).contains(
"Global Sensor: module_a/module_a1/src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo",
"Global Sensor: module_a/module_a2/src/main/xoo/com/sonar/it/samples/modules/a2/HelloA2.xoo",
"Global Sensor: module_b/module_b1/src/main/xoo/com/sonar/it/samples/modules/b1/HelloB1.xoo",
"Global Sensor: module_b/module_b2/src/main/xoo/com/sonar/it/samples/modules/b2/HelloB2.xoo");
}
@Test
public void scan_project_with_comma_in_source_path() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample,1.xoo", "Sample xoo\ncontent");
writeFile(baseDir, "another,2.xoo", "Sample xoo 2\ncontent");
File testDir = new File(baseDir, "test");
testDir.mkdir();
writeFile(testDir, "sampleTest,1.xoo", "Sample test xoo\ncontent");
writeFile(baseDir, "sampleTest,2.xoo", "Sample test xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src,\"another,2.xoo\"")
.put("sonar.tests", "\"test\",\"sampleTest,2.xoo\"")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(4);
}
@Test
public void language_without_publishAllFiles_should_not_auto_publish_files() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo3", "Sample xoo\ncontent");
writeFile(srcDir, "sample2.xoo3", "Sample xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.inputFiles())
.extracting(InputFile::filename, InputFile::language, f -> ((DefaultInputFile) f).isPublished())
.containsOnly(tuple("sample.xoo3", "xoo3", false), tuple("sample2.xoo3", "xoo3", false));
assertThat(result.getReportReader().readComponent(result.getReportReader().readMetadata().getRootComponentRef()).getChildRefCount()).isZero();
}
@Test
public void two_languages_with_same_extension() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDir, "sample.xoo2", "Sample xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(2);
AnalysisBuilder analysisBuilder = tester.newAnalysis()
.properties(builder
.put("sonar.lang.patterns.xoo2", "**/*.xoo")
.build());
assertThatThrownBy(analysisBuilder::execute)
.isInstanceOf(MessageException.class)
.hasMessage(
"Language of file 'src" + File.separator
+ "sample.xoo' can not be decided as the file matches patterns of both sonar.lang.patterns.xoo : **/*.xoo and sonar.lang.patterns.xoo2 : **/*.xoo");
// SONAR-9561
result = tester.newAnalysis()
.properties(builder
.put("sonar.exclusions", "**/sample.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
}
@Test
public void log_all_exclusions_properties_per_modules() throws IOException {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
writeFile(srcDirA, "sample.xoo", "Sample xoo\ncontent");
writeFile(srcDirB, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.inclusions", "**/global.inclusions")
.put("sonar.test.inclusions", "**/global.test.inclusions")
.put("sonar.exclusions", "**/global.exclusions")
.put("sonar.test.exclusions", "**/global.test.exclusions")
.put("sonar.coverage.exclusions", "**/coverage.exclusions")
.put("sonar.cpd.exclusions", "**/cpd.exclusions")
.build())
.execute();
assertThat(logTester.logs(Level.INFO))
.containsSequence("Project configuration:",
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
" Excluded tests: **/global.test.exclusions",
" Excluded sources for coverage: **/coverage.exclusions",
" Excluded sources for duplication: **/cpd.exclusions",
"Indexing files of module 'moduleA'",
" Base dir: " + baseDirModuleA.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS),
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
" Excluded tests: **/global.test.exclusions",
" Excluded sources for coverage: **/coverage.exclusions",
" Excluded sources for duplication: **/cpd.exclusions",
"Indexing files of module 'moduleB'",
" Base dir: " + baseDirModuleB.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS),
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
" Excluded tests: **/global.test.exclusions",
" Excluded sources for coverage: **/coverage.exclusions",
" Excluded sources for duplication: **/cpd.exclusions",
"Indexing files of module 'com.foo.project'",
" Base dir: " + baseDir.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS),
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
" Excluded tests: **/global.test.exclusions",
" Excluded sources for coverage: **/coverage.exclusions",
" Excluded sources for duplication: **/cpd.exclusions");
}
@Test
public void ignore_files_outside_project_basedir() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample1.xoo", "Sample xoo\ncontent");
File outsideBaseDir = temp.newFolder().getCanonicalFile();
File xooFile2 = writeFile(outsideBaseDir, "another.xoo", "Sample xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src," + PathUtils.canonicalPath(xooFile2))
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(logTester.logs(Level.WARN)).contains("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
}
@Test
public void dont_log_warn_about_files_out_of_basedir_if_they_arent_included() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
writeFile(srcDir, "sample1.xoo", "Sample xoo\ncontent");
File outsideBaseDir = temp.newFolder().getCanonicalFile();
File xooFile2 = new File(outsideBaseDir, "another.xoo");
FileUtils.write(xooFile2, "Sample xoo 2\ncontent", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src," + PathUtils.canonicalPath(xooFile2))
.put("sonar.inclusions", "**/sample1.xoo")
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(logTester.logs(Level.WARN)).doesNotContain("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
}
@Test
public void ignore_files_outside_module_basedir() throws IOException {
File moduleA = new File(baseDir, "moduleA");
moduleA.mkdir();
writeFile(moduleA, "src/sampleA.xoo", "Sample xoo\ncontent");
File xooFile2 = writeFile(baseDir, "another.xoo", "Sample xoo 2\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.modules", "moduleA")
.put("moduleA.sonar.sources", "src," + PathUtils.canonicalPath(xooFile2))
.build())
.execute();
assertThat(result.inputFiles()).hasSize(1);
assertThat(logTester.logs(Level.WARN))
.contains("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in module basedir '" + new File(baseDir, "moduleA") + "'.");
}
@Test
public void exclusion_based_on_scm_info() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-with-ignored-file");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.exclusions", "**/*.xoo.ignore")
.property("sonar.test.exclusions", "**/*.xoo.ignore")
.execute();
assertThat(result.inputFile("xources/hello/ClassTwo.xoo")).isNull();
assertThat(result.inputFile("testx/ClassTwoTest.xoo")).isNull();
assertThat(result.inputFile("xources/hello/ClassOne.xoo")).isNotNull();
assertThat(result.inputFile("testx/ClassOneTest.xoo")).isNotNull();
}
@Test
public void no_exclusion_when_scm_exclusions_is_disabled() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-with-ignored-file");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.scm.exclusions.disabled", "true")
.property("sonar.exclusions", "**/*.xoo.ignore")
.property("sonar.test.exclusions", "**/*.xoo.ignore")
.execute();
assertThat(result.inputFiles()).hasSize(4);
assertThat(result.inputFile("xources/hello/ClassTwo.xoo")).isNotNull();
assertThat(result.inputFile("testx/ClassTwoTest.xoo")).isNotNull();
assertThat(result.inputFile("xources/hello/ClassOne.xoo")).isNotNull();
assertThat(result.inputFile("testx/ClassOneTest.xoo")).isNotNull();
}
@Test
public void index_basedir_by_default() throws IOException {
writeFile(baseDir, "sample.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.build())
.execute();
assertThat(logTester.logs()).contains("1 file indexed");
assertThat(result.inputFile("sample.xoo")).isNotNull();
}
@Test
public void givenExclusionEndingWithOneWildcardWhenAnalysedThenOnlyDirectChildrenFilesShouldBeExcluded() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", true);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
// src/srcSubDir/srcSubSubDir/subSubSrc.xoo
File srcSubSubDir = createDir(srcSubDir, "srcSubSubDir", true);
writeFile(srcSubSubDir, "subSubSrc.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.exclusions", "src/srcSubDir/*")
.build())
.execute();
assertAnalysedFiles(result, "src/src.xoo", "src/srcSubDir/srcSubSubDir/subSubSrc.xoo");
}
@Test
public void givenPathsWithoutReadPermissionWhenAllChildrenAreExcludedThenScannerShouldSkipIt() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", false);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
// src/srcSubDir2/srcSub2.xoo
File srcSubDir2 = createDir(srcDir, "srcSubDir2", true);
boolean fileNotReadable = writeFile(srcSubDir2, "srcSub2.xoo", "Sample 2 xoo\ncontent").setReadable(false);
assumeTrue(fileNotReadable);
// src/srcSubDir2/srcSubSubDir2/srcSubSub2.xoo
File srcSubSubDir2 = createDir(srcSubDir2, "srcSubSubDir2", false);
writeFile(srcSubSubDir2, "srcSubSub2.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.exclusions", "src/srcSubDir/**/*,src/srcSubDir2/**/*")
.build())
.execute();
assertAnalysedFiles(result, "src/src.xoo");
assertThat(logTester.logs()).contains("1 file ignored because of inclusion/exclusion patterns");
}
@Test
public void givenFileWithoutAccessWhenChildrenAreExcludedThenThenScanShouldFail() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
boolean fileNotReadable = writeFile(srcDir, "src.xoo", "Sample xoo\ncontent").setReadable(false);
assumeTrue(fileNotReadable);
AnalysisBuilder result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.exclusions", "src/src.xoo/**/*") // incorrect pattern, but still the scan should fail if src.xoo is not accessible
.build());
assertThatThrownBy(result::execute)
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessageStartingWith(format("java.lang.IllegalStateException: Unable to read file"));
}
@Test
public void givenDirectoryWithoutReadPermissionWhenIncludedThenScanShouldFail() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", false);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
AnalysisBuilder result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.exclusions", "src/srcSubDir/*") // srcSubDir should not be excluded unless all children are excluded (src/srcSubDir/**/*)
.build());
assertThatThrownBy(result::execute)
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessageEndingWith(format("Failed to index files"));
}
@Test
public void givenDirectoryWhenAllChildrenAreExcludedThenSkippedFilesShouldBeReported() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", true);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
// src/srcSubDir2/srcSub2.xoo
File srcSubDir2 = createDir(srcDir, "srcSubDir2", true);
boolean fileNotReadable = writeFile(srcSubDir2, "srcSub2.xoo", "Sample 2 xoo\ncontent").setReadable(false);
assumeTrue(fileNotReadable);
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.exclusions", "src/srcSubDir/**/*,src/srcSubDir2/*")
.build())
.execute();
assertAnalysedFiles(result, "src/src.xoo");
assertThat(logTester.logs()).contains("2 files ignored because of inclusion/exclusion patterns");
}
@Ignore("Fails until we can pattern match inclusions to directories, not only files.")
@Test
public void givenDirectoryWithoutReadPermissionWhenNotIncludedThenScanShouldSkipIt() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", true);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
// src/srcSubDir2/srcSub2.xoo
File srcSubDir2 = createDir(srcDir, "srcSubDir2", false);
writeFile(srcSubDir2, "srcSub2.xoo", "Sample xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.inclusions", "src/srcSubDir/**/*")
.build())
.execute();
assertAnalysedFiles(result, "src/srcSubDir/srcSub.xoo");
}
@Test
public void givenDirectoryWithoutReadPermissionUnderSourcesWhenAnalysedThenShouldFail() throws IOException {
// src/src.xoo
File srcDir = createDir(baseDir, "src", true);
writeFile(srcDir, "src.xoo", "Sample xoo 2\ncontent");
// src/srcSubDir/srcSub.xoo
File srcSubDir = createDir(srcDir, "srcSubDir", false);
writeFile(srcSubDir, "srcSub.xoo", "Sample xoo\ncontent");
AnalysisBuilder result = tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build());
assertThatThrownBy(result::execute)
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessageEndingWith(format("Failed to index files"));
}
private static void assertAnalysedFiles(AnalysisResult result, String... files) {
assertThat(result.inputFiles().stream().map(InputFile::toString).collect(Collectors.toList())).contains(files);
}
private File createDir(File parentDir, String name, boolean isReadable) {
File dir = new File(parentDir, name);
dir.mkdir();
boolean fileSystemOperationSucceded = dir.setReadable(isReadable);
assumeTrue(fileSystemOperationSucceded); //On windows + java there is no reliable way to play with readable/not readable flag
return dir;
}
private File writeFile(File parent, String name, String content) throws IOException {
File file = new File(parent, name);
FileUtils.write(file, content, StandardCharsets.UTF_8);
return file;
}
private File writeFile(File parent, String name, long size) throws IOException {
File file = new File(parent, name);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(size);
raf.close();
return file;
}
}
| 48,941 | 37.146532 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/fs/NoLanguagesPluginsMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.fs;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.springframework.beans.factory.BeanCreationException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class NoLanguagesPluginsMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester();
@Test
public void testNoLanguagePluginsInstalled() throws Exception {
File projectDir = copyProject("test-resources/mediumtest/xoo/sample");
assertThatThrownBy(() -> tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.execute())
.isInstanceOf(BeanCreationException.class)
.hasRootCauseMessage("No language plugins are installed.");
}
private File copyProject(String path) throws Exception {
File projectDir = temp.newFolder();
File originalProjectDir = new File(path);
FileUtils.copyDirectory(originalProjectDir, projectDir, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".sonar")));
return projectDir;
}
}
| 2,159 | 36.241379 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/fs/ProjectBuilderMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.fs;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarEdition;
import org.sonar.api.batch.bootstrap.ProjectBuilder;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
public class ProjectBuilderMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ProjectBuilder projectBuilder = mock(ProjectBuilder.class);
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.setEdition(SonarEdition.SONARCLOUD)
.registerPlugin("xoo", new XooPluginWithBuilder(projectBuilder))
.addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo");
private static class XooPluginWithBuilder extends XooPlugin {
private ProjectBuilder builder;
XooPluginWithBuilder(ProjectBuilder builder) {
this.builder = builder;
}
@Override
public void define(Context context) {
super.define(context);
context.addExtension(builder);
}
}
@Test
public void testProjectReactorValidation() throws IOException {
File baseDir = prepareProject();
doThrow(new IllegalStateException("My error message")).when(projectBuilder).build(any(ProjectBuilder.Context.class));
assertThatThrownBy(() -> tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", ".")
.put("sonar.xoo.enableProjectBuilder", "true")
.build())
.execute())
.isInstanceOf(MessageException.class)
.hasMessageContaining("Failed to execute project builder")
.hasCauseInstanceOf(IllegalStateException.class);
}
@Test
public void testProjectBuilder() throws IOException {
File baseDir = prepareProject();
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", ".")
.put("sonar.verbose", "true")
.put("sonar.xoo.enableProjectBuilder", "true")
.build())
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("module1/src/sample.xoo"));
assertThat(issues).hasSize(10);
assertThat(issues)
.extracting("msg", "textRange.startLine", "gap")
.contains(tuple("This issue is generated on each line", 1, 0.0));
}
private File prepareProject() throws IOException {
File baseDir = temp.newFolder();
File module1Dir = new File(baseDir, "module1");
module1Dir.mkdir();
File srcDir = new File(module1Dir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
return baseDir;
}
}
| 4,602 | 34.137405 | 121 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/highlighting/HighlightingMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.highlighting;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
public class HighlightingMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Test
public void computeSyntaxHighlightingOnTempProject() throws IOException {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xoohighlightingFile = new File(srcDir, "sample.xoo.highlighting");
FileUtils.write(xooFile, "Sample xoo\ncontent plop");
FileUtils.write(xoohighlightingFile, "1:0:2:0:s\n2:0:2:8:k");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.highlightingTypeFor(file, 1, 0)).containsExactly(TypeOfText.STRING);
assertThat(result.highlightingTypeFor(file, 1, 9)).containsExactly(TypeOfText.STRING);
assertThat(result.highlightingTypeFor(file, 2, 0)).containsExactly(TypeOfText.KEYWORD);
assertThat(result.highlightingTypeFor(file, 2, 8)).isEmpty();
}
@Test
public void saveTwice() throws IOException {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent plop");
AnalysisBuilder analysisBuilder = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.put("sonar.it.savedatatwice", "true")
.build());;
assertThatThrownBy(() -> analysisBuilder.execute())
.isInstanceOf(UnsupportedOperationException.class)
.hasMessageContaining("Trying to save highlighting twice for the same file is not supported");
}
@Test
public void computeInvalidOffsets() throws IOException {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xoohighlightingFile = new File(srcDir, "sample.xoo.highlighting");
FileUtils.write(xooFile, "Sample xoo\ncontent plop");
FileUtils.write(xoohighlightingFile, "1:0:1:10:s\n2:18:2:18:k");
AnalysisBuilder analysisBuilder = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build());
assertThatThrownBy(() -> analysisBuilder.execute())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Error processing line 2")
.hasCauseInstanceOf(IllegalArgumentException.class);
}
}
| 5,246 | 38.451128 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/ChecksMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class ChecksMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.addRule("TemplateRule_1234", "xoo", "TemplateRule_1234", "A template rule")
.addRule("TemplateRule_1235", "xoo", "TemplateRule_1235", "Another template rule")
.activateRule(createActiveRuleWithParam("xoo", "TemplateRule_1234", "TemplateRule", "A template rule", "MAJOR", null, "xoo", "line", "1"))
.activateRule(createActiveRuleWithParam("xoo", "TemplateRule_1235", "TemplateRule", "Another template rule", "MAJOR", null, "xoo", "line", "2"));
@Test
public void testCheckWithTemplate() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "foo\nbar");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("src/sample.xoo"));
// If the message is the rule name. it's set by the CE. See SONAR-11531
assertThat(issues)
.extracting("msg", "textRange.startLine")
.containsOnly(
tuple("", 1),
tuple("", 2));
}
private LoadedActiveRule createActiveRuleWithParam(String repositoryKey, String ruleKey, @Nullable String templateRuleKey, String name,
@Nullable String severity, @Nullable String internalKey, @Nullable String languag, String paramKey, String paramValue) {
LoadedActiveRule r = new LoadedActiveRule();
r.setInternalKey(internalKey);
r.setRuleKey(RuleKey.of(repositoryKey, ruleKey));
r.setName(name);
r.setTemplateRuleKey(templateRuleKey);
r.setLanguage(languag);
r.setSeverity(severity);
r.setDeprecatedKeys(emptySet());
Map<String, String> params = new HashMap<>();
params.put(paramKey, paramValue);
r.setParams(params);
return r;
}
}
| 4,225 | 37.072072 | 149 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/ExternalIssuesMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.ExternalIssue;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.scanner.protocol.output.ScannerReport.IssueType;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.OneExternalIssuePerLineSensor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class ExternalIssuesMediumIT {
@Rule
public LogTester logs = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin());
@Test
public void testOneIssuePerLine() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues).isEmpty();
List<ExternalIssue> externalIssues = result.externalIssuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(externalIssues).hasSize(8 /* lines */);
ExternalIssue issue = externalIssues.get(0);
assertThat(issue.getTextRange().getStartLine()).isEqualTo(issue.getTextRange().getStartLine());
assertThat(result.adHocRules()).isEmpty();
}
@Test
public void testOneIssuePerLine_register_ad_hoc_rule() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.property(OneExternalIssuePerLineSensor.REGISTER_AD_HOC_RULE, "true")
.execute();
assertThat(result.adHocRules()).extracting(
ScannerReport.AdHocRule::getEngineId,
ScannerReport.AdHocRule::getRuleId,
ScannerReport.AdHocRule::getName,
ScannerReport.AdHocRule::getDescription,
ScannerReport.AdHocRule::getSeverity,
ScannerReport.AdHocRule::getType)
.containsExactlyInAnyOrder(
tuple(
OneExternalIssuePerLineSensor.ENGINE_ID,
OneExternalIssuePerLineSensor.RULE_ID,
"An ad hoc rule",
"blah blah",
Severity.BLOCKER,
IssueType.BUG));
}
@Test
public void testLoadIssuesFromJsonReport() throws URISyntaxException, IOException {
logs.setLevel(Level.DEBUG);
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.externalIssuesReportPaths", "externalIssues.json")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues).isEmpty();
List<ExternalIssue> externalIssues = result.externalIssuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(externalIssues).hasSize(2);
// precise issue location
ExternalIssue issue = externalIssues.get(0);
assertPreciseIssueLocation(issue);
// location on a line
issue = externalIssues.get(1);
assertIssueLocationLine(issue);
// One file-level issue in helloscala, with secondary location
List<ExternalIssue> externalIssues2 = result.externalIssuesFor(result.inputFile("xources/hello/helloscala.xoo"));
assertThat(externalIssues2).hasSize(1);
issue = externalIssues2.iterator().next();
assertSecondaryLocation(issue);
// one issue is located in a non-existing file
assertThat(logs.logs()).contains("External issues ignored for 1 unknown files, including: invalidFile");
}
private void assertSecondaryLocation(ExternalIssue issue) {
assertThat(issue.getFlowCount()).isEqualTo(2);
assertThat(issue.getMsg()).isEqualTo("fix the bug here");
assertThat(issue.getEngineId()).isEqualTo("externalXoo");
assertThat(issue.getRuleId()).isEqualTo("rule3");
assertThat(issue.getSeverity()).isEqualTo(Severity.MAJOR);
assertThat(issue.getType()).isEqualTo(IssueType.BUG);
assertThat(issue.hasTextRange()).isFalse();
assertThat(issue.getFlow(0).getLocationCount()).isOne();
assertThat(issue.getFlow(0).getLocation(0).getTextRange().getStartLine()).isOne();
assertThat(issue.getFlow(1).getLocationCount()).isOne();
assertThat(issue.getFlow(1).getLocation(0).getTextRange().getStartLine()).isEqualTo(3);
}
private void assertIssueLocationLine(ExternalIssue issue) {
assertThat(issue.getFlowCount()).isZero();
assertThat(issue.getMsg()).isEqualTo("fix the bug here");
assertThat(issue.getEngineId()).isEqualTo("externalXoo");
assertThat(issue.getRuleId()).isEqualTo("rule2");
assertThat(issue.getSeverity()).isEqualTo(Severity.CRITICAL);
assertThat(issue.getType()).isEqualTo(IssueType.BUG);
assertThat(issue.getEffort()).isZero();
assertThat(issue.getTextRange().getStartLine()).isEqualTo(3);
assertThat(issue.getTextRange().getEndLine()).isEqualTo(3);
assertThat(issue.getTextRange().getStartOffset()).isZero();
assertThat(issue.getTextRange().getEndOffset()).isEqualTo(24);
}
private void assertPreciseIssueLocation(ExternalIssue issue) {
assertThat(issue.getFlowCount()).isZero();
assertThat(issue.getMsg()).isEqualTo("fix the issue here");
assertThat(issue.getEngineId()).isEqualTo("externalXoo");
assertThat(issue.getRuleId()).isEqualTo("rule1");
assertThat(issue.getSeverity()).isEqualTo(Severity.MAJOR);
assertThat(issue.getEffort()).isEqualTo(50L);
assertThat(issue.getType()).isEqualTo(IssueType.CODE_SMELL);
assertThat(issue.getTextRange().getStartLine()).isEqualTo(5);
assertThat(issue.getTextRange().getEndLine()).isEqualTo(5);
assertThat(issue.getTextRange().getStartOffset()).isEqualTo(3);
assertThat(issue.getTextRange().getEndOffset()).isEqualTo(41);
}
}
| 7,752 | 40.459893 | 117 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/IssuesMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.ExternalIssue;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.HasTagSensor;
import org.sonar.xoo.rule.OneExternalIssueOnProjectSensor;
import org.sonar.xoo.rule.OneExternalIssuePerLineSensor;
import org.sonar.xoo.rule.XooRulesDefinition;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class IssuesMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo");
@Before
public void setUp() throws Exception {
logTester.setLevel(Level.DEBUG);
}
@Test
public void testOneIssuePerLine() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues).hasSize(8 /* lines */);
List<ExternalIssue> externalIssues = result.externalIssuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(externalIssues).isEmpty();
}
@Test
public void testOneExternalIssuePerLine() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssuePerLineSensor.ACTIVATE, "true")
.execute();
List<ExternalIssue> externalIssues = result.externalIssuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(externalIssues).hasSize(8 /* lines */);
}
@Test
public void testOneExternalIssueOnProject() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property(OneExternalIssueOnProjectSensor.ACTIVATE, "true")
.execute();
List<ExternalIssue> externalIssues = result.externalIssuesFor(result.project());
assertThat(externalIssues).hasSize(1);
}
@Test
public void findActiveRuleByInternalKey() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.xoo.internalKey", "OneIssuePerLine.internal")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues).hasSize(8 /* lines */ + 1 /* file */);
}
@Test
public void testOverrideQProfileSeverity() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.oneIssuePerLine.forceSeverity", "CRITICAL")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues.get(0).getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL);
}
@Test
public void testIssueExclusionByRegexp() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.issue.ignore.allfile", "1")
.property("sonar.issue.ignore.allfile.1.fileRegexp", "object")
.execute();
assertThat(result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"))).hasSize(8 /* lines */);
assertThat(result.issuesFor(result.inputFile("xources/hello/helloscala.xoo"))).isEmpty();
}
@Test
public void testIssueExclusionByBlock() throws Exception {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "1\nSONAR-OFF 2\n3\n4\n5\nSONAR-ON 6\n7\n8\n9\n10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.property("sonar.issue.ignore.block", "1")
.property("sonar.issue.ignore.block.1.beginBlockRegexp", "SON.*-OFF")
.property("sonar.issue.ignore.block.1.endBlockRegexp", "SON.*-ON")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("src/sample.xoo"));
assertThat(issues).hasSize(5);
assertThat(issues)
.extracting("textRange.startLine")
.containsExactlyInAnyOrder(1, 7, 8, 9, 10);
}
@Test
public void testIssueExclusionByIgnoreMultiCriteria() throws Exception {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
activateTODORule();
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, "1\n2\n3 TODO\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
File xooFile11 = new File(srcDir, "sample11.xoo");
FileUtils.write(xooFile11, "1\n2\n3 TODO\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.property("sonar.issue.ignore.multicriteria", "1,2")
.property("sonar.issue.ignore.multicriteria.1.ruleKey", "xoo:HasTag")
.property("sonar.issue.ignore.multicriteria.1.resourceKey", "src/sample11.xoo")
.property("sonar.issue.ignore.multicriteria.2.ruleKey", "xoo:One*")
.property("sonar.issue.ignore.multicriteria.2.resourceKey", "src/sample?.xoo")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("src/sample1.xoo"));
assertThat(issues).hasSize(2);
issues = result.issuesFor(result.inputFile("src/sample11.xoo"));
assertThat(issues).hasSize(10);
}
@Test
public void warn_user_for_outdated_IssueExclusionByIgnoreMultiCriteria() throws Exception {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
tester
.addProjectServerSettings("sonar.issue.ignore.multicriteria", "1")
.addProjectServerSettings("sonar.issue.ignore.multicriteria.1.ruleKey", "*")
.addProjectServerSettings("sonar.issue.ignore.multicriteria.1.resourceKey", "src/sampleA.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).contains(
"Specifying module-relative paths at project level in property 'sonar.issue.ignore.multicriteria' is deprecated. To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
assertThat(issues).isEmpty();
issues = result.issuesFor(result.inputFile("moduleB/src/sampleB.xoo"));
assertThat(issues).hasSize(10);
}
@Test
public void warn_user_for_unsupported_module_level_IssueExclusion() throws Exception {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.sources", "src")
.put("sonar.scm.disabled", "true")
.put("sonar.issue.ignore.multicriteria", "1")
.put("sonar.issue.ignore.multicriteria.1.ruleKey", "*")
.put("sonar.issue.ignore.multicriteria.1.resourceKey", "*")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).isEmpty();
result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.sources", "src")
.put("sonar.scm.disabled", "true")
.put("moduleA.sonar.issue.ignore.multicriteria", "1")
.put("moduleA.sonar.issue.ignore.multicriteria.1.ruleKey", "*")
.put("moduleA.sonar.issue.ignore.multicriteria.1.resourceKey", "*")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).containsOnly(
"Specifying issue exclusions at module level is not supported anymore. Configure the property 'sonar.issue.ignore.multicriteria' and any other issue exclusions at project level.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
assertThat(issues).hasSize(10);
issues = result.issuesFor(result.inputFile("moduleB/src/sampleB.xoo"));
assertThat(issues).hasSize(10);
// SONAR-11850 The Maven scanner replicates properties defined on the root module to all modules
logTester.clear();
result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.sources", "src")
.put("sonar.scm.disabled", "true")
.put("sonar.issue.ignore.multicriteria", "1")
.put("sonar.issue.ignore.multicriteria.1.ruleKey", "*")
.put("sonar.issue.ignore.multicriteria.1.resourceKey", "*")
.put("moduleA.sonar.issue.ignore.multicriteria", "1")
.put("moduleA.sonar.issue.ignore.multicriteria.1.ruleKey", "*")
.put("moduleA.sonar.issue.ignore.multicriteria.1.resourceKey", "*")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
public void testIssueExclusionByEnforceMultiCriteria() throws Exception {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
activateTODORule();
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, "1\n2\n3 TODO\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
File xooFile11 = new File(srcDir, "sample11.xoo");
FileUtils.write(xooFile11, "1\n2\n3 TODO\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.property("sonar.issue.enforce.multicriteria", "1,2")
.property("sonar.issue.enforce.multicriteria.1.ruleKey", "xoo:HasTag")
.property("sonar.issue.enforce.multicriteria.1.resourceKey", "src/sample11.xoo")
.property("sonar.issue.enforce.multicriteria.2.ruleKey", "xoo:One*")
.property("sonar.issue.enforce.multicriteria.2.resourceKey", "src/sample?.xoo")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("src/sample1.xoo"));
assertThat(issues).hasSize(10);
issues = result.issuesFor(result.inputFile("src/sample11.xoo"));
assertThat(issues).hasSize(2);
}
@Test
public void warn_user_for_outdated_IssueExclusionByEnforceMultiCriteria() throws Exception {
File baseDir = temp.getRoot();
File baseDirModuleA = new File(baseDir, "moduleA");
File baseDirModuleB = new File(baseDir, "moduleB");
File srcDirA = new File(baseDirModuleA, "src");
srcDirA.mkdirs();
File srcDirB = new File(baseDirModuleB, "src");
srcDirB.mkdirs();
File xooFileA = new File(srcDirA, "sampleA.xoo");
FileUtils.write(xooFileA, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
File xooFileB = new File(srcDirB, "sampleB.xoo");
FileUtils.write(xooFileB, "1\n2\n3\n4\n5\n6 TODO\n7\n8\n9\n10", StandardCharsets.UTF_8);
tester
.addProjectServerSettings("sonar.issue.enforce.multicriteria", "1")
.addProjectServerSettings("sonar.issue.enforce.multicriteria.1.ruleKey", "*")
.addProjectServerSettings("sonar.issue.enforce.multicriteria.1.resourceKey", "src/sampleA.xoo");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA,moduleB")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).contains(
"Specifying module-relative paths at project level in property 'sonar.issue.enforce.multicriteria' is deprecated. To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
assertThat(issues).hasSize(10);
issues = result.issuesFor(result.inputFile("moduleB/src/sampleB.xoo"));
assertThat(issues).isEmpty();
}
private void activateTODORule() {
LoadedActiveRule r = new LoadedActiveRule();
r.setRuleKey(RuleKey.of("xoo", HasTagSensor.RULE_KEY));
r.setName("TODO");
r.setLanguage("xoo");
r.setSeverity("MAJOR");
r.setDeprecatedKeys(emptySet()
);
r.setParams(ImmutableMap.of("tag", "TODO"));
tester.activateRule(r);
}
@Test
public void testIssueDetails() throws IOException {
File baseDir = temp.newFolder();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("src/sample.xoo"));
assertThat(issues).hasSize(10);
assertThat(issues)
.extracting("msg", "textRange.startLine", "gap")
.contains(tuple("This issue is generated on each line", 1, 0.0));
}
@Test
public void testIssueFilter() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
AnalysisResult result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.property("sonar.xoo.excludeAllIssuesOnOddLines", "true")
.execute();
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/HelloJava.xoo"));
assertThat(issues).hasSize(4 /* even lines */);
}
}
| 18,927 | 40.237473 | 252 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/IssuesOnDirMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class IssuesOnDirMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssueOnDirPerFile", null, "One issue per line", "MINOR", "xoo", "xoo");
@Test
public void scanTempProject() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, "Sample1 xoo\ncontent");
File xooFile2 = new File(srcDir, "sample2.xoo");
FileUtils.write(xooFile2, "Sample2 xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.issuesFor(result.project())).hasSize(2);
}
@Test
public void issueOnRootFolder() throws IOException {
File baseDir = temp.getRoot();
File xooFile1 = new File(baseDir, "sample1.xoo");
FileUtils.write(xooFile1, "Sample1 xoo\ncontent");
File xooFile2 = new File(baseDir, "sample2.xoo");
FileUtils.write(xooFile2, "Sample2 xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", ".")
.build())
.execute();
assertThat(result.issuesFor(result.project())).hasSize(2);
}
}
| 3,605 | 34.009709 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/IssuesOnModuleMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class IssuesOnModuleMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerModule", null, "One issue per module", "MINOR", "xoo", "xoo");
@Test
public void scanTempProject() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile1 = new File(srcDir, "sample1.xoo");
FileUtils.write(xooFile1, "Sample1 xoo\ncontent");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(result.issuesFor(result.project())).hasSize(1);
}
}
| 2,608 | 34.256757 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/MultilineIssuesMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.Flow;
import org.sonar.scanner.protocol.output.ScannerReport.FlowType;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
import org.sonar.scanner.protocol.output.ScannerReport.IssueLocation;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class MultilineIssuesMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.addActiveRule("xoo", "MultilineIssue", null, "Multinile Issue", "MAJOR", null, "xoo");
private AnalysisResult result;
@Before
public void prepare() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample-multiline");
File tmpDir = temp.getRoot();
FileUtils.copyDirectory(projectDir, tmpDir);
result = tester
.newAnalysis(new File(tmpDir, "sonar-project.properties"))
.execute();
}
@Test
public void testIssueRange() {
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/Single.xoo"));
assertThat(issues).hasSize(1);
Issue issue = issues.get(0);
assertThat(issue.getMsg()).isEqualTo("Primary location of the issue in xoo code");
assertThat(issue.getTextRange().getStartLine()).isEqualTo(6);
assertThat(issue.getTextRange().getStartOffset()).isEqualTo(23);
assertThat(issue.getTextRange().getEndLine()).isEqualTo(6);
assertThat(issue.getTextRange().getEndOffset()).isEqualTo(50);
}
@Test
public void testMultilineIssueRange() {
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/Multiline.xoo"));
assertThat(issues).hasSize(1);
Issue issue = issues.get(0);
assertThat(issue.getMsg()).isEqualTo("Primary location of the issue in xoo code");
assertThat(issue.getTextRange().getStartLine()).isEqualTo(6);
assertThat(issue.getTextRange().getStartOffset()).isEqualTo(23);
assertThat(issue.getTextRange().getEndLine()).isEqualTo(7);
assertThat(issue.getTextRange().getEndOffset()).isEqualTo(23);
}
@Test
public void testFlowWithSingleLocation() {
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/Multiple.xoo"));
assertThat(issues).hasSize(1);
Issue issue = issues.get(0);
assertThat(issue.getMsg()).isEqualTo("Primary location of the issue in xoo code");
assertThat(issue.getTextRange().getStartLine()).isEqualTo(6);
assertThat(issue.getTextRange().getStartOffset()).isEqualTo(23);
assertThat(issue.getTextRange().getEndLine()).isEqualTo(6);
assertThat(issue.getTextRange().getEndOffset()).isEqualTo(50);
assertThat(issue.getFlowList()).hasSize(1);
Flow flow = issue.getFlow(0);
assertThat(flow.getLocationList()).hasSize(1);
IssueLocation additionalLocation = flow.getLocation(0);
assertThat(additionalLocation.getMsg()).isEqualTo("Xoo code, flow step #1");
assertThat(additionalLocation.getTextRange().getStartLine()).isEqualTo(7);
assertThat(additionalLocation.getTextRange().getStartOffset()).isEqualTo(26);
assertThat(additionalLocation.getTextRange().getEndLine()).isEqualTo(7);
assertThat(additionalLocation.getTextRange().getEndOffset()).isEqualTo(53);
}
@Test
public void testFlowsWithMultipleElements() {
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/WithFlow.xoo"));
assertThat(issues).hasSize(1);
Issue issue = issues.get(0);
assertThat(issue.getFlowList()).hasSize(1);
Flow flow = issue.getFlow(0);
assertThat(flow.getLocationList()).hasSize(2);
// TODO more assertions
}
@Test
public void testFlowsWithTypes() {
List<Issue> issues = result.issuesFor(result.inputFile("xources/hello/FlowTypes.xoo"));
assertThat(issues).hasSize(1);
Issue issue = issues.get(0);
assertThat(issue.getFlowList()).hasSize(3);
assertThat(issue.getFlowList()).extracting(Flow::getType, Flow::getDescription, f -> f.getLocationList().size())
.containsExactly(
tuple(FlowType.DATA, "flow #1", 1),
tuple(FlowType.UNDEFINED, "", 1),
tuple(FlowType.EXECUTION, "flow #3", 1));
}
}
| 5,606 | 39.630435 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/issues/PreviewMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.issues;
import com.google.common.collect.ImmutableMap;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class PreviewMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester();
@Test
public void failWhenUsingPreviewMode() {
try {
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.analysis.mode", "preview").build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e).isInstanceOf(MessageException.class).hasMessage("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter.");
}
}
@Test
public void failWhenUsingIssuesMode() {
try {
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.analysis.mode", "issues").build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e).isInstanceOf(MessageException.class).hasMessage("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter.");
}
}
}
| 2,400 | 34.835821 | 197 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/log/ExceptionHandlingMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.log;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Priority;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import org.sonar.batch.bootstrapper.Batch;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonar.scanner.repository.settings.GlobalSettingsLoader;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExceptionHandlingMediumIT {
private Batch batch;
private static ErrorGlobalSettingsLoader loader;
@BeforeClass
public static void beforeClass() {
loader = new ErrorGlobalSettingsLoader();
}
public void setUp(boolean verbose) {
Batch.Builder builder = Batch.builder()
.setEnableLoggingConfiguration(true)
.addComponents(
loader,
new EnvironmentInformation("mediumTest", "1.0"));
if (verbose) {
builder.setGlobalProperties(Collections.singletonMap("sonar.verbose", "true"));
}
batch = builder.build();
}
@Test
public void test() throws Exception {
setUp(false);
loader.withCause = false;
assertThatThrownBy(() -> batch.execute())
.isInstanceOf(MessageException.class)
.hasMessage("Error loading settings");
}
@Test
public void testWithCause() throws Exception {
setUp(false);
loader.withCause = true;
assertThatThrownBy(() -> batch.execute())
.isInstanceOf(MessageException.class)
.hasMessage("Error loading settings")
.hasCauseInstanceOf(Throwable.class)
.hasRootCauseMessage("Code 401");
}
@Test
public void testWithVerbose() {
setUp(true);
assertThatThrownBy(() -> batch.execute())
.isInstanceOf(UnsatisfiedDependencyException.class)
.hasMessageContaining("Error loading settings");
}
@Priority(1)
private static class ErrorGlobalSettingsLoader implements GlobalSettingsLoader {
boolean withCause = false;
@Override
public Map<String, String> loadGlobalSettings() {
if (withCause) {
IllegalStateException cause = new IllegalStateException("Code 401");
throw MessageException.of("Error loading settings", cause);
} else {
throw MessageException.of("Error loading settings");
}
}
}
}
| 3,218 | 30.252427 | 85 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/log/LogListenerIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.log;
import com.google.common.collect.ImmutableMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.batch.bootstrapper.LogOutput;
import org.sonar.batch.bootstrapper.LogOutput.Level;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class LogListenerIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private Pattern simpleTimePattern = Pattern.compile("\\d{2}:\\d{2}:\\d{2}");
private List<LogEvent> logOutput;
private StringBuilder logOutputStr;
private ByteArrayOutputStream stdOutTarget;
private ByteArrayOutputStream stdErrTarget;
private static PrintStream savedStdOut;
private static PrintStream savedStdErr;
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.setLogOutput(new SimpleLogListener());
private File baseDir;
private ImmutableMap.Builder<String, String> builder;
@BeforeClass
public static void backupStdStreams() {
savedStdOut = System.out;
savedStdErr = System.err;
}
@AfterClass
public static void resumeStdStreams() {
if (savedStdOut != null) {
System.setOut(savedStdOut);
}
if (savedStdErr != null) {
System.setErr(savedStdErr);
}
}
@Before
public void prepare() {
System.out.flush();
System.err.flush();
stdOutTarget = new ByteArrayOutputStream();
stdErrTarget = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdOutTarget));
System.setErr(new PrintStream(stdErrTarget));
// logger from the batch might write to it asynchronously
logOutput = Collections.synchronizedList(new LinkedList<>());
logOutputStr = new StringBuilder();
baseDir = temp.getRoot();
builder = ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project");
}
private void assertNoStdOutput() {
assertThat(new String(stdOutTarget.toByteArray())).isEmpty();
assertThat(new String(stdErrTarget.toByteArray())).isEmpty();
}
/**
* Check that log message is not formatted, i.e. has no log level and timestamp.
*/
private void assertMsgClean(String msg) {
// FP: [JOURNAL_FLUSHER] WARNING Journal flush operation took 2,093ms last 8 cycles average is 262ms
if (msg.contains("[JOURNAL_FLUSHER]")) {
return;
}
for (Level l : Level.values()) {
assertThat(msg).doesNotContain(l.toString());
}
Matcher matcher = simpleTimePattern.matcher(msg);
assertThat(matcher.find()).isFalse();
}
@Test
public void testChangeLogForAnalysis() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent", StandardCharsets.UTF_8);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.put("sonar.verbose", "true")
.build())
.execute();
synchronized (logOutput) {
for (LogEvent e : logOutput) {
savedStdOut.println("[captured]" + e.level + " " + e.msg);
}
}
// only done in DEBUG during analysis
assertThat(logOutputStr.toString()).contains("Post-jobs : ");
}
@Test
public void testNoStdLog() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent", StandardCharsets.UTF_8);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertNoStdOutput();
assertThat(logOutput).isNotEmpty();
synchronized (logOutput) {
for (LogEvent e : logOutput) {
savedStdOut.println("[captured]" + e.level + " " + e.msg);
}
}
}
@Test
public void testNoFormattedMsgs() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent", StandardCharsets.UTF_8);
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
assertNoStdOutput();
synchronized (logOutput) {
for (LogEvent e : logOutput) {
assertMsgClean(e.msg);
savedStdOut.println("[captured]" + e.level + " " + e.msg);
}
}
}
// SONAR-7540
@Test
public void testStackTrace() throws IOException {
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\ncontent");
File xooFileMeasure = new File(srcDir, "sample.xoo.measures");
FileUtils.write(xooFileMeasure, "foo:bar", StandardCharsets.UTF_8);
try {
tester.newAnalysis()
.properties(builder
.put("sonar.sources", "src")
.build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e.getMessage()).contains("Error processing line 1");
}
assertNoStdOutput();
synchronized (logOutput) {
for (LogEvent e : logOutput) {
if (e.level == Level.ERROR) {
assertThat(e.msg).contains("Error processing line 1 of file", "src" + File.separator + "sample.xoo.measures",
"java.lang.IllegalStateException: Unknown metric with key: foo",
"at org.sonar.xoo.lang.MeasureSensor.saveMeasure");
}
}
}
}
private class SimpleLogListener implements LogOutput {
@Override
public void log(String msg, Level level) {
logOutput.add(new LogEvent(msg, level));
logOutputStr.append(msg).append("\n");
}
}
private static class LogEvent {
String msg;
Level level;
LogEvent(String msg, Level level) {
this.msg = msg;
this.level = level;
}
}
}
| 7,677 | 28.875486 | 119 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/measures/MeasuresMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.measures;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.Measure;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.Assert.fail;
public class MeasuresMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
private File srcDir;
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Before
public void setUp() throws Exception {
baseDir = temp.newFolder();
srcDir = new File(baseDir, "src");
srcDir.mkdir();
}
@Test
public void failIfTryingToSaveServerSideMeasure() throws IOException {
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\n\ncontent", StandardCharsets.UTF_8);
File measures = new File(srcDir, "sample.xoo.measures");
FileUtils.write(measures, "new_lines:2", StandardCharsets.UTF_8);
try {
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e)
.hasCauseInstanceOf(UnsupportedOperationException.class)
.hasStackTraceContaining("Metric 'new_lines' should not be computed by a Sensor");
}
}
@Test
public void lineMeasures() throws IOException {
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\n\n\ncontent", StandardCharsets.UTF_8);
File lineMeasures = new File(srcDir, "sample.xoo.linemeasures");
FileUtils.write(lineMeasures, "ncloc_data:1=1;2=0;4=1", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
Map<String, List<Measure>> allMeasures = result.allMeasures();
assertThat(allMeasures.get("com.foo.project:src/sample.xoo")).extracting("metricKey", "intValue.value", "stringValue.value")
.containsExactly(tuple("ncloc_data", 0, "1=1;4=1"));
}
@Test
public void projectLevelMeasures() throws IOException {
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\n\n\ncontent", StandardCharsets.UTF_8);
File projectMeasures = new File(baseDir, "module.measures");
FileUtils.write(projectMeasures, "tests:10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
Map<String, List<Measure>> allMeasures = result.allMeasures();
assertThat(allMeasures.get("com.foo.project"))
.extracting("metricKey", "intValue.value", "stringValue.value")
.containsExactly(tuple("tests", 10, ""));
}
@Test
public void warnWhenSavingFolderMeasure() throws IOException {
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\n\n\ncontent", StandardCharsets.UTF_8);
File folderMeasures = new File(srcDir, "folder.measures");
FileUtils.write(folderMeasures, "tests:10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
}
@Test
public void warnWhenSavingModuleMeasure() throws IOException {
File moduleDir = new File(baseDir, "moduleA");
moduleDir.mkdirs();
srcDir = new File(moduleDir, "src");
File xooFile = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile, "Sample xoo\n\n\ncontent", StandardCharsets.UTF_8);
File moduleMeasures = new File(moduleDir, "module.measures");
FileUtils.write(moduleMeasures, "tests:10", StandardCharsets.UTF_8);
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.modules", "moduleA")
.put("sonar.sources", "src")
.build())
.execute();
assertThat(logTester.logs(Level.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
}
}
| 6,600 | 35.469613 | 154 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/scm/ScmMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.scm;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.assertj.core.util.Files;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.SonarEdition;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Changesets.Changeset;
import org.sonar.scanner.protocol.output.ScannerReport.Component;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.repository.FileData;
import org.sonar.xoo.XooPlugin;
import org.sonar.xoo.rule.XooRulesDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class ScmMediumIT {
private static final String MISSING_BLAME_INFORMATION_FOR_THE_FOLLOWING_FILES = "Missing blame information for the following files:";
private static final String CHANGED_CONTENT_SCM_ON_SERVER_XOO = "src/changed_content_scm_on_server.xoo";
private static final String NO_BLAME_SCM_ON_SERVER_XOO = "src/no_blame_scm_on_server.xoo";
private static final String SAME_CONTENT_SCM_ON_SERVER_XOO = "src/same_content_scm_on_server.xoo";
private static final String SAME_CONTENT_NO_SCM_ON_SERVER_XOO = "src/same_content_no_scm_on_server.xoo";
private static final String SAMPLE_XOO_CONTENT = "Sample xoo\ncontent";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.setEdition(SonarEdition.COMMUNITY)
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
.addRules(new XooRulesDefinition())
// active a rule just to be sure that xoo files are published
.addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null)
.addFileData(CHANGED_CONTENT_SCM_ON_SERVER_XOO, new FileData(DigestUtils.md5Hex(SAMPLE_XOO_CONTENT), null))
.addFileData(SAME_CONTENT_NO_SCM_ON_SERVER_XOO, new FileData(DigestUtils.md5Hex(SAMPLE_XOO_CONTENT), null))
.addFileData(SAME_CONTENT_SCM_ON_SERVER_XOO, new FileData(DigestUtils.md5Hex(SAMPLE_XOO_CONTENT), "1.1"))
.addFileData(NO_BLAME_SCM_ON_SERVER_XOO, new FileData(DigestUtils.md5Hex(SAMPLE_XOO_CONTENT), "1.1"));
@Test
public void testScmMeasure() throws IOException, URISyntaxException {
File baseDir = prepareProject();
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.scm.provider", "xoo")
.build())
.execute();
ScannerReport.Changesets fileScm = getChangesets(baseDir, "src/sample.xoo");
assertThat(fileScm.getChangesetIndexByLineList()).hasSize(5);
Changeset changesetLine1 = fileScm.getChangeset(fileScm.getChangesetIndexByLine(0));
assertThat(changesetLine1.getAuthor()).isEmpty();
Changeset changesetLine2 = fileScm.getChangeset(fileScm.getChangesetIndexByLine(1));
assertThat(changesetLine2.getAuthor()).isEqualTo(getNonAsciiAuthor().toLowerCase());
Changeset changesetLine3 = fileScm.getChangeset(fileScm.getChangesetIndexByLine(2));
assertThat(changesetLine3.getAuthor()).isEqualTo("julien");
Changeset changesetLine4 = fileScm.getChangeset(fileScm.getChangesetIndexByLine(3));
assertThat(changesetLine4.getAuthor()).isEqualTo("julien");
Changeset changesetLine5 = fileScm.getChangeset(fileScm.getChangesetIndexByLine(4));
assertThat(changesetLine5.getAuthor()).isEqualTo("simon");
}
private ScannerReport.Changesets getChangesets(File baseDir, String path) {
File reportDir = new File(baseDir, ".sonar/scanner-report");
FileStructure fileStructure = new FileStructure(reportDir);
ScannerReportReader reader = new ScannerReportReader(fileStructure);
Component project = reader.readComponent(reader.readMetadata().getRootComponentRef());
for (Integer fileRef : project.getChildRefList()) {
Component file = reader.readComponent(fileRef);
if (file.getProjectRelativePath().equals(path)) {
return reader.readChangesets(file.getRef());
}
}
return null;
}
@Test
public void noScmOnEmptyFile() throws IOException, URISyntaxException {
File baseDir = prepareProject();
// Clear file content
FileUtils.write(new File(baseDir, "src/sample.xoo"), "");
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.put("sonar.scm.provider", "xoo")
.build())
.execute();
ScannerReport.Changesets changesets = getChangesets(baseDir, "src/sample.xoo");
assertThat(changesets).isNull();
}
@Test
public void log_files_with_missing_blame() throws IOException, URISyntaxException {
logTester.setLevel(Level.DEBUG);
File baseDir = prepareProject();
File xooFileWithoutBlame = new File(baseDir, "src/sample_no_blame.xoo");
FileUtils.write(xooFileWithoutBlame, "Sample xoo\ncontent\n3\n4\n5", StandardCharsets.UTF_8);
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.put("sonar.scm.provider", "xoo")
.build())
.execute();
ScannerReport.Changesets file1Scm = getChangesets(baseDir, "src/sample.xoo");
assertThat(file1Scm).isNotNull();
ScannerReport.Changesets fileWithoutBlameScm = getChangesets(baseDir, "src/sample_no_blame.xoo");
assertThat(fileWithoutBlameScm).isNull();
assertThat(logTester.logs()).containsSubsequence("SCM Publisher 2 source files to be analyzed", MISSING_BLAME_INFORMATION_FOR_THE_FOLLOWING_FILES,
" * src/sample_no_blame.xoo");
assertThat(logTester.logs().stream().anyMatch(s -> Pattern.matches("SCM Publisher 1/2 source file have been analyzed \\(done\\) \\| time=[0-9]+ms", s))).isTrue();
}
// SONAR-6397
@Test
public void optimize_blame() throws IOException, URISyntaxException {
logTester.setLevel(Level.DEBUG);
File baseDir = prepareProject();
File changedContentScmOnServer = new File(baseDir, CHANGED_CONTENT_SCM_ON_SERVER_XOO);
FileUtils.write(changedContentScmOnServer, SAMPLE_XOO_CONTENT + "\nchanged", StandardCharsets.UTF_8);
File xooScmFile = new File(baseDir, CHANGED_CONTENT_SCM_ON_SERVER_XOO + ".scm");
FileUtils.write(xooScmFile,
// revision,author,dateTime
"1,foo,2013-01-04\n" +
"1,bar,2013-01-04\n" +
"2,biz,2014-01-04\n",
StandardCharsets.UTF_8);
File sameContentScmOnServer = new File(baseDir, SAME_CONTENT_SCM_ON_SERVER_XOO);
FileUtils.write(sameContentScmOnServer, SAMPLE_XOO_CONTENT, StandardCharsets.UTF_8);
// No need to write .scm file since this file should not be blamed
File noBlameScmOnServer = new File(baseDir, NO_BLAME_SCM_ON_SERVER_XOO);
FileUtils.write(noBlameScmOnServer, SAMPLE_XOO_CONTENT + "\nchanged", StandardCharsets.UTF_8);
// No .scm file to emulate a failure during blame
File sameContentNoScmOnServer = new File(baseDir, SAME_CONTENT_NO_SCM_ON_SERVER_XOO);
FileUtils.write(sameContentNoScmOnServer, SAMPLE_XOO_CONTENT, StandardCharsets.UTF_8);
xooScmFile = new File(baseDir, SAME_CONTENT_NO_SCM_ON_SERVER_XOO + ".scm");
FileUtils.write(xooScmFile,
// revision,author,dateTime
"1,foo,2013-01-04\n" +
"1,bar,2013-01-04\n",
StandardCharsets.UTF_8);
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.put("sonar.scm.provider", "xoo")
.build())
.execute();
assertThat(getChangesets(baseDir, "src/sample.xoo")).isNotNull();
assertThat(getChangesets(baseDir, CHANGED_CONTENT_SCM_ON_SERVER_XOO).getCopyFromPrevious()).isFalse();
assertThat(getChangesets(baseDir, SAME_CONTENT_SCM_ON_SERVER_XOO).getCopyFromPrevious()).isTrue();
assertThat(getChangesets(baseDir, SAME_CONTENT_NO_SCM_ON_SERVER_XOO).getCopyFromPrevious()).isFalse();
assertThat(getChangesets(baseDir, NO_BLAME_SCM_ON_SERVER_XOO)).isNull();
// 5 .xoo files + 3 .scm files, but only 4 marked for publishing. 1 file is SAME so not included in the total
assertThat(logTester.logs()).containsSubsequence("8 files indexed");
assertThat(logTester.logs()).containsSubsequence("SCM Publisher 4 source files to be analyzed");
assertThat(logTester.logs().stream().anyMatch(s -> Pattern.matches("SCM Publisher 3/4 source files have been analyzed \\(done\\) \\| time=[0-9]+ms", s))).isTrue();
assertThat(logTester.logs()).containsSubsequence(MISSING_BLAME_INFORMATION_FOR_THE_FOLLOWING_FILES, " * src/no_blame_scm_on_server.xoo");
}
@Test
public void forceReload() throws IOException, URISyntaxException {
File baseDir = prepareProject();
File xooFileNoScm = new File(baseDir, SAME_CONTENT_SCM_ON_SERVER_XOO);
FileUtils.write(xooFileNoScm, SAMPLE_XOO_CONTENT, StandardCharsets.UTF_8);
File xooScmFile = new File(baseDir, SAME_CONTENT_SCM_ON_SERVER_XOO + ".scm");
FileUtils.write(xooScmFile,
// revision,author,dateTime
"1,foo,2013-01-04\n" +
"1,bar,2013-01-04\n",
StandardCharsets.UTF_8);
AnalysisBuilder analysisBuilder = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.scm.provider", "xoo")
// Force reload
.put("sonar.scm.forceReloadAll", "true")
.build());
analysisBuilder.execute();
ScannerReport.Changesets file1Scm = getChangesets(baseDir, "src/sample.xoo");
assertThat(file1Scm).isNotNull();
ScannerReport.Changesets file2Scm = getChangesets(baseDir, SAME_CONTENT_SCM_ON_SERVER_XOO);
assertThat(file2Scm).isNotNull();
}
@Test
public void configureUsingScmURL() throws IOException, URISyntaxException {
File baseDir = prepareProject();
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.links.scm_dev", "scm:xoo:foobar")
.build())
.execute();
ScannerReport.Changesets file1Scm = getChangesets(baseDir, "src/sample.xoo");
assertThat(file1Scm).isNotNull();
}
@Test
public void testAutoDetection() throws IOException, URISyntaxException {
File baseDir = prepareProject();
new File(baseDir, ".xoo").createNewFile();
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.build())
.execute();
ScannerReport.Changesets file1Scm = getChangesets(baseDir, "src/sample.xoo");
assertThat(file1Scm).isNotNull();
}
private String getNonAsciiAuthor() {
return Files.contentOf(new File("test-resources/mediumtest/blameAuthor.txt"), StandardCharsets.UTF_8);
}
private File prepareProject() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile1 = new File(srcDir, "sample.xoo");
FileUtils.write(xooFile1, "Sample xoo\ncontent\n3\n4\n5", StandardCharsets.UTF_8);
File xooScmFile1 = new File(srcDir, "sample.xoo.scm");
FileUtils.write(xooScmFile1,
// revision,author,dateTime
"1,,2013-01-04\n" +
"2," + getNonAsciiAuthor() + ",2013-01-04\n" +
"3,julien,2013-02-03\n" +
"3,julien,2013-02-03\n" +
"4,simon,2013-03-04\n",
StandardCharsets.UTF_8);
return baseDir;
}
@Test
public void testDisableScmSensor() throws IOException, URISyntaxException {
File baseDir = prepareProject();
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.sources", "src")
.put("sonar.scm.disabled", "true")
.put("sonar.scm.provider", "xoo")
.put("sonar.cpd.xoo.skip", "true")
.build())
.execute();
ScannerReport.Changesets changesets = getChangesets(baseDir, "src/sample.xoo");
assertThat(changesets).isNull();
}
}
| 14,952 | 40.536111 | 167 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/symbol/SymbolMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.symbol;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
public class SymbolMediumIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Test
public void computeSymbolReferencesOnTempProject() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xooSymbolFile = new File(srcDir, "sample.xoo.symbol");
FileUtils.write(xooFile, "Sample xoo\ncontent\nanother xoo");
// Highlight xoo symbol
FileUtils.write(xooSymbolFile, "1:7:1:10,3:8:3:11");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.symbolReferencesFor(file, 1, 7)).containsOnly(ScannerReport.TextRange.newBuilder().setStartLine(3).setStartOffset(8).setEndLine(3).setEndOffset(11).build());
}
@Test
public void computeSymbolReferencesWithVariableLength() throws IOException {
File baseDir = temp.getRoot();
File srcDir = new File(baseDir, "src");
srcDir.mkdir();
File xooFile = new File(srcDir, "sample.xoo");
File xooSymbolFile = new File(srcDir, "sample.xoo.symbol");
FileUtils.write(xooFile, "Sample xoo\ncontent\nanother xoo\nyet another");
// Highlight xoo symbol
FileUtils.write(xooSymbolFile, "1:7:1:10,3:8:4:1");
AnalysisResult result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "scan")
.put("sonar.projectBaseDir", baseDir.getAbsolutePath())
.put("sonar.projectKey", "com.foo.project")
.put("sonar.projectName", "Foo Project")
.put("sonar.projectVersion", "1.0-SNAPSHOT")
.put("sonar.projectDescription", "Description of Foo Project")
.put("sonar.sources", "src")
.build())
.execute();
InputFile file = result.inputFile("src/sample.xoo");
assertThat(result.symbolReferencesFor(file, 1, 7)).containsOnly(ScannerReport.TextRange.newBuilder().setStartLine(3).setStartOffset(8).setEndLine(4).setEndOffset(1).build());
}
}
| 4,076 | 37.462264 | 179 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/tasks/TasksMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.tasks;
import com.google.common.collect.ImmutableMap;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.utils.MessageException;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class TasksMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("faketask", new FakePlugin());
@Test
public void failWhenCallingTask() {
try {
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "fake").build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e).isInstanceOf(MessageException.class).hasMessage("Tasks support was removed in SonarQube 7.6.");
}
}
@Test
public void failWhenCallingViews() {
try {
tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.put("sonar.task", "views").build())
.execute();
fail("Expected exception");
} catch (Exception e) {
assertThat(e).isInstanceOf(MessageException.class).hasMessage("The task 'views' was removed with SonarQube 7.1. You can safely remove this call since portfolios and applications are automatically re-calculated.");
}
}
private static class FakePlugin implements Plugin {
@Override
public void define(Context context) {
}
}
}
| 2,508 | 32.013158 | 219 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scanner/mediumtest/tests/GenericTestExecutionMediumIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.mediumtest.tests;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class GenericTestExecutionMediumIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
@Test
public void singleReport() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml")
.execute();
InputFile testFile = result.inputFile("testx/ClassOneTest.xoo");
assertThat(result.allMeasures().get(testFile.key())).extracting("metricKey", "intValue.value", "longValue.value")
.containsOnly(
tuple(CoreMetrics.TESTS_KEY, 3, 0L),
tuple(CoreMetrics.SKIPPED_TESTS_KEY, 1, 0L),
tuple(CoreMetrics.TEST_ERRORS_KEY, 1, 0L),
tuple(CoreMetrics.TEST_EXECUTION_TIME_KEY, 0, 1105L),
tuple(CoreMetrics.TEST_FAILURES_KEY, 1, 0L));
assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
}
@Test
public void twoReports() {
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
AnalysisResult result = tester
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml,unittest2.xml")
.execute();
InputFile testFile = result.inputFile("testx/ClassOneTest.xoo");
assertThat(result.allMeasures().get(testFile.key())).extracting("metricKey", "intValue.value", "longValue.value")
.containsOnly(
tuple(CoreMetrics.TESTS_KEY, 4, 0L),
tuple(CoreMetrics.SKIPPED_TESTS_KEY, 2, 0L),
tuple(CoreMetrics.TEST_ERRORS_KEY, 1, 0L),
tuple(CoreMetrics.TEST_EXECUTION_TIME_KEY, 0, 1610L),
tuple(CoreMetrics.TEST_FAILURES_KEY, 1, 0L));
assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
}
}
| 3,432 | 38.011364 | 117 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scm/svn/SvnBlameCommandIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scm.svn;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.ArgumentCaptor;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.BlameCommand.BlameInput;
import org.sonar.api.batch.scm.BlameCommand.BlameOutput;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.testfixtures.log.LogTester;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.wc2.compat.SvnCodec;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatus;
import org.tmatesoft.svn.core.wc.SVNStatusClient;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import org.tmatesoft.svn.core.wc2.SvnCheckout;
import org.tmatesoft.svn.core.wc2.SvnTarget;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@RunWith(Parameterized.class)
public class SvnBlameCommandIT {
/*
* Note about SONARSCSVN-11: The case of a project baseDir is in a subFolder of working copy is part of method tests by default
*/
private static final String DUMMY_JAVA = "src/main/java/org/dummy/Dummy.java";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private FileSystem fs;
private BlameInput input;
private String serverVersion;
private int wcVersion;
@Parameters(name = "SVN server version {0}, WC version {1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {{"1.6", 10}, {"1.7", 29}, {"1.8", 31}, {"1.9", 31}});
}
public SvnBlameCommandIT(String serverVersion, int wcVersion) {
this.serverVersion = serverVersion;
this.wcVersion = wcVersion;
}
@Before
public void prepare() {
fs = mock(FileSystem.class);
input = mock(BlameInput.class);
when(input.fileSystem()).thenReturn(fs);
}
@Test
public void testParsingOfOutput() throws Exception {
File repoDir = unzip("repo-svn.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn");
when(fs.baseDir()).thenReturn(baseDir);
DefaultInputFile inputFile = new TestInputFileBuilder("foo", DUMMY_JAVA)
.setLines(27)
.setModuleBaseDir(baseDir.toPath())
.build();
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(blameResult).blameResult(eq(inputFile), captor.capture());
List<BlameLine> result = captor.getValue();
assertThat(result).hasSize(27);
Date commitDate = new Date(1342691097393L);
BlameLine[] expected = IntStream.rangeClosed(1, 27).mapToObj(i -> new BlameLine().date(commitDate).revision("2").author("dgageot")).toArray(BlameLine[]::new);
assertThat(result).containsExactly(expected);
}
private File unzip(String repoName) throws IOException {
File repoDir = temp.newFolder();
try {
javaUnzip(Paths.get(this.getClass().getResource("test-repos").toURI()).resolve(serverVersion).resolve(repoName).toFile(), repoDir);
return repoDir;
} catch (URISyntaxException e) {
throw new IOException(e);
}
}
private File checkout(String scmUrl) throws Exception {
ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
ISVNAuthenticationManager isvnAuthenticationManager = SVNWCUtil.createDefaultAuthenticationManager(null, null, (char[]) null, false);
SVNClientManager svnClientManager = SVNClientManager.newInstance(options, isvnAuthenticationManager);
File out = temp.newFolder();
SVNUpdateClient updateClient = svnClientManager.getUpdateClient();
SvnCheckout co = updateClient.getOperationsFactory().createCheckout();
co.setUpdateLocksOnDemand(updateClient.isUpdateLocksOnDemand());
co.setSource(SvnTarget.fromURL(SVNURL.parseURIEncoded(scmUrl), SVNRevision.HEAD));
co.setSingleTarget(SvnTarget.fromFile(out));
co.setRevision(SVNRevision.HEAD);
co.setDepth(SVNDepth.INFINITY);
co.setAllowUnversionedObstructions(false);
co.setIgnoreExternals(updateClient.isIgnoreExternals());
co.setExternalsHandler(SvnCodec.externalsHandler(updateClient.getExternalsHandler()));
co.setTargetWorkingCopyFormat(wcVersion);
co.run();
return out;
}
@Test
public void testParsingOfOutputWithMergeHistory() throws Exception {
File repoDir = unzip("repo-svn-with-merge.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn/trunk");
when(fs.baseDir()).thenReturn(baseDir);
DefaultInputFile inputFile = new TestInputFileBuilder("foo", DUMMY_JAVA)
.setLines(27)
.setModuleBaseDir(baseDir.toPath())
.build();
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(blameResult).blameResult(eq(inputFile), captor.capture());
List<BlameLine> result = captor.getValue();
assertThat(result).hasSize(27);
Date commitDate = new Date(1342691097393L);
Date revision6Date = new Date(1415262184300L);
BlameLine[] expected = IntStream.rangeClosed(1, 27).mapToObj(i -> {
if (i == 2 || i == 24) {
return new BlameLine().date(revision6Date).revision("6").author("henryju");
} else {
return new BlameLine().date(commitDate).revision("2").author("dgageot");
}
}).toArray(BlameLine[]::new);
assertThat(result).containsExactly(expected);
}
@Test
public void shouldNotFailIfFileContainsLocalModification() throws Exception {
File repoDir = unzip("repo-svn.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn");
when(fs.baseDir()).thenReturn(baseDir);
DefaultInputFile inputFile = new TestInputFileBuilder("foo", DUMMY_JAVA)
.setLines(28)
.setModuleBaseDir(baseDir.toPath())
.build();
Files.write(baseDir.toPath().resolve(DUMMY_JAVA), "\n//foo".getBytes(), StandardOpenOption.APPEND);
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
verifyNoInteractions(blameResult);
}
// SONARSCSVN-7
@Test
public void shouldNotFailOnWrongFilename() throws Exception {
File repoDir = unzip("repo-svn.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn");
when(fs.baseDir()).thenReturn(baseDir);
DefaultInputFile inputFile = new TestInputFileBuilder("foo", DUMMY_JAVA.toLowerCase())
.setLines(27)
.setModuleBaseDir(baseDir.toPath())
.build();
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
verifyNoInteractions(blameResult);
}
@Test
public void shouldNotFailOnUncommitedFile() throws Exception {
File repoDir = unzip("repo-svn.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn");
when(fs.baseDir()).thenReturn(baseDir);
String relativePath = "src/main/java/org/dummy/Dummy2.java";
DefaultInputFile inputFile = new TestInputFileBuilder("foo", relativePath)
.setLines(28)
.setModuleBaseDir(baseDir.toPath())
.build();
Files.write(baseDir.toPath().resolve(relativePath), "package org.dummy;\npublic class Dummy2 {}".getBytes());
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
verifyNoInteractions(blameResult);
}
@Test
public void shouldNotFailOnUncommitedDir() throws Exception {
File repoDir = unzip("repo-svn.zip");
String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
File baseDir = new File(checkout(scmUrl), "dummy-svn");
when(fs.baseDir()).thenReturn(baseDir);
String relativePath = "src/main/java/org/dummy2/dummy/Dummy.java";
DefaultInputFile inputFile = new TestInputFileBuilder("foo", relativePath)
.setLines(28)
.setModuleBaseDir(baseDir.toPath())
.build();
Path filepath = new File(baseDir, relativePath).toPath();
Files.createDirectories(filepath.getParent());
Files.write(filepath, "package org.dummy;\npublic class Dummy {}".getBytes());
BlameOutput blameResult = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(singletonList(inputFile));
newSvnBlameCommand().blame(input, blameResult);
verifyNoInteractions(blameResult);
}
@Test
public void blame_givenNoCredentials_logWarning() throws Exception {
BlameOutput output = mock(BlameOutput.class);
InputFile inputFile = mock(InputFile.class);
SvnBlameCommand svnBlameCommand = newSvnBlameCommand();
SVNClientManager clientManager = mock(SVNClientManager.class);
SVNLogClient logClient = mock(SVNLogClient.class);
SVNStatusClient statusClient = mock(SVNStatusClient.class);
SVNStatus status = mock(SVNStatus.class);
when(clientManager.getLogClient()).thenReturn(logClient);
when(clientManager.getStatusClient()).thenReturn(statusClient);
when(status.getContentsStatus()).thenReturn(SVNStatusType.STATUS_NORMAL);
when(inputFile.file()).thenReturn(mock(File.class));
when(statusClient.doStatus(any(File.class), anyBoolean())).thenReturn(status);
doThrow(SVNAuthenticationException.class).when(logClient).doAnnotate(any(File.class), any(SVNRevision.class),
any(SVNRevision.class), any(SVNRevision.class), anyBoolean(), anyBoolean(), any(AnnotationHandler.class),
eq(null));
assertThrows(IllegalStateException.class, () -> {
svnBlameCommand.blame(clientManager, inputFile, output);
assertThat(logTester.logs(Level.WARN)).contains("Authentication to SVN server is required but no " +
"authentication data was passed to the scanner");
});
}
@Test
public void blame_givenCredentialsSupplied_doNotlogWarning() throws Exception {
BlameOutput output = mock(BlameOutput.class);
InputFile inputFile = mock(InputFile.class);
SvnConfiguration properties = mock(SvnConfiguration.class);
SvnBlameCommand svnBlameCommand = new SvnBlameCommand(properties);
SVNClientManager clientManager = mock(SVNClientManager.class);
SVNLogClient logClient = mock(SVNLogClient.class);
SVNStatusClient statusClient = mock(SVNStatusClient.class);
SVNStatus status = mock(SVNStatus.class);
when(properties.isEmpty()).thenReturn(true);
when(clientManager.getLogClient()).thenReturn(logClient);
when(clientManager.getStatusClient()).thenReturn(statusClient);
when(status.getContentsStatus()).thenReturn(SVNStatusType.STATUS_NORMAL);
when(inputFile.file()).thenReturn(mock(File.class));
when(statusClient.doStatus(any(File.class), anyBoolean())).thenReturn(status);
doThrow(SVNAuthenticationException.class).when(logClient).doAnnotate(any(File.class), any(SVNRevision.class),
any(SVNRevision.class), any(SVNRevision.class), anyBoolean(), anyBoolean(), any(AnnotationHandler.class),
eq(null));
assertThrows(IllegalStateException.class, () -> svnBlameCommand.blame(clientManager, inputFile, output));
assertThat(logTester.logs(Level.WARN)).contains("Authentication to SVN server is required but no authentication data was passed to the scanner");
}
private static void javaUnzip(File zip, File toDir) {
try {
try (ZipFile zipFile = new ZipFile(zip)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File to = new File(toDir, entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(to.toPath());
} else {
File parent = to.getParentFile();
if (parent != null) {
Files.createDirectories(parent.toPath());
}
Files.copy(zipFile.getInputStream(entry), to.toPath());
}
}
}
} catch (Exception e) {
throw new IllegalStateException("Fail to unzip " + zip + " to " + toDir, e);
}
}
private static String unixPath(File file) {
return file.getAbsolutePath().replace('\\', '/');
}
private SvnBlameCommand newSvnBlameCommand() {
return new SvnBlameCommand(mock(SvnConfiguration.class));
}
}
| 15,346 | 38.452442 | 162 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scm/svn/SvnTester.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scm.svn;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNCopyClient;
import org.tmatesoft.svn.core.wc.SVNCopySource;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc2.SvnList;
import org.tmatesoft.svn.core.wc2.SvnOperationFactory;
import org.tmatesoft.svn.core.wc2.SvnRemoteMkDir;
import org.tmatesoft.svn.core.wc2.SvnTarget;
public class SvnTester {
private final SVNClientManager manager = SVNClientManager.newInstance(new SvnOperationFactory());
private final SVNURL localRepository;
public SvnTester(Path root) throws SVNException, IOException {
localRepository = SVNRepositoryFactory.createLocalRepository(root.toFile(), false, false);
mkdir("trunk");
mkdir("branches");
}
private void mkdir(String relpath) throws IOException, SVNException {
SvnRemoteMkDir remoteMkDir = manager.getOperationFactory().createRemoteMkDir();
remoteMkDir.addTarget(SvnTarget.fromURL(localRepository.appendPath(relpath, false)));
remoteMkDir.run();
}
public void createBranch(String branchName) throws IOException, SVNException {
SVNCopyClient copyClient = manager.getCopyClient();
SVNCopySource source = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, localRepository.appendPath("trunk", false));
copyClient.doCopy(new SVNCopySource[] {source}, localRepository.appendPath("branches/" + branchName, false), false, false, true, "Create branch", null);
}
public void checkout(Path worktree, String path) throws SVNException {
SVNUpdateClient updateClient = manager.getUpdateClient();
updateClient.doCheckout(localRepository.appendPath(path, false),
worktree.toFile(), null, null, SVNDepth.INFINITY, false);
}
public void add(Path worktree, String filename) throws SVNException {
manager.getWCClient().doAdd(worktree.resolve(filename).toFile(), true, false, false, SVNDepth.INFINITY, false, false, true);
}
public void copy(Path worktree, String src, String dst) throws SVNException {
SVNCopyClient copyClient = manager.getCopyClient();
SVNCopySource source = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, worktree.resolve(src).toFile());
copyClient.doCopy(new SVNCopySource[]{source}, worktree.resolve(dst).toFile(), false, false, true);
}
public void commit(Path worktree) throws SVNException {
manager.getCommitClient().doCommit(new File[] {worktree.toFile()}, false, "commit " + worktree, null, null, false, false, SVNDepth.INFINITY);
}
public void update(Path worktree) throws SVNException {
manager.getUpdateClient().doUpdate(new File[] {worktree.toFile()}, SVNRevision.HEAD, SVNDepth.INFINITY, false, false);
}
public Collection<String> list(String... paths) throws SVNException {
Set<String> results = new HashSet<>();
SvnList list = manager.getOperationFactory().createList();
if (paths.length == 0) {
list.addTarget(SvnTarget.fromURL(localRepository));
} else {
for (String path : paths) {
list.addTarget(SvnTarget.fromURL(localRepository.appendPath(path, false)));
}
}
list.setDepth(SVNDepth.INFINITY);
list.setReceiver((svnTarget, svnDirEntry) -> {
String path = svnDirEntry.getRelativePath();
if (!path.isEmpty()) {
results.add(path);
}
});
list.run();
return results;
}
public void createFile(Path worktree, String filename, String content) throws IOException {
Files.write(worktree.resolve(filename), content.getBytes());
}
public void createFile(Path worktree, String filename) throws IOException {
createFile(worktree, filename, filename + "\n");
}
public void appendToFile(Path worktree, String filename) throws IOException {
Files.write(worktree.resolve(filename), (filename + "\n").getBytes(), StandardOpenOption.APPEND);
}
public void deleteFile(Path worktree, String filename) throws SVNException {
manager.getWCClient().doDelete(worktree.resolve(filename).toFile(), false, false);
}
}
| 5,338 | 40.069231 | 156 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/it/java/org/sonar/scm/svn/SvnTesterIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scm.svn;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.tmatesoft.svn.core.SVNException;
import static org.assertj.core.api.Assertions.assertThat;
public class SvnTesterIT {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SvnTester tester;
@Before
public void before() throws IOException, SVNException {
tester = new SvnTester(temp.newFolder().toPath());
}
@Test
public void test_init() throws SVNException {
assertThat(tester.list()).containsExactlyInAnyOrder("trunk", "branches");
}
@Test
public void test_add_and_commit() throws IOException, SVNException {
assertThat(tester.list("trunk")).isEmpty();
Path worktree = temp.newFolder().toPath();
tester.checkout(worktree, "trunk");
tester.createFile(worktree, "file1");
tester.add(worktree, "file1");
tester.commit(worktree);
assertThat(tester.list("trunk")).containsOnly("file1");
}
@Test
public void test_createBranch() throws IOException, SVNException {
tester.createBranch("b1");
assertThat(tester.list()).containsExactlyInAnyOrder("trunk", "branches", "branches/b1");
assertThat(tester.list("branches")).containsOnly("b1");
}
}
| 2,183 | 30.652174 | 92 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/Batch.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.bootstrap.SpringGlobalContainer;
/**
* Entry point for SonarQube Scanner API 2.1+.
*
* @since 2.14
*/
public final class Batch {
private LoggingConfiguration loggingConfig;
private List<Object> components;
private Map<String, String> globalProperties = new HashMap<>();
private Batch(Builder builder) {
components = new ArrayList<>();
components.addAll(builder.components);
if (builder.environment != null) {
components.add(builder.environment);
}
if (builder.globalProperties != null) {
globalProperties.putAll(builder.globalProperties);
}
if (builder.isEnableLoggingConfiguration()) {
loggingConfig = new LoggingConfiguration(builder.environment).setProperties(globalProperties);
if (builder.logOutput != null) {
loggingConfig.setLogOutput(builder.logOutput);
}
}
}
public LoggingConfiguration getLoggingConfiguration() {
return loggingConfig;
}
public synchronized Batch execute() {
return doExecute(this.globalProperties, this.components);
}
public synchronized Batch doExecute(Map<String, String> scannerProperties, List<Object> components) {
configureLogging();
try {
SpringGlobalContainer.create(scannerProperties, components).execute();
} catch (RuntimeException e) {
throw handleException(e);
}
return this;
}
private RuntimeException handleException(RuntimeException t) {
if (loggingConfig != null && loggingConfig.isVerbose()) {
return t;
}
Throwable y = t;
do {
if (y instanceof MessageException) {
return (MessageException) y;
}
y = y.getCause();
} while (y != null);
return t;
}
private void configureLogging() {
if (loggingConfig != null) {
loggingConfig.setProperties(globalProperties);
LoggingConfigurator.apply(loggingConfig);
}
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private Map<String, String> globalProperties;
private EnvironmentInformation environment;
private List<Object> components = new ArrayList<>();
private boolean enableLoggingConfiguration = true;
private LogOutput logOutput;
private Builder() {
}
public Builder setEnvironment(EnvironmentInformation env) {
this.environment = env;
return this;
}
public Builder setComponents(List<Object> l) {
this.components = l;
return this;
}
public Builder setLogOutput(@Nullable LogOutput logOutput) {
this.logOutput = logOutput;
return this;
}
public Builder setGlobalProperties(Map<String, String> globalProperties) {
this.globalProperties = globalProperties;
return this;
}
public Builder addComponents(Object... components) {
Collections.addAll(this.components, components);
return this;
}
public Builder addComponent(Object component) {
this.components.add(component);
return this;
}
public boolean isEnableLoggingConfiguration() {
return enableLoggingConfiguration;
}
/**
* Logback is configured by default. It can be disabled, but n this case the batch bootstrapper must provide its
* own implementation of SLF4J.
*/
public Builder setEnableLoggingConfiguration(boolean b) {
this.enableLoggingConfiguration = b;
return this;
}
public Batch build() {
if (components == null) {
throw new IllegalStateException("Batch components are not set");
}
return new Batch(this);
}
}
}
| 4,714 | 27.403614 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/EnvironmentInformation.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
/**
* Describes execution environment.
*
* @since 2.6
*/
public class EnvironmentInformation {
private String key;
private String version;
public EnvironmentInformation(String key, String version) {
this.key = key;
this.version = version;
}
/**
* @return unique key of environment, for example - "maven", "ant"
*/
public String getKey() {
return key;
}
/**
* @return version of environment, for example Maven can have "2.2.1" or "3.0.2",
* but there is no guarantees about format - it's just a string.
*/
public String getVersion() {
return version;
}
@Override
public String toString() {
return String.format("%s/%s", key, version);
}
}
| 1,599 | 27.070175 | 83 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LogCallbackAppender.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
public class LogCallbackAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
protected LogOutput target;
public LogCallbackAppender(LogOutput target) {
setTarget(target);
}
public void setTarget(LogOutput target) {
this.target = target;
}
@Override
protected void append(ILoggingEvent event) {
if (event.getThrowableProxy() == null) {
target.log(event.getFormattedMessage(), translate(event.getLevel()));
} else {
ExtendedThrowableProxyConverter throwableConverter = new ExtendedThrowableProxyConverter();
throwableConverter.start();
target.log(event.getFormattedMessage() + "\n" + throwableConverter.convert(event), translate(event.getLevel()));
throwableConverter.stop();
}
}
private static LogOutput.Level translate(Level level) {
switch (level.toInt()) {
case Level.ERROR_INT:
return LogOutput.Level.ERROR;
case Level.WARN_INT:
return LogOutput.Level.WARN;
case Level.INFO_INT:
return LogOutput.Level.INFO;
case Level.TRACE_INT:
return LogOutput.Level.TRACE;
case Level.DEBUG_INT:
default:
return LogOutput.Level.DEBUG;
}
}
}
| 2,291 | 33.727273 | 118 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LogOutput.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
/**
* Allow to redirect batch logs to a custom output. By defaults logs are written to System.out
* @since 5.2
*/
@FunctionalInterface
public interface LogOutput {
void log(String formattedMessage, Level level);
enum Level {
ERROR, WARN, INFO, DEBUG, TRACE
}
}
| 1,158 | 32.114286 | 94 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
/**
* @since 2.14
*/
public final class LoggingConfiguration {
public static final String PROPERTY_ROOT_LOGGER_LEVEL = "ROOT_LOGGER_LEVEL";
public static final String PROPERTY_FORMAT = "FORMAT";
public static final String LEVEL_ROOT_VERBOSE = "DEBUG";
public static final String LEVEL_ROOT_DEFAULT = "INFO";
static final String FORMAT_DEFAULT = "%d{HH:mm:ss.SSS} %-5level - %msg%n";
static final String FORMAT_MAVEN = "[%level] [%d{HH:mm:ss.SSS}] %msg%n";
private Map<String, String> substitutionVariables = new HashMap<>();
private LogOutput logOutput = null;
private boolean verbose;
public LoggingConfiguration() {
this(null);
}
public LoggingConfiguration(@Nullable EnvironmentInformation environment) {
setVerbose(false);
if (environment != null && "maven".equalsIgnoreCase(environment.getKey())) {
setFormat(FORMAT_MAVEN);
} else {
setFormat(FORMAT_DEFAULT);
}
}
public LoggingConfiguration setProperties(Map<String, String> properties) {
setVerbose(properties);
return this;
}
public LoggingConfiguration setLogOutput(@Nullable LogOutput listener) {
this.logOutput = listener;
return this;
}
public LoggingConfiguration setVerbose(boolean verbose) {
return setRootLevel(verbose ? LEVEL_ROOT_VERBOSE : LEVEL_ROOT_DEFAULT);
}
public boolean isVerbose() {
return verbose;
}
public LoggingConfiguration setVerbose(Map<String, String> props) {
String logLevel = props.get("sonar.log.level");
String deprecatedProfilingLevel = props.get("sonar.log.profilingLevel");
verbose = "true".equals(props.get("sonar.verbose")) ||
"DEBUG".equals(logLevel) || "TRACE".equals(logLevel) ||
"BASIC".equals(deprecatedProfilingLevel) || "FULL".equals(deprecatedProfilingLevel);
return setVerbose(verbose);
}
public LoggingConfiguration setRootLevel(String level) {
return addSubstitutionVariable(PROPERTY_ROOT_LOGGER_LEVEL, level);
}
LoggingConfiguration setFormat(String format) {
return addSubstitutionVariable(PROPERTY_FORMAT, StringUtils.defaultIfBlank(format, FORMAT_DEFAULT));
}
private LoggingConfiguration addSubstitutionVariable(String key, String value) {
substitutionVariables.put(key, value);
return this;
}
String getSubstitutionVariable(String key) {
return substitutionVariables.get(key);
}
Map<String, String> getSubstitutionVariables() {
return substitutionVariables;
}
LogOutput getLogOutput() {
return logOutput;
}
}
| 3,532 | 30.828829 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfigurator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.bootstrapper;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import java.io.File;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.sonar.core.config.Logback;
public class LoggingConfigurator {
private static final String CUSTOM_APPENDER_NAME = "custom_stream";
private LoggingConfigurator() {
}
public static void apply(LoggingConfiguration conf, File logbackFile) {
Logback.configure(logbackFile, conf.getSubstitutionVariables());
if (conf.getLogOutput() != null) {
setCustomRootAppender(conf);
}
}
public static void apply(LoggingConfiguration conf) {
apply(conf, "/org/sonar/batch/bootstrapper/logback.xml");
}
public static void apply(LoggingConfiguration conf, String classloaderPath) {
Logback.configure(classloaderPath, conf.getSubstitutionVariables());
// if not set, keep default behavior (configured to stdout through the file in classpath)
if (conf.getLogOutput() != null) {
setCustomRootAppender(conf);
}
}
private static void setCustomRootAppender(LoggingConfiguration conf) {
Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
String level = StringUtils.defaultIfBlank(conf.getSubstitutionVariables().get(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL), LoggingConfiguration.LEVEL_ROOT_DEFAULT);
if (logger.getAppender(CUSTOM_APPENDER_NAME) == null) {
logger.detachAndStopAllAppenders();
logger.addAppender(createAppender(conf.getLogOutput()));
}
logger.setLevel(Level.toLevel(level));
}
private static Appender<ILoggingEvent> createAppender(LogOutput target) {
LogCallbackAppender appender = new LogCallbackAppender(target);
appender.setName(CUSTOM_APPENDER_NAME);
appender.start();
return appender;
}
}
| 2,793 | 35.285714 | 173 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* This package is a part of bootstrap process, so we should take care about backward compatibility.
*/
@ParametersAreNonnullByDefault
package org.sonar.batch.bootstrapper;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,078 | 37.535714 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.utils.KeyValueFormat;
import static java.util.stream.Collectors.toMap;
import static org.sonar.api.utils.Preconditions.checkArgument;
public class DefaultFileLinesContext implements FileLinesContext {
private final InputFile inputFile;
private final MetricFinder metricFinder;
/**
* metric key -> line -> value
*/
private final Map<String, Map<Integer, Object>> map = new HashMap<>();
private final SensorStorage sensorStorage;
public DefaultFileLinesContext(SensorStorage sensorStorage, InputFile inputFile, MetricFinder metricFinder) {
this.sensorStorage = sensorStorage;
this.inputFile = inputFile;
this.metricFinder = metricFinder;
}
@Override
public void setIntValue(String metricKey, int line, int value) {
checkNotNull(metricKey);
checkLineRange(line);
setValue(metricKey, line, value);
}
private void checkLineRange(int line) {
checkArgument(line > 0, "Line number should be positive for file %s.", inputFile);
checkArgument(line <= inputFile.lines(), "Line %s is out of range for file %s. File has %s lines.", line, inputFile, inputFile.lines());
}
@Override
public void setStringValue(String metricKey, int line, String value) {
checkNotNull(metricKey);
checkLineRange(line);
checkNotNull(value);
setValue(metricKey, line, value);
}
private static void checkNotNull(Object object) {
if (object == null) {
throw new NullPointerException();
}
}
private void setValue(String metricKey, int line, Object value) {
map.computeIfAbsent(metricKey, k -> new HashMap<>())
.put(line, value);
}
@Override
public void save() {
for (Map.Entry<String, Map<Integer, Object>> entry : map.entrySet()) {
String metricKey = entry.getKey();
Map<Integer, Object> lines = entry.getValue();
if (shouldSave(lines)) {
String data = KeyValueFormat.format(optimizeStorage(metricKey, lines));
new DefaultMeasure<String>(sensorStorage)
.on(inputFile)
.forMetric(metricFinder.findByKey(metricKey))
.withValue(data)
.save();
entry.setValue(Collections.unmodifiableMap(lines));
}
}
}
private static Map<Integer, Object> optimizeStorage(String metricKey, Map<Integer, Object> lines) {
// SONAR-7464 Don't store 0 because this is default value anyway
if (CoreMetrics.NCLOC_DATA_KEY.equals(metricKey) || CoreMetrics.EXECUTABLE_LINES_DATA_KEY.equals(metricKey)) {
return lines.entrySet().stream()
.filter(entry -> !entry.getValue().equals(0))
.collect(toMap(Entry::getKey, Entry::getValue));
}
return lines;
}
/**
* Checks that measure was not saved.
*
* @see #save()
*/
private static boolean shouldSave(Map<Integer, Object> lines) {
return lines instanceof HashMap;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "{" + map.toString() + "}";
}
}
| 4,265 | 32.328125 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContextFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.measures.FileLinesContext;
import org.sonar.api.measures.FileLinesContextFactory;
@Immutable
public class DefaultFileLinesContextFactory implements FileLinesContextFactory {
private final SensorStorage sensorStorage;
private final MetricFinder metricFinder;
public DefaultFileLinesContextFactory(SensorStorage sensorStorage, MetricFinder metricFinder) {
this.sensorStorage = sensorStorage;
this.metricFinder = metricFinder;
}
@Override
public FileLinesContext createFor(InputFile inputFile) {
return new DefaultFileLinesContext(sensorStorage, inputFile, metricFinder);
}
}
| 1,690 | 35.76087 | 97 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ProjectInfo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner;
import java.time.Clock;
import java.util.Date;
import java.util.Optional;
import java.util.function.Predicate;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.Startable;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.MessageException;
import static java.lang.String.format;
import static org.sonar.api.CoreProperties.BUILD_STRING_PROPERTY;
import static org.sonar.api.CoreProperties.PROJECT_VERSION_PROPERTY;
/**
* @since 6.3
*
* Immutable after {@link #start()}
*/
public class ProjectInfo implements Startable {
private final Clock clock;
private final Configuration settings;
private Date analysisDate;
private String projectVersion;
private String buildString;
public ProjectInfo(Configuration settings, Clock clock) {
this.settings = settings;
this.clock = clock;
}
public Date getAnalysisDate() {
return analysisDate;
}
public Optional<String> getProjectVersion() {
return Optional.ofNullable(projectVersion);
}
public Optional<String> getBuildString() {
return Optional.ofNullable(buildString);
}
private Date loadAnalysisDate() {
Optional<String> value = settings.get(CoreProperties.PROJECT_DATE_PROPERTY);
if (value.isEmpty()) {
return Date.from(clock.instant());
}
try {
// sonar.projectDate may have been specified as a time
return DateUtils.parseDateTime(value.get());
} catch (RuntimeException e) {
// this is probably just a date
}
try {
// sonar.projectDate may have been specified as a date
return DateUtils.parseDate(value.get());
} catch (RuntimeException e) {
throw new IllegalArgumentException("Illegal value for '" + CoreProperties.PROJECT_DATE_PROPERTY + "'", e);
}
}
@Override
public void start() {
this.analysisDate = loadAnalysisDate();
this.projectVersion = settings.get(PROJECT_VERSION_PROPERTY)
.map(StringUtils::trimToNull)
.filter(validateLengthLimit("project version"))
.orElse(null);
this.buildString = settings.get(BUILD_STRING_PROPERTY)
.map(StringUtils::trimToNull)
.filter(validateLengthLimit("buildString"))
.orElse(null);
}
private static Predicate<String> validateLengthLimit(String label) {
return value -> {
if (value.length() > 100) {
throw MessageException.of(format("\"%s\" is not a valid %s. " +
"The maximum length is 100 characters.", value, label));
}
return true;
};
}
@Override
public void stop() {
// nothing to do
}
}
| 3,511 | 29.807018 | 112 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner;
import javax.annotation.ParametersAreNonnullByDefault;
| 957 | 38.916667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/AnalysisTempFolderProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.analysis;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.impl.utils.DefaultTempFolder;
import org.sonar.api.utils.TempFolder;
import org.springframework.context.annotation.Bean;
public class AnalysisTempFolderProvider {
static final String TMP_NAME = ".sonartmp";
@Bean("AnalysisTempFolder")
public TempFolder provide(DefaultInputProject project) {
Path workingDir = project.getWorkDir();
Path tempDir = workingDir.normalize().resolve(TMP_NAME);
try {
Files.deleteIfExists(tempDir);
Files.createDirectories(tempDir);
} catch (IOException e) {
throw new IllegalStateException("Unable to create root temp directory " + tempDir, e);
}
return new DefaultTempFolder(tempDir.toFile(), true);
}
}
| 1,730 | 35.829787 | 92 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/analysis/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.analysis;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 39.291667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/AbstractExtensionDictionary.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang.ClassUtils;
import org.sonar.api.batch.DependedUpon;
import org.sonar.api.batch.DependsUpon;
import org.sonar.api.batch.Phase;
import org.sonar.api.utils.AnnotationUtils;
import org.sonar.api.utils.dag.DirectAcyclicGraph;
import org.sonar.core.platform.ExtensionContainer;
public abstract class AbstractExtensionDictionary {
private final ExtensionContainer componentContainer;
protected AbstractExtensionDictionary(ExtensionContainer componentContainer) {
this.componentContainer = componentContainer;
}
public <T> Collection<T> select(Class<T> type, boolean sort, @Nullable ExtensionMatcher matcher) {
List<T> result = getFilteredExtensions(type, matcher);
if (sort) {
return sort(result);
}
return result;
}
private static Phase.Name evaluatePhase(Object extension) {
Phase phaseAnnotation = AnnotationUtils.getAnnotation(extension, Phase.class);
if (phaseAnnotation != null) {
return phaseAnnotation.name();
}
return Phase.Name.DEFAULT;
}
protected <T> List<T> getFilteredExtensions(Class<T> type, @Nullable ExtensionMatcher matcher) {
List<T> result = new ArrayList<>();
for (T extension : getExtensions(type)) {
if (shouldKeep(type, extension, matcher)) {
result.add(extension);
}
}
return result;
}
private <T> List<T> getExtensions(Class<T> type) {
List<T> extensions = new ArrayList<>();
completeScannerExtensions(componentContainer, extensions, type);
return extensions;
}
private static <T> void completeScannerExtensions(ExtensionContainer container, List<T> extensions, Class<T> type) {
extensions.addAll(container.getComponentsByType(type));
ExtensionContainer parentContainer = container.getParent();
if (parentContainer != null) {
completeScannerExtensions(parentContainer, extensions, type);
}
}
protected <T> Collection<T> sort(Collection<T> extensions) {
DirectAcyclicGraph dag = new DirectAcyclicGraph();
for (T extension : extensions) {
dag.add(extension);
for (Object dependency : getDependencies(extension)) {
dag.add(extension, dependency);
}
for (Object generates : getDependents(extension)) {
dag.add(generates, extension);
}
completePhaseDependencies(dag, extension);
}
List<?> sortedList = dag.sort();
return (Collection<T>) sortedList.stream()
.filter(extensions::contains)
.collect(Collectors.toList());
}
/**
* Extension dependencies
*/
private <T> List<Object> getDependencies(T extension) {
return new ArrayList<>(evaluateAnnotatedClasses(extension, DependsUpon.class));
}
/**
* Objects that depend upon this extension.
*/
private <T> List<Object> getDependents(T extension) {
return new ArrayList<>(evaluateAnnotatedClasses(extension, DependedUpon.class));
}
private static void completePhaseDependencies(DirectAcyclicGraph dag, Object extension) {
Phase.Name phase = evaluatePhase(extension);
dag.add(extension, phase);
for (Phase.Name name : Phase.Name.values()) {
if (phase.compareTo(name) < 0) {
dag.add(name, extension);
} else if (phase.compareTo(name) > 0) {
dag.add(extension, name);
}
}
}
public List<Object> evaluateAnnotatedClasses(Object extension, Class<? extends Annotation> annotation) {
List<Object> results = new ArrayList<>();
Class<?> aClass = extension.getClass();
while (aClass != null) {
evaluateClass(aClass, annotation, results);
for (Method method : aClass.getDeclaredMethods()) {
if (method.getAnnotation(annotation) != null) {
checkAnnotatedMethod(method);
evaluateMethod(extension, method, results);
}
}
aClass = aClass.getSuperclass();
}
return results;
}
private static void evaluateClass(Class<?> extensionClass, Class<? extends Annotation> annotationClass, List<Object> results) {
Annotation annotation = extensionClass.getAnnotation(annotationClass);
if (annotation != null) {
if (annotation.annotationType().isAssignableFrom(DependsUpon.class)) {
results.addAll(Arrays.asList(((DependsUpon) annotation).value()));
} else if (annotation.annotationType().isAssignableFrom(DependedUpon.class)) {
results.addAll(Arrays.asList(((DependedUpon) annotation).value()));
}
}
Class<?>[] interfaces = extensionClass.getInterfaces();
for (Class<?> anInterface : interfaces) {
evaluateClass(anInterface, annotationClass, results);
}
}
private void evaluateMethod(Object extension, Method method, List<Object> results) {
try {
Object result = method.invoke(extension);
if (result != null) {
if (result instanceof Class<?>) {
results.addAll(componentContainer.getComponentsByType((Class<?>) result));
} else if (result instanceof Collection<?>) {
results.addAll((Collection<?>) result);
} else if (result.getClass().isArray()) {
for (int i = 0; i < Array.getLength(result); i++) {
results.add(Array.get(result, i));
}
} else {
results.add(result);
}
}
} catch (Exception e) {
throw new IllegalStateException("Can not invoke method " + method, e);
}
}
private static void checkAnnotatedMethod(Method method) {
if (!Modifier.isPublic(method.getModifiers())) {
throw new IllegalStateException("Annotated method must be public:" + method);
}
if (method.getParameterTypes().length > 0) {
throw new IllegalStateException("Annotated method must not have parameters:" + method);
}
}
private static boolean shouldKeep(Class<?> type, Object extension, @Nullable ExtensionMatcher matcher) {
return ClassUtils.isAssignable(extension.getClass(), type) && (matcher == null || matcher.accept(extension));
}
}
| 7,152 | 33.555556 | 129 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.sarif.SarifSerializerImpl;
import org.sonar.scanner.cpd.JavaCpdBlockIndexerSensor;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import org.sonar.scanner.externalissue.ExternalIssuesImportSensor;
import org.sonar.scanner.externalissue.sarif.DefaultSarif210Importer;
import org.sonar.scanner.externalissue.sarif.LocationMapper;
import org.sonar.scanner.externalissue.sarif.RegionMapper;
import org.sonar.scanner.externalissue.sarif.ResultMapper;
import org.sonar.scanner.externalissue.sarif.RunMapper;
import org.sonar.scanner.externalissue.sarif.SarifIssuesImportSensor;
import org.sonar.scanner.genericcoverage.GenericCoverageSensor;
import org.sonar.scanner.genericcoverage.GenericTestExecutionSensor;
import org.sonar.scanner.source.ZeroCoverageSensor;
public class BatchComponents {
private BatchComponents() {
// only static stuff
}
public static Collection<Object> all() {
List<Object> components = new ArrayList<>();
components.add(DefaultResourceTypes.get());
components.addAll(CorePropertyDefinitions.all());
components.add(ZeroCoverageSensor.class);
components.add(JavaCpdBlockIndexerSensor.class);
// Generic coverage
components.add(GenericCoverageSensor.class);
components.addAll(GenericCoverageSensor.properties());
components.add(GenericTestExecutionSensor.class);
components.addAll(GenericTestExecutionSensor.properties());
components.add(TestPlanBuilder.class);
// External issues
components.add(ExternalIssuesImportSensor.class);
components.add(ExternalIssuesImportSensor.properties());
components.add(SarifSerializerImpl.class);
// Sarif issues
components.add(SarifIssuesImportSensor.class);
components.add(SarifIssuesImportSensor.properties());
components.add(DefaultSarif210Importer.class);
components.add(RunMapper.class);
components.add(ResultMapper.class);
components.add(LocationMapper.class);
components.add(RegionMapper.class);
return components;
}
}
| 3,094 | 39.194805 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/DefaultScannerWsClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsClient;
import org.sonarqube.ws.client.WsConnector;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.sonar.api.utils.DateUtils.DATETIME_FORMAT;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultScannerWsClient implements ScannerWsClient {
private static final int MAX_ERROR_MSG_LEN = 128;
private static final String SQ_TOKEN_EXPIRATION_HEADER = "SonarQube-Authentication-Token-Expiration";
private static final DateTimeFormatter USER_FRIENDLY_DATETIME_FORMAT = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
private static final Logger LOG = Loggers.get(DefaultScannerWsClient.class);
private final Set<String> warningMessages = new HashSet<>();
private final WsClient target;
private final boolean hasCredentials;
private final GlobalAnalysisMode globalMode;
private final AnalysisWarnings analysisWarnings;
public DefaultScannerWsClient(WsClient target, boolean hasCredentials, GlobalAnalysisMode globalMode, AnalysisWarnings analysisWarnings) {
this.target = target;
this.hasCredentials = hasCredentials;
this.globalMode = globalMode;
this.analysisWarnings = analysisWarnings;
}
/**
* If an exception is not thrown, the response needs to be closed by either calling close() directly, or closing the
* body content's stream/reader.
*
* @throws IllegalStateException if the request could not be executed due to a connectivity problem or timeout. Because networks can
* fail during an exchange, it is possible that the remote server accepted the request before the failure
* @throws MessageException if there was a problem with authentication or if a error message was parsed from the response.
* @throws HttpException if the response code is not in range [200..300). Consider using {@link #createErrorMessage(HttpException)} to create more relevant messages for the users.
*/
public WsResponse call(WsRequest request) {
checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
Profiler profiler = Profiler.createIfDebug(LOG).start();
WsResponse response = target.wsConnector().call(request);
profiler.stopDebug(format("%s %d %s", request.getMethod(), response.code(), response.requestUrl()));
failIfUnauthorized(response);
checkAuthenticationWarnings(response);
return response;
}
public String baseUrl() {
return target.wsConnector().baseUrl();
}
WsConnector wsConnector() {
return target.wsConnector();
}
private void failIfUnauthorized(WsResponse response) {
int code = response.code();
if (code == HTTP_UNAUTHORIZED) {
logResponseDetailsIfDebug(response);
response.close();
if (hasCredentials) {
// credentials are not valid
throw MessageException.of(format("Not authorized. Please check the user token in the property '%s' or the credentials in the properties '%s' and '%s'.",
ScannerWsClientProvider.TOKEN_PROPERTY, CoreProperties.LOGIN, CoreProperties.PASSWORD));
}
// not authenticated - see https://jira.sonarsource.com/browse/SONAR-4048
throw MessageException.of(format("Not authorized. Analyzing this project requires authentication. " +
"Please check the user token in the property '%s' or the credentials in the properties '%s' and '%s'.",
ScannerWsClientProvider.TOKEN_PROPERTY, CoreProperties.LOGIN, CoreProperties.PASSWORD));
}
if (code == HTTP_FORBIDDEN) {
logResponseDetailsIfDebug(response);
throw MessageException.of("You're not authorized to analyze this project or the project doesn't exist on SonarQube" +
" and you're not authorized to create it. Please contact an administrator.");
}
if (code == HTTP_BAD_REQUEST) {
String jsonMsg = tryParseAsJsonError(response.content());
if (jsonMsg != null) {
throw MessageException.of(jsonMsg);
}
}
// if failed, throws an HttpException
response.failIfNotSuccessful();
}
private static void logResponseDetailsIfDebug(WsResponse response) {
if (!LOG.isDebugEnabled()) {
return;
}
String content = response.hasContent() ? response.content() : "<no content>";
Map<String, List<String>> headers = response.headers();
LOG.debug("Error response content: {}, headers: {}", content, headers);
}
private void checkAuthenticationWarnings(WsResponse response) {
if (response.code() == HTTP_OK) {
response.header(SQ_TOKEN_EXPIRATION_HEADER).ifPresent(expirationDate -> {
var datetimeInUTC = ZonedDateTime.from(DateTimeFormatter.ofPattern(DATETIME_FORMAT)
.parse(expirationDate)).withZoneSameInstant(ZoneOffset.UTC);
if (isTokenExpiringInOneWeek(datetimeInUTC)) {
addAnalysisWarning(datetimeInUTC);
}
});
}
}
private static boolean isTokenExpiringInOneWeek(ZonedDateTime expirationDate) {
ZonedDateTime localDateTime = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime headerDateTime = expirationDate.minusDays(7);
return localDateTime.isAfter(headerDateTime);
}
private void addAnalysisWarning(ZonedDateTime tokenExpirationDate) {
String warningMessage = "The token used for this analysis will expire on: " + tokenExpirationDate.format(USER_FRIENDLY_DATETIME_FORMAT);
if (!warningMessages.contains(warningMessage)) {
warningMessages.add(warningMessage);
LOG.warn(warningMessage);
LOG.warn("Analysis executed with this token will fail after the expiration date.");
}
analysisWarnings.addUnique(warningMessage + "\nAfter this date, the token can no longer be used to execute the analysis. "
+ "Please consider generating a new token and updating it in the locations where it is in use.");
}
/**
* Tries to form a short and relevant error message from the exception, to be displayed in the console.
*/
public static String createErrorMessage(HttpException exception) {
String json = tryParseAsJsonError(exception.content());
if (json != null) {
return json;
}
String msg = "HTTP code " + exception.code();
if (isHtml(exception.content())) {
return msg;
}
return msg + ": " + StringUtils.left(exception.content(), MAX_ERROR_MSG_LEN);
}
@CheckForNull
private static String tryParseAsJsonError(String responseContent) {
try {
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(responseContent).getAsJsonObject();
JsonArray errors = obj.getAsJsonArray("errors");
List<String> errorMessages = new ArrayList<>();
for (JsonElement e : errors) {
errorMessages.add(e.getAsJsonObject().get("msg").getAsString());
}
return String.join(", ", errorMessages);
} catch (Exception e) {
return null;
}
}
private static boolean isHtml(String responseContent) {
return StringUtils.stripToEmpty(responseContent).startsWith("<!DOCTYPE html>");
}
}
| 8,965 | 41.899522 | 189 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionInstaller.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import javax.annotation.Nullable;
import org.sonar.api.Plugin;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.api.internal.PluginContextImpl;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
public class ExtensionInstaller {
private final SonarRuntime sonarRuntime;
private final PluginRepository pluginRepository;
private final Configuration bootConfiguration;
public ExtensionInstaller(SonarRuntime sonarRuntime, PluginRepository pluginRepository, Configuration bootConfiguration) {
this.sonarRuntime = sonarRuntime;
this.pluginRepository = pluginRepository;
this.bootConfiguration = bootConfiguration;
}
public ExtensionInstaller install(ExtensionContainer container, ExtensionMatcher matcher) {
// core components
for (Object o : BatchComponents.all()) {
doInstall(container, matcher, null, o);
}
// plugin extensions
for (PluginInfo pluginInfo : pluginRepository.getPluginInfos()) {
Plugin plugin = pluginRepository.getPluginInstance(pluginInfo.getKey());
Plugin.Context context = new PluginContextImpl.Builder()
.setSonarRuntime(sonarRuntime)
.setBootConfiguration(bootConfiguration)
.build();
plugin.define(context);
for (Object extension : context.getExtensions()) {
doInstall(container, matcher, pluginInfo, extension);
}
}
return this;
}
private static void doInstall(ExtensionContainer container, ExtensionMatcher matcher, @Nullable PluginInfo pluginInfo, Object extension) {
if (matcher.accept(extension)) {
container.addExtension(pluginInfo, extension);
} else {
container.declareExtension(pluginInfo, extension);
}
}
}
| 2,715 | 35.213333 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionMatcher.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
public interface ExtensionMatcher {
boolean accept(Object extension);
}
| 955 | 37.24 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.api.utils.AnnotationUtils;
public class ExtensionUtils {
private ExtensionUtils() {
// only static methods
}
public static boolean isInstantiationStrategy(Object extension, String strategy) {
InstantiationStrategy annotation = AnnotationUtils.getAnnotation(extension, InstantiationStrategy.class);
if (annotation != null) {
return strategy.equals(annotation.value());
}
return InstantiationStrategy.PER_PROJECT.equals(strategy);
}
public static boolean isDeprecatedScannerSide(Object extension) {
return AnnotationUtils.getAnnotation(extension, org.sonar.api.batch.ScannerSide.class) != null;
}
public static boolean isScannerSide(Object extension) {
return AnnotationUtils.getAnnotation(extension, ScannerSide.class) != null;
}
}
| 1,777 | 35.285714 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalAnalysisMode.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import javax.annotation.concurrent.Immutable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Immutable
public class GlobalAnalysisMode {
public static final String MEDIUM_TEST_ENABLED = "sonar.mediumTest.enabled";
private static final Logger LOG = LoggerFactory.getLogger(GlobalAnalysisMode.class);
protected boolean mediumTestMode;
public GlobalAnalysisMode(ScannerProperties props) {
mediumTestMode = "true".equals(props.property(MEDIUM_TEST_ENABLED));
if (mediumTestMode) {
LOG.info("Medium test mode");
}
}
public boolean isMediumTest() {
return mediumTestMode;
}
}
| 1,502 | 33.159091 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.scanner.config.DefaultConfiguration;
@Immutable
public class GlobalConfiguration extends DefaultConfiguration {
public GlobalConfiguration(PropertyDefinitions propertyDefinitions, Encryption encryption, Map<String, String> settings) {
super(propertyDefinitions, encryption, settings);
}
}
| 1,362 | 39.088235 | 124 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfigurationProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.sonar.api.config.PropertyDefinitions;
import org.springframework.context.annotation.Bean;
public class GlobalConfigurationProvider {
@Bean("GlobalConfiguration")
public GlobalConfiguration provide(GlobalServerSettings globalServerSettings, ScannerProperties scannerProps, PropertyDefinitions propertyDefinitions) {
Map<String, String> mergedSettings = new LinkedHashMap<>();
mergedSettings.putAll(globalServerSettings.properties());
mergedSettings.putAll(scannerProps.properties());
return new GlobalConfiguration(propertyDefinitions, scannerProps.getEncryption(), mergedSettings);
}
}
| 1,555 | 42.222222 | 154 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalServerSettings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
/**
* Global properties coming from the server.
*/
@Immutable
public class GlobalServerSettings {
private final Map<String, String> properties;
public GlobalServerSettings(Map<String, String> properties) {
this.properties = Map.copyOf(properties);
}
public Map<String, String> properties() {
return properties;
}
public String property(String key) {
return properties.get(key);
}
}
| 1,365 | 28.695652 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalServerSettingsProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.CoreProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.repository.settings.GlobalSettingsLoader;
import org.springframework.context.annotation.Bean;
public class GlobalServerSettingsProvider {
private static final Logger LOG = LoggerFactory.getLogger(GlobalServerSettingsProvider.class);
@Bean("GlobalServerSettings")
public GlobalServerSettings provide(GlobalSettingsLoader loader) {
Map<String, String> serverSideSettings = loader.loadGlobalSettings();
Optional.ofNullable(serverSideSettings.get(CoreProperties.SERVER_ID)).ifPresent(v -> LOG.info("Server id: {}", v));
return new GlobalServerSettings(serverSideSettings);
}
}
| 1,644 | 40.125 | 119 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalTempFolderProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.impl.utils.DefaultTempFolder;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.TempFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.sonar.core.util.FileUtils.deleteQuietly;
import org.springframework.context.annotation.Bean;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.TimeUnit;
public class GlobalTempFolderProvider {
private static final Logger LOG = LoggerFactory.getLogger(GlobalTempFolderProvider.class);
private static final long CLEAN_MAX_AGE = TimeUnit.DAYS.toMillis(21);
static final String TMP_NAME_PREFIX = ".sonartmp_";
private System2 system;
public GlobalTempFolderProvider() {
this(new System2());
}
GlobalTempFolderProvider(System2 system) {
this.system = system;
}
@Bean("GlobalTempFolder")
public TempFolder provide(ScannerProperties scannerProps) {
String workingPathName = StringUtils.defaultIfBlank(scannerProps.property(CoreProperties.GLOBAL_WORKING_DIRECTORY), CoreProperties.GLOBAL_WORKING_DIRECTORY_DEFAULT_VALUE);
Path workingPath = Paths.get(workingPathName);
if (!workingPath.isAbsolute()) {
Path home = findSonarHome(scannerProps);
workingPath = home.resolve(workingPath).normalize();
}
try {
cleanTempFolders(workingPath);
} catch (IOException e) {
LOG.error(String.format("failed to clean global working directory: %s", workingPath), e);
}
Path tempDir = createTempFolder(workingPath);
return new DefaultTempFolder(tempDir.toFile(), true);
}
private static Path createTempFolder(Path workingPath) {
try {
Path realPath = workingPath;
if (Files.isSymbolicLink(realPath)) {
realPath = realPath.toRealPath();
}
Files.createDirectories(realPath);
} catch (IOException e) {
throw new IllegalStateException("Failed to create working path: " + workingPath, e);
}
try {
return Files.createTempDirectory(workingPath, TMP_NAME_PREFIX);
} catch (IOException e) {
throw new IllegalStateException("Failed to create temporary folder in " + workingPath, e);
}
}
private Path findSonarHome(ScannerProperties props) {
String home = props.property("sonar.userHome");
if (home != null) {
return Paths.get(home).toAbsolutePath();
}
home = system.envVariable("SONAR_USER_HOME");
if (home != null) {
return Paths.get(home).toAbsolutePath();
}
home = system.property("user.home");
return Paths.get(home, ".sonar").toAbsolutePath();
}
private static void cleanTempFolders(Path path) throws IOException {
if (path.toFile().exists()) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, new CleanFilter())) {
for (Path p : stream) {
deleteQuietly(p.toFile());
}
}
}
}
private static class CleanFilter implements DirectoryStream.Filter<Path> {
@Override
public boolean accept(Path path) throws IOException {
if (!path.toFile().exists()) {
return false;
}
if (!path.getFileName().toString().startsWith(TMP_NAME_PREFIX)) {
return false;
}
long threshold = System.currentTimeMillis() - CLEAN_MAX_AGE;
// we could also check the timestamp in the name, instead
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(path, BasicFileAttributes.class);
} catch (IOException ioe) {
LOG.error(String.format("Couldn't read file attributes for %s : ", path), ioe);
return false;
}
long creationTime = attrs.creationTime().toMillis();
return creationTime < threshold;
}
}
}
| 4,821 | 31.581081 | 175 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/PluginFiles.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.bootstrap.ScannerPluginInstaller.InstalledPlugin;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsResponse;
import static java.lang.String.format;
public class PluginFiles {
private static final Logger LOGGER = LoggerFactory.getLogger(PluginFiles.class);
private static final String MD5_HEADER = "Sonar-MD5";
private final DefaultScannerWsClient wsClient;
private final File cacheDir;
private final File tempDir;
public PluginFiles(DefaultScannerWsClient wsClient, Configuration configuration) {
this.wsClient = wsClient;
File home = locateHomeDir(configuration);
this.cacheDir = mkdir(new File(home, "cache"), "user cache");
this.tempDir = mkdir(new File(home, "_tmp"), "temp dir");
LOGGER.info("User cache: {}", cacheDir.getAbsolutePath());
}
public File createTempDir() {
try {
return Files.createTempDirectory(tempDir.toPath(), "plugins").toFile();
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp directory in " + tempDir, e);
}
}
/**
* Get the JAR file of specified plugin. If not present in user local cache,
* then it's downloaded from server and added to cache.
*
* @return the file, or {@link Optional#empty()} if plugin not found (404 HTTP code)
* @throws IllegalStateException if the plugin can't be downloaded (not 404 nor 2xx HTTP codes)
* or can't be cached locally.
*/
public Optional<File> get(InstalledPlugin plugin) {
// Does not fail if another process tries to create the directory at the same time.
File jarInCache = jarInCache(plugin.key, plugin.hash);
if (jarInCache.exists() && jarInCache.isFile()) {
return Optional.of(jarInCache);
}
return download(plugin);
}
private Optional<File> download(InstalledPlugin plugin) {
GetRequest request = new GetRequest("api/plugins/download")
.setParam("plugin", plugin.key)
.setTimeOutInMs(5 * 60_000);
File downloadedFile = newTempFile();
LOGGER.debug("Download plugin '{}' to '{}'", plugin.key, downloadedFile);
try (WsResponse response = wsClient.call(request)) {
Optional<String> expectedMd5 = response.header(MD5_HEADER);
if (!expectedMd5.isPresent()) {
throw new IllegalStateException(format(
"Fail to download plugin [%s]. Request to %s did not return header %s", plugin.key, response.requestUrl(), MD5_HEADER));
}
downloadBinaryTo(plugin, downloadedFile, response);
// verify integrity
String effectiveTempMd5 = computeMd5(downloadedFile);
if (!expectedMd5.get().equals(effectiveTempMd5)) {
throw new IllegalStateException(format(
"Fail to download plugin [%s]. File %s was expected to have checksum %s but had %s", plugin.key, downloadedFile, expectedMd5.get(), effectiveTempMd5));
}
// un-compress if needed
String cacheMd5;
File tempJar;
tempJar = downloadedFile;
cacheMd5 = expectedMd5.get();
// put in cache
File jarInCache = jarInCache(plugin.key, cacheMd5);
mkdir(jarInCache.getParentFile());
moveFile(tempJar, jarInCache);
return Optional.of(jarInCache);
} catch (HttpException e) {
if (e.code() == HttpURLConnection.HTTP_NOT_FOUND) {
// Plugin was listed but not longer available. It has probably been
// uninstalled.
return Optional.empty();
}
// not 2xx nor 404
throw new IllegalStateException(format("Fail to download plugin [%s]. Request to %s returned code %d.", plugin.key, e.url(), e.code()));
}
}
private static void downloadBinaryTo(InstalledPlugin plugin, File downloadedFile, WsResponse response) {
try (InputStream stream = response.contentStream()) {
FileUtils.copyInputStreamToFile(stream, downloadedFile);
} catch (IOException e) {
throw new IllegalStateException(format("Fail to download plugin [%s] into %s", plugin.key, downloadedFile), e);
}
}
private File jarInCache(String pluginKey, String hash) {
File hashDir = new File(cacheDir, hash);
File file = new File(hashDir, format("sonar-%s-plugin.jar", pluginKey));
if (!file.getParentFile().toPath().equals(hashDir.toPath())) {
// vulnerability - attempt to create a file outside the cache directory
throw new IllegalStateException(format("Fail to download plugin [%s]. Key is not valid.", pluginKey));
}
return file;
}
private File newTempFile() {
try {
return File.createTempFile("fileCache", null, tempDir);
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp file in " + tempDir, e);
}
}
private static String computeMd5(File file) {
try (InputStream fis = new BufferedInputStream(FileUtils.openInputStream(file))) {
return DigestUtils.md5Hex(fis);
} catch (IOException e) {
throw new IllegalStateException("Fail to compute md5 of " + file, e);
}
}
private static void moveFile(File sourceFile, File targetFile) {
boolean rename = sourceFile.renameTo(targetFile);
// Check if the file was cached by another process during download
if (!rename && !targetFile.exists()) {
LOGGER.warn("Unable to rename {} to {}", sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
LOGGER.warn("A copy/delete will be tempted but with no guarantee of atomicity");
try {
Files.move(sourceFile.toPath(), targetFile.toPath());
} catch (IOException e) {
throw new IllegalStateException("Fail to move " + sourceFile.getAbsolutePath() + " to " + targetFile, e);
}
}
}
private static void mkdir(File dir) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException e) {
throw new IllegalStateException("Fail to create cache directory: " + dir, e);
}
}
private static File mkdir(File dir, String debugTitle) {
if (!dir.isDirectory() || !dir.exists()) {
LOGGER.debug("Create : {}", dir.getAbsolutePath());
try {
Files.createDirectories(dir.toPath());
} catch (IOException e) {
throw new IllegalStateException("Unable to create " + debugTitle + dir.getAbsolutePath(), e);
}
}
return dir;
}
private static File locateHomeDir(Configuration configuration) {
return Stream.of(
configuration.get("sonar.userHome").orElse(null),
System.getenv("SONAR_USER_HOME"),
System.getProperty("user.home") + File.separator + ".sonar")
.filter(Objects::nonNull)
.findFirst()
.map(File::new)
.get();
}
}
| 8,007 | 36.596244 | 161 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/PluginInstaller.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.List;
import java.util.Map;
public interface PluginInstaller {
/**
* Gets the list of plugins installed on server and downloads them if not
* already in local cache.
* @return information about all installed plugins, grouped by key
*/
Map<String, ScannerPlugin> installRemotes();
/**
* Used only by medium tests.
* @see org.sonar.scanner.mediumtest.ScannerMediumTester
*/
List<Object[]> installLocals();
}
| 1,336 | 32.425 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/PostJobExtensionDictionary.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Collection;
import java.util.stream.Collectors;
import org.sonar.api.batch.postjob.PostJob;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.scanner.postjob.PostJobOptimizer;
import org.sonar.scanner.postjob.PostJobWrapper;
public class PostJobExtensionDictionary extends AbstractExtensionDictionary {
private final PostJobContext postJobContext;
private final PostJobOptimizer postJobOptimizer;
public PostJobExtensionDictionary(ExtensionContainer container, PostJobOptimizer postJobOptimizer, PostJobContext postJobContext) {
super(container);
this.postJobOptimizer = postJobOptimizer;
this.postJobContext = postJobContext;
}
public Collection<PostJobWrapper> selectPostJobs() {
Collection<PostJob> result = sort(getFilteredExtensions(PostJob.class, null));
return result.stream()
.map(j -> new PostJobWrapper(j, postJobContext, postJobOptimizer))
.filter(PostJobWrapper::shouldExecute)
.collect(Collectors.toList());
}
}
| 1,946 | 38.734694 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPlugin.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.plugin.PluginType;
import org.sonar.updatecenter.common.Version;
public class ScannerPlugin {
private final String key;
private final long updatedAt;
private final PluginInfo info;
private final PluginType type;
public ScannerPlugin(String key, long updatedAt, PluginType type, PluginInfo info) {
this.key = key;
this.updatedAt = updatedAt;
this.type = type;
this.info = info;
}
public PluginInfo getInfo() {
return info;
}
public String getName() {
return info.getName();
}
public Version getVersion() {
return info.getVersion();
}
public String getKey() {
return key;
}
public long getUpdatedAt() {
return updatedAt;
}
public PluginType getType() {
return type;
}
}
| 1,699 | 25.5625 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import com.google.gson.Gson;
import java.io.File;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.plugin.PluginType;
import org.sonarqube.ws.client.GetRequest;
import static java.lang.String.format;
/**
* Downloads the plugins installed on server and stores them in a local user cache
*/
public class ScannerPluginInstaller implements PluginInstaller {
private static final Logger LOG = Loggers.get(ScannerPluginInstaller.class);
private static final String PLUGINS_WS_URL = "api/plugins/installed";
private final PluginFiles pluginFiles;
private final DefaultScannerWsClient wsClient;
public ScannerPluginInstaller(PluginFiles pluginFiles, DefaultScannerWsClient wsClient) {
this.pluginFiles = pluginFiles;
this.wsClient = wsClient;
}
@Override
public Map<String, ScannerPlugin> installRemotes() {
Profiler profiler = Profiler.create(LOG).startInfo("Load/download plugins");
try {
Map<String, ScannerPlugin> result = new HashMap<>();
Loaded loaded = loadPlugins(result);
if (!loaded.ok) {
// retry once, a plugin may have been uninstalled during downloads
result.clear();
loaded = loadPlugins(result);
if (!loaded.ok) {
throw new IllegalStateException(format("Fail to download plugin [%s]. Not found.", loaded.notFoundPlugin));
}
}
return result;
} finally {
profiler.stopInfo();
}
}
private Loaded loadPlugins(Map<String, ScannerPlugin> result) {
for (InstalledPlugin plugin : listInstalledPlugins()) {
Optional<File> jarFile = pluginFiles.get(plugin);
if (jarFile.isEmpty()) {
return new Loaded(false, plugin.key);
}
PluginInfo info = PluginInfo.create(jarFile.get());
result.put(info.getKey(), new ScannerPlugin(plugin.key, plugin.updatedAt, PluginType.valueOf(plugin.type), info));
}
return new Loaded(true, null);
}
/**
* Returns empty on purpose. This method is used only by medium tests.
*/
@Override
public List<Object[]> installLocals() {
return Collections.emptyList();
}
/**
* Gets information about the plugins installed on server (filename, checksum)
*/
private InstalledPlugin[] listInstalledPlugins() {
Profiler profiler = Profiler.create(LOG).startInfo("Load plugins index");
GetRequest getRequest = new GetRequest(PLUGINS_WS_URL);
InstalledPlugins installedPlugins;
try (Reader reader = wsClient.call(getRequest).contentReader()) {
installedPlugins = new Gson().fromJson(reader, InstalledPlugins.class);
} catch (Exception e) {
throw new IllegalStateException("Fail to parse response of " + PLUGINS_WS_URL, e);
}
profiler.stopInfo();
return installedPlugins.plugins;
}
private static class InstalledPlugins {
InstalledPlugin[] plugins;
public InstalledPlugins() {
// http://stackoverflow.com/a/18645370/229031
}
}
static class InstalledPlugin {
String key;
String hash;
long updatedAt;
String type;
public InstalledPlugin() {
// http://stackoverflow.com/a/18645370/229031
}
}
private static class Loaded {
private final boolean ok;
@Nullable
private final String notFoundPlugin;
private Loaded(boolean ok, @Nullable String notFoundPlugin) {
this.ok = ok;
this.notFoundPlugin = notFoundPlugin;
}
}
}
| 4,587 | 30.861111 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginJarExploder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import org.apache.commons.io.FileUtils;
import org.sonar.api.utils.ZipUtils;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginJarExploder;
import static org.sonar.core.util.FileUtils.deleteQuietly;
public class ScannerPluginJarExploder extends PluginJarExploder {
private final PluginFiles pluginFiles;
public ScannerPluginJarExploder(PluginFiles pluginFiles) {
this.pluginFiles = pluginFiles;
}
@Override
public ExplodedPlugin explode(PluginInfo info) {
try {
File dir = unzipFile(info.getNonNullJarFile());
return explodeFromUnzippedDir(info, info.getNonNullJarFile(), dir);
} catch (Exception e) {
throw new IllegalStateException(String.format("Fail to open plugin [%s]: %s", info.getKey(), info.getNonNullJarFile().getAbsolutePath()), e);
}
}
private File unzipFile(File cachedFile) throws IOException {
String filename = cachedFile.getName();
File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
if (!destDir.exists()) {
try (FileOutputStream out = new FileOutputStream(lockFile)) {
FileLock lock = createLockWithRetries(out.getChannel());
try {
// Recheck in case of concurrent processes
if (!destDir.exists()) {
File tempDir = pluginFiles.createTempDir();
ZipUtils.unzip(cachedFile, tempDir, newLibFilter());
FileUtils.moveDirectory(tempDir, destDir);
}
} finally {
lock.release();
}
} finally {
deleteQuietly(lockFile);
}
}
return destDir;
}
private static FileLock createLockWithRetries(FileChannel channel) throws IOException {
int tryCount = 0;
while (tryCount++ < 10) {
try {
return channel.lock();
} catch (OverlappingFileLockException ofle) {
// ignore overlapping file exception
}
try {
Thread.sleep(200L * tryCount);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new IOException("Unable to get lock after " + tryCount + " tries");
}
}
| 3,360 | 34.010417 | 147 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.Plugin;
import org.sonar.api.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginJarExploder;
import org.sonar.core.platform.PluginRepository;
import org.sonar.core.plugin.PluginType;
import static java.util.stream.Collectors.toList;
import static org.sonar.api.utils.Preconditions.checkState;
/**
* Orchestrates the installation and loading of plugins
*/
public class ScannerPluginRepository implements PluginRepository, Startable {
private static final Logger LOG = LoggerFactory.getLogger(ScannerPluginRepository.class);
private final PluginInstaller installer;
private final PluginJarExploder pluginJarExploder;
private final PluginClassLoader loader;
private Map<String, Plugin> pluginInstancesByKeys;
private Map<String, ScannerPlugin> pluginsByKeys;
private Map<ClassLoader, String> keysByClassLoader;
public ScannerPluginRepository(PluginInstaller installer, PluginJarExploder pluginJarExploder, PluginClassLoader loader) {
this.installer = installer;
this.pluginJarExploder = pluginJarExploder;
this.loader = loader;
}
@Override
public void start() {
pluginsByKeys = new HashMap<>(installer.installRemotes());
Map<String, ExplodedPlugin> explodedPLuginsByKey = pluginsByKeys.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> pluginJarExploder.explode(e.getValue().getInfo())));
pluginInstancesByKeys = new HashMap<>(loader.load(explodedPLuginsByKey));
// this part is only used by medium tests
for (Object[] localPlugin : installer.installLocals()) {
String pluginKey = (String) localPlugin[0];
PluginInfo pluginInfo = new PluginInfo(pluginKey);
pluginsByKeys.put(pluginKey, new ScannerPlugin(pluginInfo.getKey(), (long) localPlugin[2], PluginType.BUNDLED, pluginInfo));
pluginInstancesByKeys.put(pluginKey, (Plugin) localPlugin[1]);
}
keysByClassLoader = new HashMap<>();
for (Map.Entry<String, Plugin> e : pluginInstancesByKeys.entrySet()) {
keysByClassLoader.put(e.getValue().getClass().getClassLoader(), e.getKey());
}
logPlugins();
}
@CheckForNull
public String getPluginKey(ClassLoader cl) {
return keysByClassLoader.get(cl);
}
private void logPlugins() {
if (pluginsByKeys.isEmpty()) {
LOG.debug("No plugins loaded");
} else {
LOG.debug("Plugins:");
for (ScannerPlugin p : pluginsByKeys.values()) {
LOG.debug(" * {} {} ({})", p.getName(), p.getVersion(), p.getKey());
}
}
}
@Override
public void stop() {
// close plugin classloaders
loader.unload(pluginInstancesByKeys.values());
pluginInstancesByKeys.clear();
pluginsByKeys.clear();
keysByClassLoader.clear();
}
public Map<String, ScannerPlugin> getPluginsByKey() {
return pluginsByKeys;
}
@Override
public Collection<PluginInfo> getPluginInfos() {
return pluginsByKeys.values().stream().map(ScannerPlugin::getInfo).collect(toList());
}
public Collection<PluginInfo> getExternalPluginsInfos() {
return pluginsByKeys.values().stream().filter(p -> p.getType() == PluginType.EXTERNAL).map(ScannerPlugin::getInfo).collect(toList());
}
public Collection<PluginInfo> getBundledPluginsInfos() {
return pluginsByKeys.values().stream().filter(p -> p.getType() == PluginType.BUNDLED).map(ScannerPlugin::getInfo).collect(toList());
}
@Override
public PluginInfo getPluginInfo(String key) {
ScannerPlugin info = pluginsByKeys.get(key);
checkState(info != null, "Plugin [%s] does not exist", key);
return info.getInfo();
}
@Override
public Plugin getPluginInstance(String key) {
Plugin instance = pluginInstancesByKeys.get(key);
checkState(instance != null, "Plugin [%s] does not exist", key);
return instance;
}
@Override
public Collection<Plugin> getPluginInstances() {
return pluginInstancesByKeys.values();
}
@Override
public boolean hasPlugin(String key) {
return pluginsByKeys.containsKey(key);
}
}
| 5,236 | 33.682119 | 137 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerProperties.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.config.internal.Encryption;
import static org.sonar.api.CoreProperties.ENCRYPTION_SECRET_KEY_PATH;
import static org.sonar.api.CoreProperties.PROJECT_KEY_PROPERTY;
/**
* Properties that are coming from scanner.
*/
@Immutable
public class ScannerProperties {
private final Map<String, String> properties;
private final Encryption encryption;
public ScannerProperties(Map<String, String> properties) {
encryption = new Encryption(properties.get(ENCRYPTION_SECRET_KEY_PATH));
Map<String, String> decryptedProps = new HashMap<>(properties.size());
for (Map.Entry<String, String> entry : properties.entrySet()) {
String value = entry.getValue();
if (value != null && encryption.isEncrypted(value)) {
try {
value = encryption.decrypt(value);
} catch (Exception e) {
throw new IllegalStateException("Fail to decrypt the property " + entry.getKey() + ". Please check your secret key.", e);
}
}
decryptedProps.put(entry.getKey(), value);
}
this.properties = Collections.unmodifiableMap(new HashMap<>(decryptedProps));
}
public Encryption getEncryption() {
return encryption;
}
public Map<String, String> properties() {
return properties;
}
public String property(String key) {
return properties.get(key);
}
public String getProjectKey() {
return properties.get(PROJECT_KEY_PROPERTY);
}
}
| 2,443 | 32.479452 | 131 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerWsClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.sonarqube.ws.client.WsRequest;
import org.sonarqube.ws.client.WsResponse;
public interface ScannerWsClient {
WsResponse call(WsRequest request);
String baseUrl();
}
| 1,064 | 33.354839 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerWsClientProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import org.sonar.api.CoreProperties;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.System2;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonarqube.ws.client.HttpConnector;
import org.sonarqube.ws.client.WsClientFactories;
import org.springframework.context.annotation.Bean;
import static java.lang.Integer.parseInt;
import static java.lang.String.valueOf;
import static org.apache.commons.lang.StringUtils.defaultIfBlank;
public class ScannerWsClientProvider {
static final int CONNECT_TIMEOUT_MS = 5_000;
static final String READ_TIMEOUT_SEC_PROPERTY = "sonar.ws.timeout";
public static final String TOKEN_PROPERTY = "sonar.token";
private static final String TOKEN_ENV_VARIABLE = "SONAR_TOKEN";
static final int DEFAULT_READ_TIMEOUT_SEC = 60;
@Bean("DefaultScannerWsClient")
public DefaultScannerWsClient provide(ScannerProperties scannerProps, EnvironmentInformation env, GlobalAnalysisMode globalMode,
System2 system, AnalysisWarnings analysisWarnings) {
String url = defaultIfBlank(scannerProps.property("sonar.host.url"), "http://localhost:9000");
HttpConnector.Builder connectorBuilder = HttpConnector.newBuilder();
String timeoutSec = defaultIfBlank(scannerProps.property(READ_TIMEOUT_SEC_PROPERTY), valueOf(DEFAULT_READ_TIMEOUT_SEC));
String envVarToken = defaultIfBlank(system.envVariable(TOKEN_ENV_VARIABLE), null);
String token = defaultIfBlank(scannerProps.property(TOKEN_PROPERTY), envVarToken);
String login = defaultIfBlank(scannerProps.property(CoreProperties.LOGIN), token);
connectorBuilder
.readTimeoutMilliseconds(parseInt(timeoutSec) * 1_000)
.connectTimeoutMilliseconds(CONNECT_TIMEOUT_MS)
.userAgent(env.toString())
.url(url)
.credentials(login, scannerProps.property(CoreProperties.PASSWORD));
// OkHttp detect 'http.proxyHost' java property, but credentials should be filled
final String proxyUser = System.getProperty("http.proxyUser", "");
if (!proxyUser.isEmpty()) {
connectorBuilder.proxyCredentials(proxyUser, System.getProperty("http.proxyPassword"));
}
return new DefaultScannerWsClient(WsClientFactories.getDefault().newClient(connectorBuilder.build()), login != null,
globalMode, analysisWarnings);
}
}
| 3,195 | 46 | 130 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/SpringGlobalContainer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.bootstrap;
import java.time.Clock;
import java.util.List;
import java.util.Map;
import javax.annotation.Priority;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.Plugin;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.internal.MetadataLoader;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.UriReader;
import org.sonar.api.utils.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.documentation.DefaultDocumentationLinkGenerator;
import org.sonar.core.extension.CoreExtensionRepositoryImpl;
import org.sonar.core.extension.CoreExtensionsLoader;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginClassloaderFactory;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.core.util.DefaultHttpDownloader;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.scanner.extension.ScannerCoreExtensionsInstaller;
import org.sonar.scanner.notifications.DefaultAnalysisWarnings;
import org.sonar.scanner.platform.DefaultServer;
import org.sonar.scanner.repository.DefaultMetricsRepositoryLoader;
import org.sonar.scanner.repository.DefaultNewCodePeriodLoader;
import org.sonar.scanner.repository.MetricsRepositoryProvider;
import org.sonar.scanner.repository.settings.DefaultGlobalSettingsLoader;
import org.sonar.scanner.scan.SpringProjectScanContainer;
@Priority(3)
public class SpringGlobalContainer extends SpringComponentContainer {
private static final Logger LOG = LoggerFactory.getLogger(SpringGlobalContainer.class);
private final Map<String, String> scannerProperties;
private SpringGlobalContainer(Map<String, String> scannerProperties, List<?> addedExternally) {
super(addedExternally);
this.scannerProperties = scannerProperties;
}
public static SpringGlobalContainer create(Map<String, String> scannerProperties, List<?> extensions) {
return new SpringGlobalContainer(scannerProperties, extensions);
}
@Override
public void doBeforeStart() {
ScannerProperties rawScannerProperties = new ScannerProperties(scannerProperties);
GlobalAnalysisMode globalMode = new GlobalAnalysisMode(rawScannerProperties);
add(rawScannerProperties);
add(globalMode);
addBootstrapComponents();
}
private void addBootstrapComponents() {
Version apiVersion = MetadataLoader.loadApiVersion(System2.INSTANCE);
Version sqVersion = MetadataLoader.loadSQVersion(System2.INSTANCE);
SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE);
DefaultAnalysisWarnings analysisWarnings = new DefaultAnalysisWarnings(System2.INSTANCE);
LOG.debug("{} {}", edition.getLabel(), sqVersion);
add(
// plugins
ScannerPluginRepository.class,
PluginClassLoader.class,
PluginClassloaderFactory.class,
ScannerPluginJarExploder.class,
ExtensionInstaller.class,
new SonarQubeVersion(sqVersion),
new GlobalServerSettingsProvider(),
new GlobalConfigurationProvider(),
new ScannerWsClientProvider(),
DefaultServer.class,
DefaultDocumentationLinkGenerator.class,
new GlobalTempFolderProvider(),
analysisWarnings,
UriReader.class,
PluginFiles.class,
System2.INSTANCE,
Clock.systemDefaultZone(),
new MetricsRepositoryProvider(),
UuidFactoryImpl.INSTANCE,
DefaultHttpDownloader.class,
SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.SCANNER, edition),
ScannerPluginInstaller.class,
CoreExtensionRepositoryImpl.class,
CoreExtensionsLoader.class,
ScannerCoreExtensionsInstaller.class,
DefaultGlobalSettingsLoader.class,
DefaultNewCodePeriodLoader.class,
DefaultMetricsRepositoryLoader.class);
}
@Override
protected void doAfterStart() {
installPlugins();
loadCoreExtensions();
long startTime = System.currentTimeMillis();
String taskKey = StringUtils.defaultIfEmpty(scannerProperties.get(CoreProperties.TASK), CoreProperties.SCAN_TASK);
if (taskKey.equals("views")) {
throw MessageException.of("The task 'views' was removed with SonarQube 7.1. " +
"You can safely remove this call since portfolios and applications are automatically re-calculated.");
} else if (!taskKey.equals(CoreProperties.SCAN_TASK)) {
throw MessageException.of("Tasks support was removed in SonarQube 7.6.");
}
String analysisMode = StringUtils.defaultIfEmpty(scannerProperties.get("sonar.analysis.mode"), "publish");
if (!analysisMode.equals("publish")) {
throw MessageException.of("The preview mode, along with the 'sonar.analysis.mode' parameter, is no more supported. You should stop using this parameter.");
}
new SpringProjectScanContainer(this).execute();
LOG.info("Analysis total time: {}", formatTime(System.currentTimeMillis() - startTime));
}
private void installPlugins() {
PluginRepository pluginRepository = getComponentByType(PluginRepository.class);
for (PluginInfo pluginInfo : pluginRepository.getPluginInfos()) {
Plugin instance = pluginRepository.getPluginInstance(pluginInfo.getKey());
addExtension(pluginInfo, instance);
}
}
private void loadCoreExtensions() {
getComponentByType(CoreExtensionsLoader.class).load();
}
static String formatTime(long time) {
long h = time / (60 * 60 * 1000);
long m = (time - h * 60 * 60 * 1000) / (60 * 1000);
long s = (time - h * 60 * 60 * 1000 - m * 60 * 1000) / 1000;
long ms = time % 1000;
final String format;
if (h > 0) {
format = "%1$d:%2$02d:%3$02d.%4$03d s";
} else if (m > 0) {
format = "%2$d:%3$02d.%4$03d s";
} else {
format = "%3$d.%4$03d s";
}
return String.format(format, h, m, s, ms);
}
}
| 6,956 | 39.923529 | 161 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.bootstrap;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/AnalysisCacheEnabled.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import org.sonar.api.config.Configuration;
public class AnalysisCacheEnabled {
static final String PROP_KEY = "sonar.analysisCache.enabled";
private final Configuration configuration;
public AnalysisCacheEnabled(Configuration configuration) {
this.configuration = configuration;
}
public boolean isEnabled() {
return configuration.getBoolean(PROP_KEY).orElse(true);
}
}
| 1,270 | 34.305556 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/AnalysisCacheLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.util.Optional;
import org.sonar.scanner.protocol.internal.SensorCacheData;
public interface AnalysisCacheLoader {
Optional<SensorCacheData> load();
}
| 1,042 | 36.25 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/AnalysisCacheMemoryStorage.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.io.InputStream;
import javax.annotation.Nullable;
import org.sonar.scanner.protocol.internal.SensorCacheData;
public class AnalysisCacheMemoryStorage implements AnalysisCacheStorage {
private final AnalysisCacheLoader loader;
@Nullable
private SensorCacheData cache;
public AnalysisCacheMemoryStorage(AnalysisCacheLoader loader) {
this.loader = loader;
}
@Override
public InputStream get(String key) {
if (!contains(key)) {
throw new IllegalArgumentException("Key not found: " + key);
}
return cache.getEntries().get(key).newInput();
}
@Override
public boolean contains(String key) {
if (cache == null) {
return false;
}
return cache.getEntries().containsKey(key);
}
public void load() {
cache = loader.load().orElse(null);
}
}
| 1,692 | 29.781818 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/AnalysisCacheProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.io.InputStream;
import org.jetbrains.annotations.Nullable;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.springframework.context.annotation.Bean;
public class AnalysisCacheProvider {
@Bean("ReadCache")
public ReadCache provideReader(AnalysisCacheEnabled analysisCacheEnabled, AnalysisCacheMemoryStorage storage) {
if (analysisCacheEnabled.isEnabled()) {
storage.load();
return new ReadCacheImpl(storage);
}
return new NoOpReadCache();
}
@Bean("WriteCache")
public ScannerWriteCache provideWriter(AnalysisCacheEnabled analysisCacheEnabled, ReadCache readCache, BranchConfiguration branchConfiguration, FileStructure fileStructure) {
if (analysisCacheEnabled.isEnabled() && !branchConfiguration.isPullRequest()) {
return new WriteCacheImpl(readCache, fileStructure);
}
return new NoOpWriteCache();
}
static class NoOpWriteCache implements ScannerWriteCache {
@Override
public void write(String s, InputStream inputStream) {
// no op
}
@Override
public void write(String s, byte[] bytes) {
// no op
}
@Override
public void copyFromPrevious(String s) {
// no op
}
@Override
public void close() {
// no op
}
}
static class NoOpReadCache implements ReadCache {
@Nullable
@Override
public InputStream read(String s) {
return null;
}
@Override
public boolean contains(String s) {
return false;
}
}
}
| 2,494 | 29.060241 | 176 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/AnalysisCacheStorage.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.io.InputStream;
public interface AnalysisCacheStorage {
InputStream get(String key);
boolean contains(String key);
}
| 1,012 | 33.931034 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/DefaultAnalysisCacheLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import java.util.zip.GZIPInputStream;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.core.util.Protobuf;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.internal.SensorCacheData;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsResponse;
import static org.sonar.core.util.FileUtils.humanReadableByteCountSI;
/**
* Loads plugin cache into the local storage
*/
public class DefaultAnalysisCacheLoader implements AnalysisCacheLoader {
private static final Logger LOG = Loggers.get(DefaultAnalysisCacheLoader.class);
private static final String LOG_MSG = "Load analysis cache";
static final String CONTENT_ENCODING = "Content-Encoding";
static final String CONTENT_LENGTH = "Content-Length";
static final String ACCEPT_ENCODING = "Accept-Encoding";
private static final String URL = "api/analysis_cache/get";
private final DefaultScannerWsClient wsClient;
private final InputProject project;
private final BranchConfiguration branchConfiguration;
public DefaultAnalysisCacheLoader(DefaultScannerWsClient wsClient, InputProject project, BranchConfiguration branchConfiguration) {
this.project = project;
this.branchConfiguration = branchConfiguration;
this.wsClient = wsClient;
}
@Override
public Optional<SensorCacheData> load() {
String url = URL + "?project=" + project.key();
if (branchConfiguration.referenceBranchName() != null) {
url = url + "&branch=" + branchConfiguration.referenceBranchName();
}
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
GetRequest request = new GetRequest(url).setHeader(ACCEPT_ENCODING, "gzip");
try (WsResponse response = wsClient.call(request); InputStream is = response.contentStream()) {
Optional<String> contentEncoding = response.header(CONTENT_ENCODING);
Optional<Integer> length = response.header(CONTENT_LENGTH).map(Integer::parseInt);
boolean hasGzipEncoding = contentEncoding.isPresent() && contentEncoding.get().equals("gzip");
SensorCacheData cache = hasGzipEncoding ? decompress(is) : read(is);
if (length.isPresent()) {
profiler.stopInfo(LOG_MSG + String.format(" (%s)", humanReadableByteCountSI(length.get())));
} else {
profiler.stopInfo(LOG_MSG);
}
return Optional.of(cache);
} catch (HttpException e) {
if (e.code() == 404) {
profiler.stopInfo(LOG_MSG + " (404)");
return Optional.empty();
}
throw MessageException.of("Failed to download analysis cache: " + DefaultScannerWsClient.createErrorMessage(e));
} catch (Exception e) {
throw new IllegalStateException("Failed to download analysis cache", e);
}
}
public SensorCacheData decompress(InputStream is) throws IOException {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(is)) {
return read(gzipInputStream);
}
}
public SensorCacheData read(InputStream is) {
Iterable<SensorCacheEntry> it = () -> Protobuf.readStream(is, SensorCacheEntry.parser());
return new SensorCacheData(StreamSupport.stream(it.spliterator(), false).collect(Collectors.toList()));
}
}
| 4,582 | 40.663636 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/ReadCacheImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import java.io.InputStream;
import org.sonar.api.batch.sensor.cache.ReadCache;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkNotNull;
public class ReadCacheImpl implements ReadCache {
private final AnalysisCacheStorage cache;
public ReadCacheImpl(AnalysisCacheStorage storage) {
this.cache = storage;
}
@Override
public InputStream read(String key) {
checkNotNull(key);
checkArgument(contains(key));
return cache.get(key);
}
@Override
public boolean contains(String key) {
checkNotNull(key);
return cache.contains(key);
}
}
| 1,518 | 30.645833 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/ScannerWriteCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import org.sonar.api.batch.sensor.cache.WriteCache;
public interface ScannerWriteCache extends WriteCache {
void close();
}
| 1,004 | 36.222222 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/WriteCacheImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.cache;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.output.FileStructure;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkNotNull;
public class WriteCacheImpl implements ScannerWriteCache {
private final ReadCache readCache;
private final Set<String> keys = new HashSet<>();
private final FileStructure fileStructure;
private OutputStream stream = null;
public WriteCacheImpl(ReadCache readCache, FileStructure fileStructure) {
this.readCache = readCache;
this.fileStructure = fileStructure;
}
@Override
public void write(String key, InputStream data) {
checkNotNull(data);
try {
write(key, data.readAllBytes());
} catch (IOException e) {
throw new IllegalStateException("Failed to read sensor write cache data", e);
}
}
@Override
public void write(String key, byte[] data) {
checkNotNull(data);
checkKey(key);
try {
OutputStream out = getStream();
toProto(key, data).writeDelimitedTo(out);
keys.add(key);
} catch (IOException e) {
throw new IllegalStateException("Failed to write to sensor cache file", e);
}
}
private OutputStream getStream() throws IOException {
if (stream == null) {
stream = new GZIPOutputStream(new FileOutputStream(fileStructure.analysisCache()));
}
return stream;
}
@Override
public void copyFromPrevious(String key) {
checkArgument(readCache.contains(key), "Previous cache doesn't contain key '%s'", key);
write(key, readCache.read(key));
}
private static SensorCacheEntry toProto(String key, byte[] data) {
return SensorCacheEntry.newBuilder()
.setKey(key)
.setData(ByteString.copyFrom(data))
.build();
}
@Override
public void close() {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
throw new IllegalStateException("Failed to close sensor cache file", e);
}
}
}
private void checkKey(String key) {
checkNotNull(key);
checkArgument(!keys.contains(key), "Cache already contains key '%s'", key);
}
}
| 3,384 | 30.342593 | 91 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cache/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.cache;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/CiConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci;
import java.util.Optional;
/**
* Configuration provided by CI environments like TravisCI or Jenkins.
*
* @see CiVendor
*/
public interface CiConfiguration {
/**
* Name of the CI environment
*/
String getCiName();
/**
* The revision that triggered the analysis. It should
* be the revision as seen by end-user, but not the necessarily
* the effective revision of the clone on disk (merge commit with
* base branch for instance).
*/
Optional<String> getScmRevision();
}
| 1,379 | 29.666667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/CiConfigurationImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci;
import java.util.Optional;
import javax.annotation.Nullable;
import static org.apache.commons.lang.StringUtils.defaultIfBlank;
public class CiConfigurationImpl implements CiConfiguration {
private final String ciName;
@Nullable
private final String scmRevision;
public CiConfigurationImpl(@Nullable String scmRevision, String ciName) {
this.scmRevision = defaultIfBlank(scmRevision, null);
this.ciName = ciName;
}
@Override
public Optional<String> getScmRevision() {
return Optional.ofNullable(scmRevision);
}
@Override
public String getCiName() {
return ciName;
}
}
| 1,485 | 29.958333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/CiConfigurationProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.springframework.context.annotation.Bean;
public class CiConfigurationProvider {
private static final Logger LOG = LoggerFactory.getLogger(CiConfigurationProvider.class);
private static final String PROP_DISABLED = "sonar.ci.autoconfig.disabled";
@Bean("CiConfiguration")
public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) {
boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false);
if (disabled) {
return new EmptyCiConfiguration();
}
List<CiVendor> detectedVendors = Arrays.stream(ciVendors)
.filter(CiVendor::isDetected)
.collect(Collectors.toList());
if (detectedVendors.size() > 1) {
List<String> names = detectedVendors.stream().map(CiVendor::getName).collect(Collectors.toList());
throw MessageException.of("Multiple CI environments are detected: " + names + ". Please check environment variables or set property " + PROP_DISABLED + " to true.");
}
if (detectedVendors.size() == 1) {
CiVendor vendor = detectedVendors.get(0);
LOG.info("Auto-configuring with CI '{}'", vendor.getName());
return vendor.loadConfiguration();
}
return new EmptyCiConfiguration();
}
static class EmptyCiConfiguration implements CiConfiguration {
@Override
public Optional<String> getScmRevision() {
return Optional.empty();
}
@Override
public String getCiName() {
return "undetected";
}
}
}
| 2,605 | 34.69863 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/CiVendor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci;
import org.sonar.api.scanner.ScannerSide;
@ScannerSide
public interface CiVendor {
/**
* The display name, for example "Jenkins"
*/
String getName();
/**
* Whether the analyser runs in the CI vendor or not.
*/
boolean isDetected();
/**
* The configuration guessed by CI vendor. Called only
* if {@link #isDetected()} is true.
*/
CiConfiguration loadConfiguration();
}
| 1,280 | 28.113636 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.scanner.ci;
import javax.annotation.ParametersAreNonnullByDefault;
| 960 | 39.041667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/AppVeyor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
/**
* Support of https://www.appveyor.com
* <p>
* Environment variables: https://www.appveyor.com/docs/environment-variables/
*/
public class AppVeyor implements CiVendor {
private final System2 system;
public AppVeyor(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "AppVeyor";
}
@Override
public boolean isDetected() {
return "true".equalsIgnoreCase(system.envVariable("CI")) && "true".equalsIgnoreCase(system.envVariable("APPVEYOR"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("APPVEYOR_REPO_COMMIT");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,755 | 30.357143 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/AwsCodeBuild.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
public class AwsCodeBuild implements CiVendor {
private final System2 system;
public AwsCodeBuild(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "AwsCodeBuild";
}
@Override
public boolean isDetected() {
return environmentVariableIsPresent("CODEBUILD_BUILD_ID") &&
environmentVariableIsPresent("CODEBUILD_START_TIME");
}
@Override
public CiConfiguration loadConfiguration() {
return new CiConfigurationImpl(null, getName());
}
private boolean environmentVariableIsPresent(String key) {
return system.envVariable(key) != null;
}
}
| 1,678 | 29.527273 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/AzureDevops.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* Support of https://azure.microsoft.com/en-us/services/devops/
* <p>
* Environment variables: https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables
*/
public class AzureDevops implements CiVendor {
private final System2 system;
public AzureDevops(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Azure DevOps";
}
@Override
public boolean isDetected() {
return "true".equalsIgnoreCase(system.envVariable("TF_BUILD"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("SYSTEM_PULLREQUEST_SOURCECOMMITID");
if (isBlank(revision)) {
revision = system.envVariable("BUILD_SOURCEVERSION");
}
return new CiConfigurationImpl(revision, getName());
}
}
| 1,925 | 30.57377 | 97 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/Bamboo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
public class Bamboo implements CiVendor {
private final System2 system;
public Bamboo(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Bamboo";
}
@Override
public boolean isDetected() {
return system.envVariable("bamboo_buildNumber") != null;
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("bamboo_planRepository_revision");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,566 | 29.72549 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/BitbucketPipelines.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
public class BitbucketPipelines implements CiVendor {
private final System2 system;
public BitbucketPipelines(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Bitbucket Pipelines";
}
@Override
public boolean isDetected() {
String ci = system.envVariable("CI");
String revision = system.envVariable("BITBUCKET_COMMIT");
return "true".equals(ci) && isNotEmpty(revision);
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("BITBUCKET_COMMIT");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,749 | 30.818182 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/Bitrise.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import java.util.Optional;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
public class Bitrise implements CiVendor {
private final System2 system2;
public Bitrise(System2 system2) {
this.system2 = system2;
}
@Override
public String getName() {
return "Bitrise";
}
@Override
public boolean isDetected() {
return environmentVariableIsTrue("CI") && environmentVariableIsTrue("BITRISE_IO");
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system2.envVariable("BITRISE_GIT_COMMIT");
return new CiConfigurationImpl(revision, getName());
}
private boolean environmentVariableIsTrue(String key) {
return Optional.ofNullable(system2.envVariable(key))
.map(Boolean::parseBoolean)
.orElse(false);
}
}
| 1,791 | 29.896552 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/Buildkite.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
/**
* Support of https://buildkite.com
* <p>
* Environment variables: https://buildkite.com/docs/pipelines/environment-variables
*/
public class Buildkite implements CiVendor {
private final System2 system;
public Buildkite(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Buildkite";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("CI")) && "true".equals(system.envVariable("BUILDKITE"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("BUILDKITE_COMMIT");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,738 | 30.053571 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/CircleCi.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
/**
* Support of https://circleci.com
* <p>
* Environment variables: https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables
*/
public class CircleCi implements CiVendor {
private final System2 system;
public CircleCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "CircleCI";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("CI")) && "true".equals(system.envVariable("CIRCLECI"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("CIRCLE_SHA1");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,740 | 30.089286 | 100 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/CirrusCi.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isEmpty;
/**
* Support https://cirrus-ci.org/
* <p>
* Environment variables are documented at https://cirrus-ci.org/guide/writing-tasks/#environment-variables
*/
public class CirrusCi implements CiVendor {
private static final String PROPERTY_COMMIT = "CIRRUS_CHANGE_IN_REPO";
private final System2 system;
public CirrusCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "CirrusCI";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("CIRRUS_CI"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable(PROPERTY_COMMIT);
if (isEmpty(revision)) {
LoggerFactory.getLogger(getClass()).warn("Missing environment variable " + PROPERTY_COMMIT);
}
return new CiConfigurationImpl(revision, getName());
}
}
| 2,009 | 30.904762 | 107 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/CodeMagic.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isEmpty;
public class CodeMagic implements CiVendor {
private static final Logger LOG = LoggerFactory.getLogger(CodeMagic.class);
private final System2 system;
public CodeMagic(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "CodeMagic";
}
@Override
public boolean isDetected() {
return !isEmpty(system.envVariable("FCI_BUILD_ID"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("FCI_COMMIT");
if (isEmpty(revision)) {
LOG.warn("Missing environment variable FCI_COMMIT");
}
return new CiConfigurationImpl(revision, getName());
}
}
| 1,841 | 29.7 | 77 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.