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-duplications/src/test/java/org/sonar/duplications/index/DataUtilsTest.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.duplications.index;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import org.junit.Test;
public class DataUtilsTest {
@Test
public void testSort() {
int[] expected = new int[200];
int[] actual = new int[expected.length];
for (int i = 0; i < expected.length; i++) {
expected[i] = (int) (Math.random() * 900);
actual[i] = expected[i];
}
Arrays.sort(expected);
DataUtils.sort(new SimpleSortable(actual, actual.length));
assertThat(actual, equalTo(expected));
}
@Test
public void testSearch() {
int[] a = new int[] { 1, 2, 4, 4, 4, 5, 0 };
SimpleSortable sortable = new SimpleSortable(a, a.length - 1);
// search 4
a[a.length - 1] = 4;
assertThat(DataUtils.binarySearch(sortable), is(2));
// search 5
a[a.length - 1] = 5;
assertThat(DataUtils.binarySearch(sortable), is(5));
// search -5
a[a.length - 1] = -5;
assertThat(DataUtils.binarySearch(sortable), is(0));
// search 10
a[a.length - 1] = 10;
assertThat(DataUtils.binarySearch(sortable), is(6));
// search 3
a[a.length - 1] = 3;
assertThat(DataUtils.binarySearch(sortable), is(2));
}
static class SimpleSortable implements DataUtils.Sortable {
private final int[] a;
private final int size;
public SimpleSortable(int[] a, int size) {
this.a = a;
this.size = size;
}
public int size() {
return size;
}
public void swap(int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public boolean isLess(int i, int j) {
return a[i] < a[j];
}
}
}
| 2,586 | 27.428571 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/index/PackedMemoryCloneIndexTest.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.duplications.index;
import org.junit.Before;
import org.junit.Test;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.duplications.index.PackedMemoryCloneIndex.ResourceBlocks;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
public class PackedMemoryCloneIndexTest {
private PackedMemoryCloneIndex index;
@Before
public void setUp() {
index = new PackedMemoryCloneIndex();
}
@Test
public void test() {
index.insert(newBlock("a", 1));
index.insert(newBlock("a", 2));
index.insert(newBlock("b", 1));
index.insert(newBlock("c", 1));
index.insert(newBlock("d", 1));
index.insert(newBlock("e", 1));
index.insert(newBlock("e", 2));
index.insert(newBlock("e", 3));
assertThat(index.noResources()).isEqualTo(5);
assertThat(index.getBySequenceHash(new ByteArray(1L)).size(), is(5));
assertThat(index.getBySequenceHash(new ByteArray(2L)).size(), is(2));
assertThat(index.getBySequenceHash(new ByteArray(3L)).size(), is(1));
assertThat(index.getBySequenceHash(new ByteArray(4L)).size(), is(0));
assertThat(index.getByResourceId("a").size(), is(2));
assertThat(index.getByResourceId("b").size(), is(1));
assertThat(index.getByResourceId("e").size(), is(3));
assertThat(index.getByResourceId("does not exist").size(), is(0));
}
/**
* When: query by a hash value.
* Expected: all blocks should have same hash, which presented in the form of the same object.
*/
@Test
public void should_construct_blocks_with_normalized_hash() {
index.insert(newBlock("a", 1));
index.insert(newBlock("b", 1));
index.insert(newBlock("c", 1));
ByteArray requestedHash = new ByteArray(1L);
Collection<Block> blocks = index.getBySequenceHash(requestedHash);
assertThat(blocks.size(), is(3));
for (Block block : blocks) {
assertThat(block.getBlockHash(), sameInstance(requestedHash));
}
}
@Test
public void iterate() {
index.insert(newBlock("a", 1));
index.insert(newBlock("c", 1));
index.insert(newBlock("b", 1));
index.insert(newBlock("c", 2));
index.insert(newBlock("a", 2));
Iterator<ResourceBlocks> it = index.iterator();
ArrayList<ResourceBlocks> resourcesBlocks = new ArrayList<>();
while(it.hasNext()) {
resourcesBlocks.add(it.next());
}
assertThat(resourcesBlocks).hasSize(3);
assertThat(resourcesBlocks.get(0).resourceId()).isEqualTo("a");
assertThat(resourcesBlocks.get(1).resourceId()).isEqualTo("b");
assertThat(resourcesBlocks.get(2).resourceId()).isEqualTo("c");
assertThat(resourcesBlocks.get(0).blocks()).hasSize(2);
assertThat(resourcesBlocks.get(1).blocks()).hasSize(1);
assertThat(resourcesBlocks.get(2).blocks()).hasSize(2);
}
/**
* Given: index with initial capacity 1.
* Expected: size and capacity should be increased after insertion of two blocks.
*/
@Test
public void should_increase_capacity() {
CloneIndex index = new PackedMemoryCloneIndex(8, 1);
index.insert(newBlock("a", 1));
index.insert(newBlock("a", 2));
assertThat(index.getByResourceId("a").size(), is(2));
}
/**
* Given: index, which accepts blocks with 4-byte hash.
* Expected: exception during insertion of block with 8-byte hash.
*/
@Test(expected = IllegalArgumentException.class)
public void attempt_to_insert_hash_of_incorrect_size() {
CloneIndex index = new PackedMemoryCloneIndex(4, 1);
index.insert(newBlock("a", 1));
}
/**
* Given: index, which accepts blocks with 4-byte hash.
* Expected: exception during search by 8-byte hash.
*/
@Test(expected = IllegalArgumentException.class)
public void attempt_to_find_hash_of_incorrect_size() {
CloneIndex index = new PackedMemoryCloneIndex(4, 1);
index.getBySequenceHash(new ByteArray(1L));
}
private static Block newBlock(String resourceId, long hash) {
return Block.builder()
.setResourceId(resourceId)
.setBlockHash(new ByteArray(hash))
.setIndexInFile(1)
.setLines(1, 2)
.build();
}
}
| 5,245 | 32.845161 | 96 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/internal/pmd/PmdBlockChunkerTest.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.duplications.internal.pmd;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.api.batch.sensor.cpd.internal.TokensLine;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class PmdBlockChunkerTest {
@Test
public void shouldBuildBlocks() {
TokensLine line1 = new TokensLine(0, 9, 1, Character.toString((char) 1));
TokensLine line2 = new TokensLine(10, 19, 2, Character.toString((char) 2));
TokensLine line3 = new TokensLine(20, 29, 3, Character.toString((char) 3));
List<Block> blocks = new PmdBlockChunker(2).chunk("resourceId", Arrays.asList(line1, line2, line3));
assertThat(blocks.size(), is(2));
Block block = blocks.get(0);
// assertThat(block.getLengthInUnits(), is(11));
assertThat(block.getStartLine(), is(1));
assertThat(block.getEndLine(), is(2));
assertThat(block.getBlockHash(), is(new ByteArray(1L * 31 + 2)));
block = blocks.get(1);
// assertThat(block.getLengthInUnits(), is(33));
assertThat(block.getStartLine(), is(2));
assertThat(block.getEndLine(), is(3));
assertThat(block.getBlockHash(), is(new ByteArray(2L * 31 + 3)));
}
}
| 2,151 | 36.754386 | 104 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/java/JavaDuplicationsFunctionalTest.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.duplications.java;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.BlockChunker;
import org.sonar.duplications.detector.suffixtree.SuffixTreeCloneDetectionAlgorithm;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.CloneIndex;
import org.sonar.duplications.index.ClonePart;
import org.sonar.duplications.index.MemoryCloneIndex;
import org.sonar.duplications.statement.Statement;
import org.sonar.duplications.statement.StatementChunker;
import org.sonar.duplications.token.TokenChunker;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* From <a href="http://research.cs.queensu.ca/TechReports/Reports/2007-541.pdf">A Survey on Software Clone Detection Research (2007 year)</a>:
* <ul>
* <li>Type 1: Identical code fragments except for variations in whitespace (may be also variations in layout) and comments.
* Type 1 is widely know as Exact clones.</li>
* <li>Type 2: Structurally/syntactically identical fragments except for variations in identifiers, literals, types, layout and comments.
* The reserved words and the sentence structures are essentially the same.</li>
* <li>Type 3: Copied fragments with further modifications. Statements can be changed,
* added and/or deleted in addition to variations in identifiers, literals, types, layout
* and comments.</li>
* </ul>
*/
public class JavaDuplicationsFunctionalTest {
@Test
public void type1() {
String fragment0 = source(
"if (a >= b) {",
" c = d + b; // Comment1",
" d = d + 1;}",
"else",
" c = d - a; // Comment2");
String fragment1 = source(
"if (a>=b) {",
" // Comment1",
" c=d+b;",
" d=d+1;",
"} else // Comment2",
" c=d-a;");
List<CloneGroup> duplications = detect2(fragment0, fragment1);
assertThat(duplications.size(), is(1));
ClonePart part = duplications.get(0).getOriginPart();
assertThat(part.getStartLine(), is(1));
assertThat(part.getEndLine(), is(5));
}
/**
* Supports only subset of Type 2.
*
* @see #type2
* @see #literalsNormalization()
*/
@Test
public void type2_literals() {
String fragment0 = source(
"if (a >= b) {",
" c = b + 1; // Comment1",
" d = '1';}",
"else",
" c = d - a; // Comment2");
String fragment1 = source(
"if (a >= b) {",
" c = b + 2; // Comment1",
" d = '2';}",
"else",
" c = d - a; // Comment2");
List<CloneGroup> duplications = detect2(fragment0, fragment1);
assertThat(duplications.size(), is(1));
ClonePart part = duplications.get(0).getOriginPart();
assertThat(part.getStartLine(), is(1));
assertThat(part.getEndLine(), is(5));
}
@Test
public void type2() {
String fragment0 = source(
"if (a >= b) {",
" c = d + b; // Comment1",
" d = d + 1;}",
"else",
" c = d - a; // Comment2");
String fragment1 = source(
"if (m >= n) {",
" // Comment3",
" y = x + n; // Comment1",
" x = x + 5;}",
"else",
" y = x - m; // Comment2");
List<CloneGroup> duplications = detect2(fragment0, fragment1);
assertThat(duplications.size(), is(0));
}
/**
* Does not support Type 3, however able to detect inner parts.
*/
@Test
public void type3() {
String fragment0 = source(
"public int getSoLinger() throws SocketException {",
" Object o = impl.getOption( SocketOptions.SO_LINGER);",
" if (o instanceof Integer) {",
" return((Integer) o).intValue();",
" }",
" else return -1;",
"}");
String fragment1 = source(
"public synchronized int getSoTimeout() throws SocketException {",
" Object o = impl.getOption( SocketOptions.SO_TIMEOUT);",
" if (o instanceof Integer) {",
" return((Integer) o).intValue();",
" }",
" else return -0;",
"}");
List<CloneGroup> duplications = detect2(fragment0, fragment1);
assertThat(duplications.size(), is(1));
ClonePart part = duplications.get(0).getOriginPart();
assertThat(part.getStartLine(), is(3));
assertThat(part.getEndLine(), is(6));
}
private String source(String... lines) {
return Arrays.stream(lines).collect(joining("\n"));
}
private static List<CloneGroup> detect2(String... fragments) {
MemoryCloneIndex index = new MemoryCloneIndex();
for (int i = 0; i < fragments.length; i++) {
addToIndex(index, "fragment" + i, fragments[i]);
}
return detect(index, index.getByResourceId("fragment0"));
}
private static void addToIndex(CloneIndex index, String resourceId, String sourceCode) {
List<Statement> statements = STATEMENT_CHUNKER.chunk(TOKEN_CHUNKER.chunk(sourceCode));
BlockChunker blockChunker = new BlockChunker(2);
List<Block> blocks = blockChunker.chunk(resourceId, statements);
for (Block block : blocks) {
index.insert(block);
}
}
private static List<CloneGroup> detect(CloneIndex index, Collection<Block> blocks) {
return SuffixTreeCloneDetectionAlgorithm.detect(index, blocks);
}
private static final int BLOCK_SIZE = 1;
private static TokenChunker TOKEN_CHUNKER = JavaTokenProducer.build();
private static StatementChunker STATEMENT_CHUNKER = JavaStatementBuilder.build();
private static BlockChunker BLOCK_CHUNKER = new BlockChunker(BLOCK_SIZE);
private List<CloneGroup> detect(String... lines) {
String sourceCode = Arrays.stream(lines).collect(joining("\n"));
MemoryCloneIndex index = new MemoryCloneIndex();
List<Statement> statements = STATEMENT_CHUNKER.chunk(TOKEN_CHUNKER.chunk(sourceCode));
List<Block> blocks = BLOCK_CHUNKER.chunk("resourceId", statements);
for (Block block : blocks) {
index.insert(block);
}
return detect(index, blocks);
}
/**
* See SONAR-2837
*/
@Test
public void initializationOfMultidimensionalArray() {
List<CloneGroup> duplications = detect("int[][] idx = new int[][] { { 1, 2 }, { 3, 4 } };");
assertThat(duplications.size(), is(0));
}
/**
* See SONAR-2782
*/
@Test
public void chainOfCases() {
List<CloneGroup> duplications = detect(
"switch (a) {",
" case 'a': case 'b': case 'c':",
" doSomething();",
" case 'd': case 'e': case 'f':",
" doSomethingElse();",
"}");
assertThat(duplications.size(), is(0));
}
@Test
public void literalsNormalization() {
List<CloneGroup> duplications = detect(
"String s = \"abc\";",
"String s = \"def\";");
assertThat(duplications.size(), is(1));
duplications = detect(
"int i = 1;",
"int i = 2;");
assertThat(duplications.size(), is(1));
}
}
| 7,802 | 32.779221 | 143 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/java/JavaStatementBuilderTest.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.duplications.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.duplications.DuplicationsTestUtil;
import org.sonar.duplications.statement.Statement;
import org.sonar.duplications.statement.StatementChunker;
import org.sonar.duplications.token.TokenChunker;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaStatementBuilderTest {
private final TokenChunker tokenChunker = JavaTokenProducer.build();
private final StatementChunker statementChunker = JavaStatementBuilder.build();
private List<Statement> chunk(String sourceCode) {
return statementChunker.chunk(tokenChunker.chunk(sourceCode));
}
@Test
public void shouldIgnoreImportStatement() {
assertThat(chunk("import org.sonar.duplications.java;")).isEmpty();
}
@Test
public void shouldIgnorePackageStatement() {
assertThat(chunk("package org.sonar.duplications.java;")).isEmpty();
}
@Test
public void shouldHandleAnnotation() {
List<Statement> statements = chunk("" +
"@Entity" +
"@Table(name = \"properties\")" +
"@Column(updatable = true, nullable = true)");
assertThat(statements).hasSize(3);
assertThat(statements.get(0).getValue()).isEqualTo("@Entity");
assertThat(statements.get(1).getValue()).isEqualTo("@Table(name=$CHARS)");
assertThat(statements.get(2).getValue()).isEqualTo("@Column(updatable=true,nullable=true)");
}
@Test
public void shouldHandleIf() {
List<Statement> statements = chunk("if (a > b) { something(); }");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("if(a>b)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
statements = chunk("if (a > b) { something(); } else { somethingOther(); }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("if(a>b)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("else");
assertThat(statements.get(3).getValue()).isEqualTo("somethingOther()");
statements = chunk("if (a > 0) { something(); } else if (a == 0) { somethingOther(); }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("if(a>$NUMBER)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("elseif(a==$NUMBER)");
assertThat(statements.get(3).getValue()).isEqualTo("somethingOther()");
}
@Test
public void shouldHandleFor() {
List<Statement> statements = chunk("for (int i = 0; i < 10; i++) { something(); }");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("for(inti=$NUMBER;i<$NUMBER;i++)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
statements = chunk("for (Item item : items) { something(); }");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("for(Itemitem:items)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
}
@Test
public void shouldHandleWhile() {
List<Statement> statements = chunk("while (i < args.length) { something(); }");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("while(i<args.length)");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
statements = chunk("while (true);");
assertThat(statements.size()).isOne();
assertThat(statements.get(0).getValue()).isEqualTo("while(true)");
}
@Test
public void shouldHandleDoWhile() {
List<Statement> statements = chunk("do { something(); } while (true);");
assertThat(statements).hasSize(3);
assertThat(statements.get(0).getValue()).isEqualTo("do");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("while(true)");
}
@Test
public void shouldHandleSwitch() {
List<Statement> statements = chunk("" +
"switch (month) {" +
" case 1 : monthString=\"January\"; break;" +
" case 2 : monthString=\"February\"; break;" +
" default: monthString=\"Invalid\";" +
"}");
assertThat(statements).hasSize(6);
assertThat(statements.get(0).getValue()).isEqualTo("switch(month)");
assertThat(statements.get(1).getValue()).isEqualTo("case$NUMBER:monthString=$CHARS");
assertThat(statements.get(2).getValue()).isEqualTo("break");
assertThat(statements.get(3).getValue()).isEqualTo("case$NUMBER:monthString=$CHARS");
assertThat(statements.get(4).getValue()).isEqualTo("break");
assertThat(statements.get(5).getValue()).isEqualTo("default:monthString=$CHARS");
}
/**
* See SONAR-2782
*/
@Test
public void shouldHandleNestedSwitch() {
List<Statement> statements = chunk("" +
"switch (a) {" +
" case 'a': case 'b': case 'c': something(); break;" +
" case 'd': case 'e': case 'f': somethingOther(); break;" +
"}");
assertThat(statements).hasSize(5);
assertThat(statements.get(0).getValue()).isEqualTo("switch(a)");
assertThat(statements.get(1).getValue()).isEqualTo("case$CHARS:case$CHARS:case$CHARS:something()");
assertThat(statements.get(2).getValue()).isEqualTo("break");
assertThat(statements.get(3).getValue()).isEqualTo("case$CHARS:case$CHARS:case$CHARS:somethingOther()");
assertThat(statements.get(4).getValue()).isEqualTo("break");
}
@Test
public void shouldHandleArray() {
List<Statement> statements = chunk("new Integer[] { 1, 2, 3, 4 };");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("newInteger[]");
assertThat(statements.get(1).getValue()).isEqualTo("{$NUMBER,$NUMBER,$NUMBER,$NUMBER}");
}
/**
* See SONAR-2837
*/
@Test
public void shouldHandleMultidimensionalArray() {
List<Statement> statements = chunk("new Integer[][] { { 1, 2 }, {3, 4} };");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("newInteger[][]");
assertThat(statements.get(1).getValue()).isEqualTo("{{$NUMBER,$NUMBER},{$NUMBER,$NUMBER}}");
statements = chunk("new Integer[][] { null, {3, 4} };");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("newInteger[][]");
assertThat(statements.get(1).getValue()).isEqualTo("{null,{$NUMBER,$NUMBER}}");
}
@Test
public void shouldHandleTryCatch() {
List<Statement> statements;
statements = chunk("try { } catch (Exception e) { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exceptione)");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } catch (Exception e) { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exceptione)");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } catch (Exception e) { onException(); }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exceptione)");
assertThat(statements.get(3).getValue()).isEqualTo("onException()");
statements = chunk("try { something(); } catch (Exception1 e) { onException1(); } catch (Exception2 e) { onException2(); }");
assertThat(statements).hasSize(6);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exception1e)");
assertThat(statements.get(3).getValue()).isEqualTo("onException1()");
assertThat(statements.get(4).getValue()).isEqualTo("catch(Exception2e)");
assertThat(statements.get(5).getValue()).isEqualTo("onException2()");
}
@Test
public void shouldHandleTryFinnaly() {
List<Statement> statements;
statements = chunk("try { } finally { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
assertThat(statements.get(2).getValue()).isEqualTo("finally");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } finally { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("finally");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } finally { somethingOther(); }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("finally");
assertThat(statements.get(3).getValue()).isEqualTo("somethingOther()");
}
@Test
public void shouldHandleTryCatchFinally() {
List<Statement> statements;
statements = chunk("try { } catch (Exception e) {} finally { }");
assertThat(statements).hasSize(6);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exceptione)");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
assertThat(statements.get(4).getValue()).isEqualTo("finally");
assertThat(statements.get(5).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } catch (Exception e) { onException(); } finally { somethingOther(); }");
assertThat(statements).hasSize(6);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exceptione)");
assertThat(statements.get(3).getValue()).isEqualTo("onException()");
assertThat(statements.get(4).getValue()).isEqualTo("finally");
assertThat(statements.get(5).getValue()).isEqualTo("somethingOther()");
}
/**
* Java 7.
*/
@Test
public void shouldHandleMultiCatch() {
List<Statement> statements;
statements = chunk("try { } catch (Exception1 | Exception2 e) { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exception1|Exception2e)");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } catch (Exception1 | Exception2 e) { }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exception1|Exception2e)");
assertThat(statements.get(3).getValue()).isEqualTo("{}");
statements = chunk("try { something(); } catch (Exception1 | Exception2 e) { onException(); }");
assertThat(statements).hasSize(4);
assertThat(statements.get(0).getValue()).isEqualTo("try");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
assertThat(statements.get(2).getValue()).isEqualTo("catch(Exception1|Exception2e)");
assertThat(statements.get(3).getValue()).isEqualTo("onException()");
}
/**
* Java 7.
*/
@Test
public void shouldHandleTryWithResource() {
List<Statement> statements;
statements = chunk("try (FileInputStream in = new FileInputStream()) {}");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("try(FileInputStreamin=newFileInputStream())");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
statements = chunk("try (FileInputStream in = new FileInputStream(); FileOutputStream out = new FileOutputStream()) {}");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("try(FileInputStreamin=newFileInputStream();FileOutputStreamout=newFileOutputStream())");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
statements = chunk("try (FileInputStream in = new FileInputStream(); FileOutputStream out = new FileOutputStream();) {}");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("try(FileInputStreamin=newFileInputStream();FileOutputStreamout=newFileOutputStream();)");
assertThat(statements.get(1).getValue()).isEqualTo("{}");
statements = chunk("try (FileInputStream in = new FileInputStream()) { something(); }");
assertThat(statements).hasSize(2);
assertThat(statements.get(0).getValue()).isEqualTo("try(FileInputStreamin=newFileInputStream())");
assertThat(statements.get(1).getValue()).isEqualTo("something()");
}
/**
* Java 8.
*/
@Test
public void shouldHandleLambda() {
List<Statement> statements;
statements = chunk("List<String> result = lines.stream().filter(line -> !\"mkyong\".equals(line)).toList();");
assertThat(statements.size()).isOne();
assertThat(statements).extracting(Statement::getValue).containsExactly("List<String>result=lines.stream().filter(line->!$CHARS.equals(line)).toList()");
statements = chunk("items.forEach((k,v)->{System.out.println(\"Item : \" + k + \" Count : \" + v); if(\"E\".equals(k)) { System.out.println(\"Hello E\");}});");
assertThat(statements).hasSize(5);
assertThat(statements).extracting(Statement::getValue)
.containsExactly("items.forEach((k,v)->",
"System.out.println($CHARS+k+$CHARS+v)",
"if($CHARS.equals(k))",
"System.out.println($CHARS)",
")");
}
/**
* Java 9.
*/
@Test
public void shouldHandleModuleInfo() {
List<Statement> statements;
statements = chunk("module com.application.infra { requires com.application.domain; exports com.application.infra.api; }");
assertThat(statements).hasSize(3);
assertThat(statements).extracting(Statement::getValue)
.containsExactly("modulecom.application.infra",
"requirescom.application.domain",
"exportscom.application.infra.api");
}
/**
* Java 11.
*/
@Test
public void shouldHandleVar() {
List<Statement> statements;
statements = chunk("IFunc f = (@NonNull var x, final var y) -> Foo.foo(x, y);");
assertThat(statements.size()).isOne();
assertThat(statements).extracting(Statement::getValue).containsExactly("IFuncf=(@NonNullvarx,finalvary)->Foo.foo(x,y)");
}
@Test
public void realExamples() {
assertThat(chunk(DuplicationsTestUtil.findFile("/java/MessageResources.java")).size()).isPositive();
assertThat(chunk(DuplicationsTestUtil.findFile("/java/RequestUtils.java")).size()).isPositive();
}
private List<Statement> chunk(File file) {
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
return statementChunker.chunk(tokenChunker.chunk(reader));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
}
| 16,924 | 43.075521 | 164 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/java/JavaTokenProducerTest.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.duplications.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.duplications.DuplicationsTestUtil;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenChunker;
import org.sonar.duplications.token.TokenQueue;
import static org.assertj.core.api.Assertions.assertThat;
public class JavaTokenProducerTest {
private static final Token NUMERIC_LITTERAL = new Token("$NUMBER", 1, 0);
private static final Token STRING_LITTERAL = new Token("$CHARS", 1, 0);
private final TokenChunker chunker = JavaTokenProducer.build();
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.6">White Space</a>
*/
@Test
public void shouldIgnoreWhitespaces() {
assertThat(chunk(" \t\f\n\r")).isEmpty();
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.7">Comments</a>
*/
@Test
public void shouldIgnoreEndOfLineComment() {
assertThat(chunk("// This is a comment")).isEmpty();
assertThat(chunk("// This is a comment \n and_this_is_not")).containsExactly(new Token("and_this_is_not", 2, 1));
}
@Test
public void shouldIgnoreTraditionalComment() {
assertThat(chunk("/* This is a comment \n and the second line */")).isEmpty();
assertThat(chunk("/** This is a javadoc \n and the second line */")).isEmpty();
assertThat(chunk("/* this \n comment /* \n // /** ends \n here: */")).isEmpty();
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.8">Identifiers</a>
*/
@Test
public void shouldPreserveIdentifiers() {
assertThat(chunk("String")).containsExactly(new Token("String", 1, 0));
assertThat(chunk("i3")).containsExactly(new Token("i3", 1, 0));
assertThat(chunk("MAX_VALUE")).containsExactly(new Token("MAX_VALUE", 1, 0));
assertThat(chunk("isLetterOrDigit")).containsExactly(new Token("isLetterOrDigit", 1, 0));
assertThat(chunk("_")).containsExactly(new Token("_", 1, 0));
assertThat(chunk("_123_")).containsExactly(new Token("_123_", 1, 0));
assertThat(chunk("_Field")).containsExactly(new Token("_Field", 1, 0));
assertThat(chunk("_Field5")).containsExactly(new Token("_Field5", 1, 0));
assertThat(chunk("$")).containsExactly(new Token("$", 1, 0));
assertThat(chunk("$field")).containsExactly(new Token("$field", 1, 0));
assertThat(chunk("i2j")).containsExactly(new Token("i2j", 1, 0));
assertThat(chunk("from1to4")).containsExactly(new Token("from1to4", 1, 0));
// identifier with unicode
assertThat(chunk("αβγ")).containsExactly(new Token("αβγ", 1, 0));
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.9">Keywords</a>
*/
@Test
public void shouldPreserverKeywords() {
assertThat(chunk("private static final")).containsExactly(
new Token("private", 1, 0),
new Token("static", 1, 8),
new Token("final", 1, 15));
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.1">Integer Literals</a>
*/
@Test
public void shouldNormalizeDecimalIntegerLiteral() {
assertThat(chunk("543")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("543l")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("543L")).containsExactly(NUMERIC_LITTERAL);
}
@Test
public void shouldNormalizeOctalIntegerLiteral() {
assertThat(chunk("077")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("077l")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("077L")).containsExactly(NUMERIC_LITTERAL);
}
@Test
public void shouldNormalizeHexIntegerLiteral() {
assertThat(chunk("0xFF")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xFFl")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xFFL")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XFF")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XFFl")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XFFL")).containsExactly(NUMERIC_LITTERAL);
}
/**
* New in Java 7.
*/
@Test
public void shouldNormalizeBinaryIntegerLiteral() {
assertThat(chunk("0b10")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0b10l")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0b10L")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0B10")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0B10l")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0B10L")).containsExactly(NUMERIC_LITTERAL);
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.2">Floating-Point Literals</a>
*/
@Test
public void shouldNormalizeDecimalFloatingPointLiteral() {
// with dot at the end
assertThat(chunk("1234.")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234.E1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234.e+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234.E-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234.f")).containsExactly(NUMERIC_LITTERAL);
// with dot between
assertThat(chunk("12.34")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34E1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34e+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34E-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34f")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34E1F")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34E+1d")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("12.34e-1D")).containsExactly(NUMERIC_LITTERAL);
// with dot at the beginning
assertThat(chunk(".1234")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234e1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234E+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234E-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234f")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234E1F")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234e+1d")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1234E-1D")).containsExactly(NUMERIC_LITTERAL);
// without dot
assertThat(chunk("1234e1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234E+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234E-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234E1f")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234e+1d")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1234E-1D")).containsExactly(NUMERIC_LITTERAL);
}
@Test
public void shouldNormalizeHexadecimalFloatingPointLiteral() {
// with dot at the end
assertThat(chunk("0xAF.")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAF.P1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.p+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAF.p-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.f")).containsExactly(NUMERIC_LITTERAL);
// with dot between
assertThat(chunk("0XAF.BC")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.BCP1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAF.BCp+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.BCP-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.BCf")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAF.BCp1F")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAF.BCP+1d")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAF.BCp-1D")).containsExactly(NUMERIC_LITTERAL);
// without dot
assertThat(chunk("0xAFp1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAFp+1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAFp-1")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAFp1f")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xAFp+1d")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0XAFp-1D")).containsExactly(NUMERIC_LITTERAL);
}
/**
* New in Java 7.
*/
@Test
public void shouldNormalizeNumericLiteralsWithUnderscores() {
assertThat(chunk("54_3L")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("07_7L")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0b1_0L")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xF_FL")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1_234.")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1_2.3_4")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk(".1_234")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("1_234e1_0")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xA_F.")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0xA_F.B_C")).containsExactly(NUMERIC_LITTERAL);
assertThat(chunk("0x1.ffff_ffff_ffff_fP1_023")).containsExactly(NUMERIC_LITTERAL);
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.3">Boolean Literals</a>
*/
@Test
public void shouldPreserveBooleanLiterals() {
assertThat(chunk("true false")).containsExactly(new Token("true", 1, 0), new Token("false", 1, 5));
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.4">Character Literals</a>
*/
@Test
public void shouldNormalizeCharacterLiterals() {
// single character
assertThat(chunk("'a'")).containsExactly(STRING_LITTERAL);
// escaped LF
assertThat(chunk("'\\n'")).containsExactly(STRING_LITTERAL);
// escaped quote
assertThat(chunk("'\\''")).containsExactly(STRING_LITTERAL);
// octal escape
assertThat(chunk("'\\177'")).containsExactly(STRING_LITTERAL);
// unicode escape
assertThat(chunk("'\\u03a9'")).containsExactly(STRING_LITTERAL);
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5">String Literals</a>
*/
@Test
public void shouldNormalizeStringLiterals() {
// regular string
assertThat(chunk("\"string\"")).containsExactly(STRING_LITTERAL);
// empty string
assertThat(chunk("\"\"")).containsExactly(STRING_LITTERAL);
// escaped LF
assertThat(chunk("\"\\n\"")).containsExactly(STRING_LITTERAL);
// escaped double quotes
assertThat(chunk("\"string, which contains \\\"escaped double quotes\\\"\"")).containsExactly(STRING_LITTERAL);
// octal escape
assertThat(chunk("\"string \\177\"")).containsExactly(STRING_LITTERAL);
// unicode escape
assertThat(chunk("\"string \\u03a9\"")).containsExactly(STRING_LITTERAL);
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.7">The Null Literal</a>
*/
@Test
public void shouldPreserverNullLiteral() {
assertThat(chunk("null")).containsExactly(new Token("null", 1, 0));
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.11">Separators</a>
*/
@Test
public void shouldPreserveSeparators() {
assertThat(chunk("(){}[];,.")).containsExactly(
new Token("(", 1, 0), new Token(")", 1, 1),
new Token("{", 1, 2), new Token("}", 1, 3),
new Token("[", 1, 4), new Token("]", 1, 5),
new Token(";", 1, 6), new Token(",", 1, 7),
new Token(".", 1, 8));
}
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.12">Operators</a>
*/
@Test
public void shouldPreserveOperators() {
assertThat(chunk("+=")).containsExactly(new Token("+", 1, 0), new Token("=", 1, 1));
assertThat(chunk("--")).containsExactly(new Token("-", 1, 0), new Token("-", 1, 1));
}
@Test
public void realExamples() {
File testFile = DuplicationsTestUtil.findFile("/java/MessageResources.java");
assertThat(chunk(testFile)).isNotEmpty();
testFile = DuplicationsTestUtil.findFile("/java/RequestUtils.java");
assertThat(chunk(testFile)).isNotEmpty();
}
private TokenQueue chunk(File file) {
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
return chunker.chunk(reader);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(reader);
}
}
private List<Token> chunk(String sourceCode) {
List<Token> target = new ArrayList<>();
chunker.chunk(sourceCode).forEach(target::add);
return target;
}
}
| 13,714 | 38.985423 | 117 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/junit/TestNamePrinter.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.duplications.junit;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class TestNamePrinter extends TestWatcher {
@Override
protected void starting(Description description) {
System.out.println("Executing " + description.getMethodName());
}
}
| 1,148 | 33.818182 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/StatementChannelDisptacherTest.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.duplications.statement;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.statement.matcher.TokenMatcher;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class StatementChannelDisptacherTest {
@Test(expected = IllegalStateException.class)
public void shouldThrowAnException() {
TokenMatcher tokenMatcher = mock(TokenMatcher.class);
StatementChannel channel = StatementChannel.create(tokenMatcher);
StatementChannelDisptacher dispatcher = new StatementChannelDisptacher(asList(channel));
TokenQueue tokenQueue = mock(TokenQueue.class);
when(tokenQueue.peek()).thenReturn(new Token("a", 1, 0)).thenReturn(null);
List<Statement> statements = mock(List.class);
dispatcher.consume(tokenQueue, statements);
}
@Test
public void shouldConsume() {
TokenMatcher tokenMatcher = mock(TokenMatcher.class);
when(tokenMatcher.matchToken(any(TokenQueue.class), anyList())).thenReturn(true);
StatementChannel channel = StatementChannel.create(tokenMatcher);
StatementChannelDisptacher dispatcher = new StatementChannelDisptacher(asList(channel));
TokenQueue tokenQueue = mock(TokenQueue.class);
when(tokenQueue.peek()).thenReturn(new Token("a", 1, 0)).thenReturn(null);
List<Statement> statements = mock(List.class);
assertThat(dispatcher.consume(tokenQueue, statements), is(true));
verify(tokenQueue, times(2)).peek();
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(statements);
}
}
| 2,861 | 39.885714 | 92 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/StatementChannelTest.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.duplications.statement;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.duplications.statement.matcher.AnyTokenMatcher;
import org.sonar.duplications.statement.matcher.TokenMatcher;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class StatementChannelTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
StatementChannel.create((TokenMatcher[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptEmpty() {
StatementChannel.create(new TokenMatcher[]{});
}
@Test
public void shouldPushForward() {
TokenQueue tokenQueue = mock(TokenQueue.class);
TokenMatcher matcher = mock(TokenMatcher.class);
List<Statement> output = mock(List.class);
StatementChannel channel = StatementChannel.create(matcher);
assertThat(channel.consume(tokenQueue, output), is(false));
ArgumentCaptor<List> matchedTokenList = ArgumentCaptor.forClass(List.class);
verify(matcher).matchToken(eq(tokenQueue), matchedTokenList.capture());
verifyNoMoreInteractions(matcher);
verify(tokenQueue).pushForward(matchedTokenList.getValue());
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(output);
}
@Test
public void shouldCreateStatement() {
Token token = new Token("a", 1, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(token)));
TokenMatcher matcher = spy(new AnyTokenMatcher());
StatementChannel channel = StatementChannel.create(matcher);
List<Statement> output = mock(List.class);
assertThat(channel.consume(tokenQueue, output), is(true));
verify(matcher).matchToken(eq(tokenQueue), anyList());
verifyNoMoreInteractions(matcher);
ArgumentCaptor<Statement> statement = ArgumentCaptor.forClass(Statement.class);
verify(output).add(statement.capture());
assertThat(statement.getValue().getValue(), is("a"));
assertThat(statement.getValue().getStartLine(), is(1));
assertThat(statement.getValue().getEndLine(), is(1));
verifyNoMoreInteractions(output);
}
@Test
public void shouldNotCreateStatement() {
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(new Token("a", 1, 1))));
TokenMatcher matcher = spy(new AnyTokenMatcher());
StatementChannel channel = StatementChannel.create(matcher);
List<Statement> output = mock(List.class);
assertThat(channel.consume(tokenQueue, output), is(true));
verify(matcher).matchToken(eq(tokenQueue), anyList());
verifyNoMoreInteractions(matcher);
verify(output).add(any());
verifyNoMoreInteractions(output);
}
}
| 4,006 | 37.902913 | 85 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/StatementChunkerTest.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.duplications.statement;
import org.junit.Test;
public class StatementChunkerTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
StatementChunker.builder().build().chunk(null);
}
}
| 1,095 | 33.25 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/StatementTest.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.duplications.statement;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class StatementTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
new Statement(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptEmpty() {
new Statement(new ArrayList<>());
}
@Test
public void shouldCreateStatementFromListOfTokens() {
Statement statement = new Statement(Arrays.asList(new Token("a", 1, 1), new Token("b", 2, 1)));
assertThat(statement.getValue(), is("ab"));
assertThat(statement.getStartLine(), is(1));
assertThat(statement.getEndLine(), is(2));
}
@Test
public void test_equals() {
Statement statement = new Statement(1, 2, "value_1");
assertThat(statement)
.isEqualTo(statement)
.isNotEqualTo(null)
.isNotEqualTo(new Object())
.isNotEqualTo(new Statement(1, 2, "value_2"))
.isNotEqualTo(new Statement(1, 0, "value_1"))
.isNotEqualTo(new Statement(0, 2, "value_1"))
.isEqualTo(new Statement(1, 2, "value_1"));
}
}
| 2,170 | 32.4 | 99 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/TokenMatcherFactoryTest.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.duplications.statement;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import org.sonar.duplications.statement.matcher.AnyTokenMatcher;
import org.sonar.duplications.statement.matcher.BridgeTokenMatcher;
import org.sonar.duplications.statement.matcher.ExactTokenMatcher;
import org.sonar.duplications.statement.matcher.ForgetLastTokenMatcher;
import org.sonar.duplications.statement.matcher.OptTokenMatcher;
import org.sonar.duplications.statement.matcher.TokenMatcher;
import org.sonar.duplications.statement.matcher.UptoTokenMatcher;
public class TokenMatcherFactoryTest {
@Test
public void shouldCreateMatchers() {
assertThat(TokenMatcherFactory.anyToken(), instanceOf(AnyTokenMatcher.class));
assertThat(TokenMatcherFactory.bridge("(", ")"), instanceOf(BridgeTokenMatcher.class));
assertThat(TokenMatcherFactory.forgetLastToken(), instanceOf(ForgetLastTokenMatcher.class));
assertThat(TokenMatcherFactory.from("if"), instanceOf(ExactTokenMatcher.class));
assertThat(TokenMatcherFactory.opt(mock(TokenMatcher.class)), instanceOf(OptTokenMatcher.class));
assertThat(TokenMatcherFactory.to(";"), instanceOf(UptoTokenMatcher.class));
assertThat(TokenMatcherFactory.token(";"), instanceOf(ExactTokenMatcher.class));
}
}
| 2,230 | 44.530612 | 101 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/AnyTokenMatcherTest.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.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class AnyTokenMatcherTest {
@Test
public void shouldMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("b", 2, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2)));
List<Token> output = mock(List.class);
AnyTokenMatcher matcher = new AnyTokenMatcher();
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(tokenQueue).poll();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verifyNoMoreInteractions(output);
}
}
| 1,856 | 33.388889 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/BridgeTokenMatcherTest.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.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class BridgeTokenMatcherTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNullAsLeft() {
new BridgeTokenMatcher(null, ")");
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNullAsRight() {
new BridgeTokenMatcher("(", null);
}
@Test
public void shouldMatch() {
Token t1 = new Token("(", 1, 1);
Token t2 = new Token("a", 2, 1);
Token t3 = new Token("(", 3, 1);
Token t4 = new Token("b", 4, 1);
Token t5 = new Token(")", 5, 1);
Token t6 = new Token("c", 6, 1);
Token t7 = new Token(")", 7, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2, t3, t4, t5, t6, t7)));
List<Token> output = mock(List.class);
BridgeTokenMatcher matcher = new BridgeTokenMatcher("(", ")");
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(tokenQueue, times(1)).isNextTokenValue("(");
verify(tokenQueue, times(7)).poll();
verify(tokenQueue, times(7)).peek();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verify(output).add(t2);
verify(output).add(t3);
verify(output).add(t4);
verify(output).add(t5);
verify(output).add(t6);
verify(output).add(t7);
verifyNoMoreInteractions(output);
}
@Test
public void shouldNotMatchWhenNoLeft() {
Token t1 = new Token("a", 1, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1)));
List<Token> output = mock(List.class);
BridgeTokenMatcher matcher = new BridgeTokenMatcher("(", ")");
assertThat(matcher.matchToken(tokenQueue, output), is(false));
verify(tokenQueue).isNextTokenValue("(");
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(output);
}
@Test
public void shouldNotMatchWhenNoRight() {
Token t1 = new Token("(", 1, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1)));
List<Token> output = mock(List.class);
BridgeTokenMatcher matcher = new BridgeTokenMatcher("(", ")");
assertThat(matcher.matchToken(tokenQueue, output), is(false));
verify(tokenQueue, times(1)).isNextTokenValue("(");
verify(tokenQueue, times(1)).poll();
verify(tokenQueue, times(2)).peek();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verifyNoMoreInteractions(output);
}
}
| 3,724 | 33.813084 | 91 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/ExactTokenMatcherTest.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.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class ExactTokenMatcherTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
new ExactTokenMatcher(null);
}
@Test
public void shouldMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("b", 2, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2)));
List<Token> output = mock(List.class);
ExactTokenMatcher matcher = new ExactTokenMatcher("a");
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(tokenQueue).isNextTokenValue("a");
verify(tokenQueue).poll();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verifyNoMoreInteractions(output);
}
@Test
public void shouldNotMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("b", 2, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2)));
List<Token> output = mock(List.class);
ExactTokenMatcher matcher = new ExactTokenMatcher("b");
assertThat(matcher.matchToken(tokenQueue, output), is(false));
verify(tokenQueue).isNextTokenValue("b");
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(output);
}
}
| 2,527 | 33.162162 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/ForgetLastTokenMatcherTest.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.duplications.statement.matcher;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public class ForgetLastTokenMatcherTest {
@Test
public void shouldMatch() {
TokenQueue tokenQueue = spy(new TokenQueue());
Token token = new Token("a", 0, 0);
List<Token> output = new ArrayList<>(Arrays.asList(token));
ForgetLastTokenMatcher matcher = new ForgetLastTokenMatcher();
assertThat(matcher.matchToken(tokenQueue, output), is(true));
assertThat(output.size(), is(0));
verify(tokenQueue).pushForward(eq(Collections.singletonList(token)));
}
}
| 1,820 | 34.705882 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/OptTokenMatcherTest.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.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class OptTokenMatcherTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
new OptTokenMatcher(null);
}
@Test
public void shouldMatch() {
TokenQueue tokenQueue = spy(new TokenQueue());
TokenMatcher delegate = mock(TokenMatcher.class);
OptTokenMatcher matcher = new OptTokenMatcher(delegate);
List<Token> output = mock(List.class);
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(delegate).matchToken(tokenQueue, output);
verifyNoMoreInteractions(delegate);
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(output);
}
}
| 1,957 | 33.350877 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/UptoTokenMatcherTest.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.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class UptoTokenMatcherTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
new UptoTokenMatcher(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptEmpty() {
new UptoTokenMatcher(new String[] {});
}
@Test
public void shouldMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token(";", 2, 1); // should stop on this token
Token t3 = new Token(";", 3, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2, t3)));
List<Token> output = mock(List.class);
UptoTokenMatcher matcher = new UptoTokenMatcher(new String[] { ";" });
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(tokenQueue, times(2)).poll();
verify(tokenQueue).peek();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verify(output).add(t2);
verifyNoMoreInteractions(output);
}
@Test
public void shouldMatchAnyOfProvidedTokens() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("{", 2, 1);
Token t3 = new Token("b", 3, 1);
Token t4 = new Token("}", 4, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2, t3, t4)));
List<Token> output = mock(List.class);
UptoTokenMatcher matcher = new UptoTokenMatcher(new String[] { "{", "}" });
assertThat(matcher.matchToken(tokenQueue, output), is(true));
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(tokenQueue, times(4)).poll();
verify(tokenQueue, times(2)).peek();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verify(output).add(t2);
verify(output).add(t3);
verify(output).add(t4);
verifyNoMoreInteractions(output);
}
@Test
public void shouldNotMatch() {
Token t1 = new Token("a", 1, 1);
Token t2 = new Token("b", 2, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2)));
List<Token> output = mock(List.class);
UptoTokenMatcher matcher = new UptoTokenMatcher(new String[] { ";" });
assertThat(matcher.matchToken(tokenQueue, output), is(false));
verify(tokenQueue, times(2)).poll();
verify(tokenQueue, times(2)).peek();
verifyNoMoreInteractions(tokenQueue);
verify(output).add(t1);
verify(output).add(t2);
verifyNoMoreInteractions(output);
}
}
| 3,739 | 33.953271 | 79 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/token/BlackHoleTokenChannelTest.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.duplications.token;
import org.junit.Test;
import org.sonar.channel.CodeReader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
public class BlackHoleTokenChannelTest {
@Test
public void shouldConsume() {
BlackHoleTokenChannel channel = new BlackHoleTokenChannel("ABC");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("ABCD");
assertThat(channel.consume(codeReader, output)).isTrue();
assertThat(codeReader.getLinePosition()).isOne();
assertThat(codeReader.getColumnPosition()).isEqualTo(3);
verifyNoInteractions(output);
}
}
| 1,569 | 34.681818 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/token/TokenChannelTest.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.duplications.token;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.channel.CodeReader;
public class TokenChannelTest {
@Test
public void shouldConsume() {
TokenChannel channel = new TokenChannel("ABC");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("ABCD");
assertThat(channel.consume(codeReader, output), is(true));
ArgumentCaptor<Token> token = ArgumentCaptor.forClass(Token.class);
verify(output).add(token.capture());
assertThat(token.getValue(), is(new Token("ABC", 1, 0)));
verifyNoMoreInteractions(output);
assertThat(codeReader.getLinePosition(), is(1));
assertThat(codeReader.getColumnPosition(), is(3));
}
@Test
public void shouldNormalize() {
TokenChannel channel = new TokenChannel("ABC", "normalized");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("ABCD");
assertThat(channel.consume(codeReader, output), is(true));
ArgumentCaptor<Token> token = ArgumentCaptor.forClass(Token.class);
verify(output).add(token.capture());
assertThat(token.getValue(), is(new Token("normalized", 1, 0)));
verifyNoMoreInteractions(output);
assertThat(codeReader.getLinePosition(), is(1));
assertThat(codeReader.getColumnPosition(), is(3));
}
@Test
public void shouldNotConsume() {
TokenChannel channel = new TokenChannel("ABC");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("123");
assertThat(channel.consume(new CodeReader("123"), output), is(false));
verifyNoInteractions(output);
assertThat(codeReader.getLinePosition(), is(1));
assertThat(codeReader.getColumnPosition(), is(0));
}
@Test
public void shouldCorrectlyDeterminePositionWhenTokenSpansMultipleLines() {
TokenChannel channel = new TokenChannel("AB\nC");
TokenQueue output = mock(TokenQueue.class);
CodeReader codeReader = new CodeReader("AB\nCD");
assertThat(channel.consume(codeReader, output), is(true));
ArgumentCaptor<Token> token = ArgumentCaptor.forClass(Token.class);
verify(output).add(token.capture());
assertThat(token.getValue(), is(new Token("AB\nC", 1, 0)));
verifyNoMoreInteractions(output);
assertThat(codeReader.getLinePosition(), is(2));
assertThat(codeReader.getColumnPosition(), is(1));
}
}
| 3,537 | 37.043011 | 77 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/token/TokenQueueTest.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.duplications.token;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class TokenQueueTest {
TokenQueue tokenQueue;
@Before
public void initTest() {
List<Token> tokenList = new ArrayList<>();
tokenList.add(new Token("a", 1, 0));
tokenList.add(new Token("bc", 1, 2));
tokenList.add(new Token("def", 1, 5));
tokenQueue = new TokenQueue(tokenList);
}
@Test
public void shouldPeekToken() {
Token token = tokenQueue.peek();
assertThat(token, is(new Token("a", 1, 0)));
assertThat(tokenQueue.size(), is(3));
}
@Test
public void shouldPollToken() {
Token token = tokenQueue.poll();
assertThat(token, is(new Token("a", 1, 0)));
assertThat(tokenQueue.size(), is(2));
}
@Test
public void shouldPushTokenAtBegining() {
Token pushedToken = new Token("push", 1, 0);
List<Token> pushedTokenList = new ArrayList<>();
pushedTokenList.add(pushedToken);
tokenQueue.pushForward(pushedTokenList);
assertThat(tokenQueue.peek(), is(pushedToken));
assertThat(tokenQueue.size(), is(4));
}
}
| 2,075 | 29.086957 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/token/TokenTest.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.duplications.token;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class TokenTest {
@Test
public void test_equals() {
Token token = new Token("value_1", 1, 2);
Assertions.assertThat(token)
.isEqualTo(token)
.isNotEqualTo(null)
.isNotEqualTo(new Object())
.isNotEqualTo(new Token("value_1", 1, 0))
.isNotEqualTo(new Token("value_1", 0, 2))
.isNotEqualTo(new Token("value_2", 1, 2))
.isEqualTo(new Token("value_1", 1, 2));
}
}
| 1,370 | 32.439024 | 75 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/utils/FastStringComparatorTest.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.duplications.utils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class FastStringComparatorTest {
static int compare(String left, String right) {
return FastStringComparator.INSTANCE.compare(left, right);
}
@Test
public void sameHashCode() {
// Next two Strings have same hash code in Java - see http://www.drmaciver.com/2008/07/javalangstringhashcode/
String s1 = "Od";
String s2 = "PE";
assertThat(s1).hasSameHashCodeAs(s2);
assertThat(compare(s1, s2)).isNegative();
assertThat(compare(s2, s1)).isPositive();
}
@Test
public void differentHashCode() {
String s1 = "a";
String s2 = "c";
assertThat(s1.hashCode()).isNotEqualTo(s2.hashCode());
assertThat(compare(s1, s2)).isEqualTo(-1);
assertThat(compare(s2, s1)).isOne();
}
@Test
public void sameObject() {
String s1 = "a";
String s2 = s1;
assertThat(s1).isSameAs(s2);
assertThat(compare(s1, s2)).isZero();
assertThat(compare(s1, s2)).isZero();
}
@Test
public void sameString() {
String s1 = new String("a");
String s2 = new String("a");
assertThat(s1).isNotSameAs(s2);
assertThat(compare(s1, s2)).isZero();
assertThat(compare(s1, s2)).isZero();
}
}
| 2,131 | 28.611111 | 114 | java |
sonarqube | sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/utils/SortedListsUtilsTest.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.duplications.utils;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.junit.Test;
public class SortedListsUtilsTest {
@Test
public void testContains() {
assertThat(contains(Arrays.asList(1, 2, 3), Arrays.asList(1, 2)), is(true));
assertThat(contains(Arrays.asList(1, 2), Arrays.asList(1, 2, 3)), is(false));
assertThat(contains(Arrays.asList(1, 2, 3), Arrays.asList(1, 3)), is(true));
assertThat(contains(Arrays.asList(1, 3), Arrays.asList(1, 2, 3)), is(false));
assertThat(contains(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 2, 3)), is(true));
assertThat(contains(Arrays.asList(1, 2, 2, 3), Arrays.asList(1, 2, 3)), is(true));
}
private static boolean contains(List<Integer> a, List<Integer> b) {
return SortedListsUtils.contains(a, b, IntegerComparator.INSTANCE);
}
private static class IntegerComparator implements Comparator<Integer> {
public static final IntegerComparator INSTANCE = new IntegerComparator();
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
}
| 2,039 | 34.172414 | 86 | java |
sonarqube | sonarqube-master/sonar-duplications/test-resources/org/sonar/duplications/cpd/CPDTest/CPDFile1.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.fork;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.cpd.CPDListener;
import net.sourceforge.pmd.cpd.CPDNullListener;
import net.sourceforge.pmd.cpd.Language;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.Tokens;
import org.sonar.duplications.cpd.MatchAlgorithm;
public class CPDFile1 {
private Map<String, SourceCode> source = new HashMap<String, SourceCode>();
private CPDListener listener = new CPDNullListener();
private Tokens tokens = new Tokens();
private int minimumTileSize;
private MatchAlgorithm matchAlgorithm;
private Language language;
private boolean skipDuplicates;
public static boolean debugEnable = false;
private boolean loadSourceCodeSlices = true;
private String encoding = System.getProperty("file.encoding");
public CPD(int minimumTileSize, Language language) {
this.minimumTileSize = minimumTileSize;
this.language = language;
}
public void skipDuplicates() {
this.skipDuplicates = true;
}
public void setCpdListener(CPDListener cpdListener) {
this.listener = cpdListener;
}
}
| 1,233 | 28.380952 | 79 | java |
sonarqube | sonarqube-master/sonar-duplications/test-resources/org/sonar/duplications/cpd/CPDTest/CPDFile2.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.fork;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.cpd.CPDListener;
import net.sourceforge.pmd.cpd.CPDNullListener;
import net.sourceforge.pmd.cpd.Language;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.Tokens;
import org.sonar.duplications.cpd.MatchAlgorithm;
public class CPDFile2 {
private Map<String, SourceCode> source = new HashMap<String, SourceCode>();
private CPDListener listener = new CPDNullListener();
private Tokens tokens = new Tokens();
private int minimumTileSize;
private MatchAlgorithm matchAlgorithm;
private Language language;
private boolean skipDuplicates;
public static boolean debugEnable = false;
private boolean loadSourceCodeSlices = true;
private String encoding = System.getProperty("file.encoding");
public CPD(int minimumTileSize, Language language) {
this.minimumTileSize = minimumTileSize;
this.language = language;
}
public void skipDuplicates() {
this.skipDuplicates = true;
}
public void setCpdListener(CPDListener cpdListener) {
this.listener = cpdListener;
}
}
| 1,233 | 28.380952 | 79 | java |
sonarqube | sonarqube-master/sonar-duplications/test-resources/org/sonar/duplications/cpd/CPDTest/CPDFile3.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.fork;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.cpd.CPDListener;
import net.sourceforge.pmd.cpd.CPDNullListener;
import net.sourceforge.pmd.cpd.Language;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.Tokens;
import org.apache.commons.io.FileUtils;
import org.sonar.duplications.cpd.CPD;
import org.sonar.duplications.cpd.Match;
import org.sonar.duplications.cpd.MatchAlgorithm;
public class CPDFile2 {
public void method1(){
CPD cpd = new CPD(20, cpdLanguage);
cpd.setEncoding(Charset.defaultCharset().name());
cpd.setLoadSourceCodeSlices(false);
cpd.add(FileUtils.toFile(CPD.class.getResource("/org/sonar/duplications/cpd/CPDTest/CPDFile1.java")));
cpd.add(FileUtils.toFile(CPD.class.getResource("/org/sonar/duplications/cpd/CPDTest/CPDFile2.java")));
cpd.go();
List<Match> matches = getMatches(cpd);
assertThat(matches.size(), is(1));
org.sonar.duplications.cpd.Match match = matches.get(0);
assertThat(match.getLineCount(), is(26));
assertThat(match.getFirstMark().getBeginLine(), is(16));
assertThat(match.getSourceCodeSlice(), is(nullValue()));
}
public void method1Duplicated(){
CPD cpd = new CPD(20, cpdLanguage);
cpd.setEncoding(Charset.defaultCharset().name());
cpd.setLoadSourceCodeSlices(false);
cpd.add(FileUtils.toFile(CPD.class.getResource("/org/sonar/duplications/cpd/CPDTest/CPDFile1.java")));
cpd.add(FileUtils.toFile(CPD.class.getResource("/org/sonar/duplications/cpd/CPDTest/CPDFile2.java")));
cpd.go();
List<Match> matches = getMatches(cpd);
assertThat(matches.size(), is(1));
org.sonar.duplications.cpd.Match match = matches.get(0);
assertThat(match.getLineCount(), is(26));
assertThat(match.getFirstMark().getBeginLine(), is(16));
assertThat(match.getSourceCodeSlice(), is(nullValue()));
}
}
| 2,208 | 33.515625 | 106 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/BlackholeChannel.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.markdown;
import org.sonar.channel.Channel;
import org.sonar.channel.CodeReader;
class BlackholeChannel extends Channel<MarkdownOutput> {
@Override
public boolean consume(CodeReader code, MarkdownOutput output) {
output.append((char)code.pop());
return true;
}
}
| 1,141 | 33.606061 | 75 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlBlockquoteChannel.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.markdown;
import org.sonar.channel.Channel;
import org.sonar.channel.CodeReader;
import org.sonar.channel.RegexChannel;
/**
* Markdown treats lines starting with a greater than sign (>) as a block of quoted text.
*
* E.g, the input:
* <pre>
* > Yesterday it worked
* > Today it is not working
* > Software is like that
* </pre>
* will produce:
* {@literal<blockquote>}{@literal<p>}Yesterday it worked{@literal<br/>}
* Today it is not working{@literal<br/>}
* Software is like that{@literal</blockquote>}
* @since 4.4
*/
class HtmlBlockquoteChannel extends Channel<MarkdownOutput> {
private QuotedLineElementChannel quotedLineElement = new QuotedLineElementChannel();
private EndOfLine endOfLine = new EndOfLine();
private boolean pendingBlockConstruction;
@Override
public boolean consume(CodeReader code, MarkdownOutput output) {
try {
if (code.getColumnPosition() == 0 && quotedLineElement.consume(code, output)) {
while (endOfLine.consume(code, output) && quotedLineElement.consume(code, output)) {
// consume input
}
output.append("</blockquote>");
return true;
}
return false;
} finally {
pendingBlockConstruction = false;
}
}
private class QuotedLineElementChannel extends RegexChannel<MarkdownOutput> {
private QuotedLineElementChannel() {
super(">\\s[^\r\n]*+");
}
@Override
public void consume(CharSequence token, MarkdownOutput output) {
if (!pendingBlockConstruction) {
output.append("<blockquote>");
pendingBlockConstruction = true;
}
output.append(token.subSequence(searchIndexOfFirstCharacter(token), token.length()));
output.append("<br/>");
}
private int searchIndexOfFirstCharacter(CharSequence token) {
int index = 0;
while (index < token.length()) {
if (token.charAt(index) == '&') {
index += 4;
while (index < token.length()) {
index ++;
if (token.charAt(index) != ' ') {
return index;
}
}
}
index ++;
}
return token.length() - 1;
}
}
private static final class EndOfLine extends RegexChannel<MarkdownOutput> {
public EndOfLine() {
super("(\r?\n)|(\r)");
}
@Override
public void consume(CharSequence token, MarkdownOutput output) {
output.append(token);
}
}
}
| 3,313 | 29.40367 | 92 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlCodeChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Markdown treats double backtick quote (``) as indicators of code. Text wrapped with two `` will be wrapped with an HTML {@literal <code>} tag.
*
* E.g., the input ``printf()`` will produce {@literal<code>}printf(){@literal</code>}
*/
class HtmlCodeChannel extends RegexChannel<MarkdownOutput> {
public HtmlCodeChannel() {
super("``.+?``");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
output.append("<code>");
output.append(token.subSequence(2, token.length() - 2));
output.append("</code>");
}
}
| 1,483 | 34.333333 | 145 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlEmphasisChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Markdown treats asterisks (*) as indicators of emphasis. Text wrapped with one * will be wrapped with an HTML {@literal <em>} tag.
*
* E.g., the input *word* will produce {@literal <em>}work{@literal </em>}
*/
class HtmlEmphasisChannel extends RegexChannel<MarkdownOutput> {
HtmlEmphasisChannel() {
super("\\*[^\\s\\*]\\*|\\*[^\\s\\*][^\n\r]*?[^\\s\\*]\\*");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
output.append("<strong>");
output.append(token.subSequence(1, token.length() - 1));
output.append("</strong>");
}
}
| 1,506 | 34.880952 | 133 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlEndOfLineChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Markdown replace any line return by an HTML {@literal <br/>}
* tag.
*
*/
class HtmlEndOfLineChannel extends RegexChannel<MarkdownOutput> {
public HtmlEndOfLineChannel() {
super("(\r?\n)|(\r)");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
output.append("<br/>");
}
}
| 1,245 | 30.15 | 75 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlHeadingChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Headings are triggered by equal signs at the beginning of a line. The depth of the heading is determined by the number
* of equal signs (up to 6).
*
* E.g., the input:
* <pre>
* = Level 1
* == Level 2
* === Level 3
* ==== Level 4
* ===== Level 5
* ====== Level 6
* </pre>
* will produce:
* <pre>
* {@literal<h1>}Level 1{@literal</h1>}
* {@literal<h2>}Level 2{@literal</h2>}
* {@literal<h3>}Level 3{@literal</h3>}
* {@literal<h4>}Level 4{@literal</h4>}
* {@literal<h5>}Level 5{@literal</h5>}
* {@literal<h6>}Level 6{@literal</h6>}
* </pre>
* @since 4.4
*
*/
public class HtmlHeadingChannel extends RegexChannel<MarkdownOutput> {
private static final int MAX_HEADING_DEPTH = 6;
public HtmlHeadingChannel() {
super("\\s*=+\\s[^\r\n]*+[\r\n]*");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
int index = 0;
int headingLevel = 0;
while (index < token.length() && Character.isWhitespace(token.charAt(index))) {
index++;
}
while (index < token.length() && token.charAt(index) == '=') {
if (index < MAX_HEADING_DEPTH) {
headingLevel++;
}
index++;
}
while (index < token.length() && Character.isWhitespace(token.charAt(index))) {
index++;
}
CharSequence headingText = token.subSequence(index, token.length());
output.append("<h" + headingLevel + ">");
output.append(headingText.toString().trim());
output.append("</h" + headingLevel + ">");
}
}
| 2,418 | 29.2375 | 121 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlLinkChannel.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.markdown;
import org.sonar.channel.RegexChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Markdown interprets text in brackets followed by text in parentheses to generate documented links.
*
* E.g., the input [See documentation](http://docs.sonarqube.org/display/SONAR) will produce
* {@literal<a href="http://docs.sonarqube.org/display/SONAR">}See documentation{@literal</a>}
*/
class HtmlLinkChannel extends RegexChannel<MarkdownOutput> {
private static final String LINK_REGEX = "\\[([^\\]]+)\\]\\(([^\\)]+)\\)";
private static final Pattern LINK_PATTERN = Pattern.compile(LINK_REGEX);
public HtmlLinkChannel() {
super(LINK_REGEX);
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
Matcher matcher = LINK_PATTERN.matcher(token);
// Initialize match groups
matcher.matches();
String content = matcher.group(1);
String url = matcher.group(2);
boolean isRelativeUrl = !url.contains("://");
output.append("<a href=\"");
output.append(url);
output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">");
output.append(content);
output.append("</a>");
}
}
| 2,076 | 34.810345 | 101 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlListChannel.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.markdown;
import org.sonar.channel.Channel;
import org.sonar.channel.CodeReader;
import org.sonar.channel.RegexChannel;
/**
* Lists come in two flavors:
* <ul>
* <li>Unordered lists, triggered by lines that start with a <code>*</code></li>
* <li>Ordered lists (added in 4.4), triggered by lines that start with a digit followed by a <code>.</code></li>
* </ul>
* E.g., the input:
* <pre>
* * One
* * Two
* * Three
* </pre>
* will produce:
* {@literal<ul>}{@literal<li>}One{@literal</li>}
* {@literal<li>}Two{@literal</li>}
* {@literal<li>}Three{@literal</li>}{@literal</ul>}
*
* Whereas the input:
* <pre>
* 1. One
* 1. Two
* 1. Three
* </pre>
* will produce:
* {@literal<ol>}{@literal<li>}One{@literal</li>}
* {@literal<li>}Two{@literal</li>}
* {@literal<li>}Three{@literal</li>}{@literal</ol>}
*
* @since 2.10.1
*/
class HtmlListChannel extends Channel<MarkdownOutput> {
private OrderedListElementChannel orderedListElement = new OrderedListElementChannel();
private UnorderedListElementChannel unorderedListElement = new UnorderedListElementChannel();
private EndOfLine endOfLine = new EndOfLine();
private boolean pendingListConstruction;
@Override
public boolean consume(CodeReader code, MarkdownOutput output) {
try {
ListElementChannel currentChannel = null;
if (code.getColumnPosition() == 0) {
if (orderedListElement.consume(code, output)) {
currentChannel = orderedListElement;
} else if (unorderedListElement.consume(code, output)) {
currentChannel = unorderedListElement;
}
if (currentChannel != null) {
while (endOfLine.consume(code, output) && currentChannel.consume(code, output)) {
// consume input
}
output.append("</" + currentChannel.listElement + ">");
return true;
}
}
return false;
} finally {
pendingListConstruction = false;
}
}
private class OrderedListElementChannel extends ListElementChannel {
public OrderedListElementChannel() {
super("\\d\\.", "ol");
}
}
private class UnorderedListElementChannel extends ListElementChannel {
public UnorderedListElementChannel() {
super("\\*", "ul");
}
}
private abstract class ListElementChannel extends RegexChannel<MarkdownOutput> {
private String listElement;
protected ListElementChannel(String markerRegexp, String listElement) {
super("\\s*+" + markerRegexp + "\\s[^\r\n]*+");
this.listElement = listElement;
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
if (!pendingListConstruction) {
output.append("<" + listElement + ">");
pendingListConstruction = true;
}
output.append("<li>");
output.append(token.subSequence(searchIndexOfFirstCharacter(token), token.length()));
output.append("</li>");
}
private int searchIndexOfFirstCharacter(CharSequence token) {
for (int index = 0; index < token.length(); index++) {
if (token.charAt(index) == '*'
|| Character.isDigit(token.charAt(index))) {
if (token.charAt(index + 1) == '.') {
index ++;
}
while (++ index < token.length()) {
if (token.charAt(index) != ' ') {
return index;
}
}
}
}
return token.length() - 1;
}
}
private static final class EndOfLine extends RegexChannel<MarkdownOutput> {
public EndOfLine() {
super("(\r?\n)|(\r)");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
output.append(token);
}
}
}
| 4,571 | 29.48 | 114 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlMultilineCodeChannel.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.markdown;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.sonar.channel.RegexChannel;
/**
* Markdown treats double backtick quote (``) as indicators of code. Text wrapped with two `` and that spans on multiple lines will be wrapped with
* an HTML {@literal <pre><code>} tag.
*
* E.g., the input:
* <pre>
* ``
* This code
* spans on 2 lines
* ``
* </pre>
* will produce:
* {@literal<pre>}{@literal<code>}This code
* spans on 2 lines{@literal</code>}{@literal</pre>}
*
* @since 2.14
*/
class HtmlMultilineCodeChannel extends RegexChannel<MarkdownOutput> {
private static final String NEWLINE = "(?:\\n\\r|\\r|\\n)";
private static final String LANGUAGE = "([a-zA-Z][a-zA-Z0-9_]*+)?";
private static final String DETECTION_REGEXP = "``" + LANGUAGE + NEWLINE + "([\\s\\S]+?)" + NEWLINE + "``";
private final Matcher regexpMatcher;
public HtmlMultilineCodeChannel() {
super(DETECTION_REGEXP);
regexpMatcher = Pattern.compile(DETECTION_REGEXP).matcher("");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
regexpMatcher.reset(token);
regexpMatcher.matches();
output.append("<pre");
String language = regexpMatcher.group(1);
if (language != null) {
output.append(" lang=\"");
output.append(language);
output.append("\"");
}
output.append("><code>");
output.append(regexpMatcher.group(2));
output.append("</code></pre>");
}
}
| 2,343 | 31.109589 | 148 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/HtmlUrlChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Markdown will wrap any URL with an HTML {@literal <a href="URL">} tag.
*
*/
class HtmlUrlChannel extends RegexChannel<MarkdownOutput> {
public HtmlUrlChannel() {
super("https?://[\\w\\d:#@%/;$()~_?\\+-=\\.&]++");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
String url = token.toString();
boolean isRelativeUrl = !url.contains("://");
output.append("<a href=\"");
output.append(url);
output.append(isRelativeUrl ? "\">" : "\" target=\"_blank\" rel=\"noopener noreferrer\">");
output.append(url);
output.append("</a>");
}
}
| 1,524 | 32.888889 | 95 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/IdentifierAndNumberChannel.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.markdown;
import org.sonar.channel.RegexChannel;
/**
* Channel used only to improve performances of the Markdown engine by consuming any sequence of letter or digit.
*/
class IdentifierAndNumberChannel extends RegexChannel<MarkdownOutput> {
public IdentifierAndNumberChannel() {
super("[\\w\\d]++");
}
@Override
protected void consume(CharSequence token, MarkdownOutput output) {
output.append(token);
}
}
| 1,291 | 33 | 113 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/Markdown.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.markdown;
import org.apache.commons.lang.StringEscapeUtils;
import org.sonar.channel.ChannelDispatcher;
import org.sonar.channel.CodeReader;
/**
* Entry point of the Markdown library
*/
public final class Markdown {
private ChannelDispatcher<MarkdownOutput> dispatcher;
private Markdown() {
dispatcher = ChannelDispatcher.builder()
.addChannel(new HtmlLinkChannel())
.addChannel(new HtmlUrlChannel())
.addChannel(new HtmlEndOfLineChannel())
.addChannel(new HtmlEmphasisChannel())
.addChannel(new HtmlListChannel())
.addChannel(new HtmlBlockquoteChannel())
.addChannel(new HtmlHeadingChannel())
.addChannel(new HtmlCodeChannel())
.addChannel(new HtmlMultilineCodeChannel())
.addChannel(new IdentifierAndNumberChannel())
.addChannel(new BlackholeChannel())
.build();
}
private String convert(String input) {
CodeReader reader = new CodeReader(input);
MarkdownOutput output = new MarkdownOutput();
dispatcher.consume(reader, output);
return output.toString();
}
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml(input));
}
}
| 2,061 | 33.366667 | 75 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/MarkdownOutput.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.markdown;
class MarkdownOutput {
private StringBuilder ouput = new StringBuilder();
public Appendable append(CharSequence charSequence) {
return ouput.append(charSequence);
}
public Appendable append(char character) {
return ouput.append(character);
}
@Override
public String toString() {
return ouput.toString();
}
}
| 1,212 | 30.102564 | 75 | java |
sonarqube | sonarqube-master/sonar-markdown/src/main/java/org/sonar/markdown/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.
*/
/**
* Basic implementation of the Markdown markup language (see http://en.wikipedia.org/wiki/Markdown)
*
*/
package org.sonar.markdown;
| 984 | 36.884615 | 99 | java |
sonarqube | sonarqube-master/sonar-markdown/src/test/java/org/sonar/markdown/MarkdownTest.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.markdown;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MarkdownTest {
@Test
public void shouldDecorateAbsoluteUrl() {
assertThat(Markdown.convertToHtml("http://google.com"))
.isEqualTo("<a href=\"http://google.com\" target=\"_blank\" rel=\"noopener noreferrer\">http://google.com</a>");
}
@Test
public void shouldDecorateRelativeUrl() {
assertThat(Markdown.convertToHtml("[Google](/google/com)"))
.isEqualTo("<a href=\"/google/com\">Google</a>");
}
@Test
public void shouldDecorateDocumentedLink() {
assertThat(Markdown.convertToHtml("For more details, please [check online documentation](http://docs.sonarqube.org/display/SONAR)."))
.isEqualTo("For more details, please <a href=\"http://docs.sonarqube.org/display/SONAR\" target=\"_blank\" rel=\"noopener noreferrer\">check online documentation</a>.");
}
@Test
public void shouldDecorateEndOfLine() {
assertThat(Markdown.convertToHtml("1\r2\r\n3\n")).isEqualTo("1<br/>2<br/>3<br/>");
}
@Test
public void shouldDecorateUnorderedList() {
assertThat(Markdown.convertToHtml(" * one\r* two\r\n* three\n * \n *five"))
.isEqualTo("<ul><li>one</li>\r<li>two</li>\r\n<li>three</li>\n<li> </li>\n</ul> *five");
assertThat(Markdown.convertToHtml(" * one\r* two")).isEqualTo("<ul><li>one</li>\r<li>two</li></ul>");
assertThat(Markdown.convertToHtml("* \r*")).isEqualTo("<ul><li> </li>\r</ul>*");
}
@Test
public void shouldDecorateOrderedList() {
assertThat(Markdown.convertToHtml(" 1. one\r1. two\r\n1. three\n 1. \n 1.five"))
.isEqualTo("<ol><li>one</li>\r<li>two</li>\r\n<li>three</li>\n<li> </li>\n</ol> 1.five");
assertThat(Markdown.convertToHtml(" 1. one\r1. two")).isEqualTo("<ol><li>one</li>\r<li>two</li></ol>");
assertThat(Markdown.convertToHtml("1. \r1.")).isEqualTo("<ol><li> </li>\r</ol>1.");
}
@Test
public void shouldDecorateHeadings() {
assertThat(Markdown.convertToHtml(" = Top\r== Sub\r\n=== Sub sub\n ==== \n ===== five\n============ max"))
.isEqualTo("<h1>Top</h1><h2>Sub</h2><h3>Sub sub</h3><h4></h4><h5>five</h5><h6>max</h6>");
}
@Test
public void shouldDecorateBlockquote() {
assertThat(Markdown.convertToHtml("> Yesterday <br/> it worked\n> Today it is not working\r\n> Software is like that\r"))
.isEqualTo("<blockquote>Yesterday <br/> it worked<br/>\nToday it is not working<br/>\r\nSoftware is like that<br/>\r</blockquote>");
assertThat(Markdown.convertToHtml("HTML elements should <em>not</em> be quoted!"))
.isEqualTo("HTML elements should <em>not</em> be quoted!");
}
@Test
public void shouldDecorateMixedOrderedAndUnorderedList() {
assertThat(Markdown.convertToHtml(" 1. one\r* two\r\n1. three\n * \n 1.five"))
.isEqualTo("<ol><li>one</li>\r</ol><ul><li>two</li>\r\n</ul><ol><li>three</li>\n</ol><ul><li> </li>\n</ul> 1.five");
}
@Test
public void shouldDecorateCode() {
assertThat(Markdown.convertToHtml("This is a ``line of code``")).isEqualTo("This is a <code>line of code</code>");
assertThat(Markdown.convertToHtml("This is not a ``line of code")).isEqualTo("This is not a ``line of code");
}
@Test
public void shouldDecorateMultipleLineCode() {
assertThat(Markdown.convertToHtml("This is a ``\nline of code\nOn multiple lines\n``")).isEqualTo("This is a <pre><code>line of code\nOn multiple lines</code></pre>");
assertThat(Markdown.convertToHtml("This is not a ``line of code\nOn multiple lines``")).isEqualTo("This is not a ``line of code<br/>On multiple lines``");
assertThat(Markdown.convertToHtml("This is not a ``line of code\nOn multiple lines")).isEqualTo("This is not a ``line of code<br/>On multiple lines");
}
@Test
public void shouldDecorateMultipleLineCodeWithLanguageSpecified() {
assertThat(Markdown.convertToHtml("This is a ``java\nline of code\nOn multiple lines\n``")).isEqualTo("This is a <pre lang=\"java\"><code>line of code\nOn multiple lines</code></pre>");
assertThat(Markdown.convertToHtml("This is not a ``java line of code\nOn multiple lines``")).isEqualTo("This is not a ``java line of code<br/>On multiple lines``");
assertThat(Markdown.convertToHtml("This is not a ``java \nline of code\nOn multiple lines``")).isEqualTo("This is not a ``java <br/>line of code<br/>On multiple lines``");
}
@Test
public void shouldEmphasisText() {
assertThat(Markdown.convertToHtml("This is *Sparta !!!*")).isEqualTo("This is <strong>Sparta !!!</strong>");
assertThat(Markdown.convertToHtml("This is *A*")).isEqualTo("This is <strong>A</strong>");
assertThat(Markdown.convertToHtml("This should not be * \n emphasized")).isEqualTo("This should not be * <br/> emphasized");
assertThat(Markdown.convertToHtml("This is *very* very *important*")).isEqualTo("This is <strong>very</strong> very <strong>important</strong>");
assertThat(Markdown.convertToHtml("Not * emphasized * because of whitespaces")).isEqualTo("Not * emphasized * because of whitespaces");
assertThat(Markdown.convertToHtml("Not *emphasized * because of whitespace")).isEqualTo("Not *emphasized * because of whitespace");
assertThat(Markdown.convertToHtml("Not * emphasized* because of whitespace")).isEqualTo("Not * emphasized* because of whitespace");
assertThat(Markdown.convertToHtml("emphasized*inside*word")).isEqualTo("emphasized<strong>inside</strong>word");
assertThat(Markdown.convertToHtml("*Emphasize many words*")).isEqualTo("<strong>Emphasize many words</strong>");
}
@Test
public void shouldNotChangeAnythingInTheText() {
assertThat(Markdown.convertToHtml("My text is $123 ''")).isEqualTo("My text is $123 ''");
}
}
| 6,620 | 51.133858 | 189 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/AbstractProjectOrModule.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.batch.fs.internal;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Immutable
public abstract class AbstractProjectOrModule extends DefaultInputComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractProjectOrModule.class);
private final Path baseDir;
private final Path workDir;
private final String name;
private final String originalName;
private final String description;
private final Map<String, String> properties;
private final String key;
private final ProjectDefinition definition;
private final Charset encoding;
public AbstractProjectOrModule(ProjectDefinition definition, int scannerComponentId) {
super(scannerComponentId);
this.baseDir = initBaseDir(definition);
this.workDir = initWorkingDir(definition);
this.name = definition.getName();
this.originalName = definition.getOriginalName();
this.description = definition.getDescription();
this.properties = Collections.unmodifiableMap(new HashMap<>(definition.properties()));
this.definition = definition;
this.key = definition.getKey();
this.encoding = initEncoding(definition);
}
private static Charset initEncoding(ProjectDefinition module) {
String encodingStr = module.properties().get(CoreProperties.ENCODING_PROPERTY);
Charset result;
if (StringUtils.isNotEmpty(encodingStr)) {
result = Charset.forName(StringUtils.trim(encodingStr));
} else {
result = Charset.defaultCharset();
}
return result;
}
private static Path initBaseDir(ProjectDefinition module) {
Path result;
try {
result = module.getBaseDir().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
} catch (IOException e) {
throw new IllegalStateException("Unable to resolve module baseDir", e);
}
return result;
}
private static Path initWorkingDir(ProjectDefinition module) {
File workingDirAsFile = module.getWorkDir();
Path workingDir = workingDirAsFile.getAbsoluteFile().toPath().normalize();
if (SystemUtils.IS_OS_WINDOWS) {
try {
Files.createDirectories(workingDir);
Files.setAttribute(workingDir, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
} catch (IOException e) {
LOGGER.warn("Failed to set working directory hidden: {}", e.getMessage());
}
}
return workingDir;
}
@Override
public String key() {
return key;
}
@Override
public boolean isFile() {
return false;
}
public ProjectDefinition definition() {
return definition;
}
public Path getBaseDir() {
return baseDir;
}
public Path getWorkDir() {
return workDir;
}
public Map<String, String> properties() {
return properties;
}
@CheckForNull
public String getOriginalName() {
return originalName;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Charset getEncoding() {
return encoding;
}
}
| 4,359 | 28.863014 | 94 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultFileSystem.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.batch.fs.internal;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.StreamSupport;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.predicates.DefaultFilePredicates;
import org.sonar.api.batch.fs.internal.predicates.FileExtensionPredicate;
import org.sonar.api.batch.fs.internal.predicates.OptimizedFilePredicateAdapter;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.PathUtils;
import static java.util.Collections.emptySet;
/**
* @since 4.2
*/
public class DefaultFileSystem implements FileSystem {
private final Cache cache;
private final FilePredicates predicates;
private final Path baseDir;
private Path workDir;
private Charset encoding;
/**
* Only for testing
*/
public DefaultFileSystem(Path baseDir) {
this(baseDir, new MapCache(), new DefaultFilePredicates(baseDir));
}
/**
* Only for testing
*/
public DefaultFileSystem(File baseDir) {
this(baseDir.toPath(), new MapCache(), new DefaultFilePredicates(baseDir.toPath()));
}
protected DefaultFileSystem(Path baseDir, Cache cache, FilePredicates filePredicates) {
this.baseDir = baseDir;
this.cache = cache;
this.predicates = filePredicates;
}
public Path baseDirPath() {
return baseDir;
}
@Override
public File baseDir() {
return baseDir.toFile();
}
public DefaultFileSystem setEncoding(Charset e) {
this.encoding = e;
return this;
}
@Override
public Charset encoding() {
return encoding;
}
public DefaultFileSystem setWorkDir(Path d) {
this.workDir = d;
return this;
}
@Override
public File workDir() {
return workDir.toFile();
}
@Override
public InputFile inputFile(FilePredicate predicate) {
Iterable<InputFile> files = inputFiles(predicate);
Iterator<InputFile> iterator = files.iterator();
if (!iterator.hasNext()) {
return null;
}
InputFile first = iterator.next();
if (!iterator.hasNext()) {
return first;
}
StringBuilder sb = new StringBuilder();
sb.append("expected one element but was: <" + first);
for (int i = 0; i < 4 && iterator.hasNext(); i++) {
sb.append(", " + iterator.next());
}
if (iterator.hasNext()) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
public Iterable<InputFile> inputFiles() {
return inputFiles(predicates.all());
}
@Override
public Iterable<InputFile> inputFiles(FilePredicate predicate) {
return OptimizedFilePredicateAdapter.create(predicate).get(cache);
}
@Override
public boolean hasFiles(FilePredicate predicate) {
return inputFiles(predicate).iterator().hasNext();
}
@Override
public Iterable<File> files(FilePredicate predicate) {
return () -> StreamSupport.stream(inputFiles(predicate).spliterator(), false)
.map(InputFile::file)
.iterator();
}
@Override
public InputDir inputDir(File dir) {
String relativePath = PathUtils.sanitize(new PathResolver().relativePath(baseDir.toFile(), dir));
if (relativePath == null) {
return null;
}
// Issues on InputDir are moved to the project, so we just return a fake InputDir for backward compatibility
return new DefaultInputDir("unused", relativePath).setModuleBaseDir(baseDir);
}
public DefaultFileSystem add(InputFile inputFile) {
cache.add(inputFile);
return this;
}
@Override
public SortedSet<String> languages() {
return cache.languages();
}
@Override
public FilePredicates predicates() {
return predicates;
}
public abstract static class Cache implements Index {
protected abstract void doAdd(InputFile inputFile);
final void add(InputFile inputFile) {
doAdd(inputFile);
}
protected abstract SortedSet<String> languages();
}
/**
* Used only for testing
*/
private static class MapCache extends Cache {
private final Map<String, InputFile> fileMap = new HashMap<>();
private final Map<String, Set<InputFile>> filesByNameCache = new HashMap<>();
private final Map<String, Set<InputFile>> filesByExtensionCache = new HashMap<>();
private final SortedSet<String> languages = new TreeSet<>();
@Override
public Iterable<InputFile> inputFiles() {
return new ArrayList<>(fileMap.values());
}
@Override
public InputFile inputFile(String relativePath) {
return fileMap.get(relativePath);
}
@Override
public Iterable<InputFile> getFilesByName(String filename) {
return filesByNameCache.getOrDefault(filename, emptySet());
}
@Override
public Iterable<InputFile> getFilesByExtension(String extension) {
return filesByExtensionCache.getOrDefault(extension, emptySet());
}
@Override
protected void doAdd(InputFile inputFile) {
if (inputFile.language() != null) {
languages.add(inputFile.language());
}
fileMap.put(inputFile.relativePath(), inputFile);
filesByNameCache.computeIfAbsent(inputFile.filename(), x -> new HashSet<>()).add(inputFile);
filesByExtensionCache.computeIfAbsent(FileExtensionPredicate.getExtension(inputFile), x -> new HashSet<>()).add(inputFile);
}
@Override
protected SortedSet<String> languages() {
return languages;
}
}
@Override
public File resolvePath(String path) {
File file = new File(path);
if (!file.isAbsolute()) {
try {
file = new File(baseDir(), path).getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Unable to resolve path '" + path + "'", e);
}
}
return file;
}
}
| 7,016 | 27.180723 | 129 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultIndexedFile.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.batch.fs.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.IndexedFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.utils.PathUtils;
/**
* @since 6.3
*/
@Immutable
public class DefaultIndexedFile extends DefaultInputComponent implements IndexedFile {
// should match limit in org.sonar.core.component.ComponentKeys
private static final Integer MAX_KEY_LENGTH = 400;
private static final AtomicInteger intGenerator = new AtomicInteger(0);
private final String projectRelativePath;
private final String moduleRelativePath;
private final String projectKey;
private final String language;
private final Type type;
private final Path absolutePath;
private final SensorStrategy sensorStrategy;
private final String oldRelativeFilePath;
/**
* Testing purposes only!
*/
public DefaultIndexedFile(String projectKey, Path baseDir, String relativePath, @Nullable String language) {
this(baseDir.resolve(relativePath), projectKey, relativePath, relativePath, Type.MAIN, language, intGenerator.getAndIncrement(),
new SensorStrategy(), null);
}
public DefaultIndexedFile(Path absolutePath, String projectKey, String projectRelativePath, String moduleRelativePath, Type type, @Nullable String language, int batchId,
SensorStrategy sensorStrategy) {
this(absolutePath, projectKey, projectRelativePath, moduleRelativePath, type, language, batchId, sensorStrategy, null);
}
public DefaultIndexedFile(Path absolutePath, String projectKey, String projectRelativePath, String moduleRelativePath, Type type, @Nullable String language, int batchId,
SensorStrategy sensorStrategy, @Nullable String oldRelativeFilePath) {
super(batchId);
this.projectKey = projectKey;
this.projectRelativePath = checkSanitize(projectRelativePath);
this.moduleRelativePath = PathUtils.sanitize(moduleRelativePath);
this.type = type;
this.language = language;
this.sensorStrategy = sensorStrategy;
this.absolutePath = absolutePath;
this.oldRelativeFilePath = oldRelativeFilePath;
validateKeyLength();
}
static String checkSanitize(String relativePath) {
String sanitized = PathUtils.sanitize(relativePath);
if(sanitized == null) {
throw new IllegalArgumentException(String.format("The path '%s' must sanitize to a non-null value", relativePath));
}
return sanitized;
}
private void validateKeyLength() {
String key = key();
if (key.length() > MAX_KEY_LENGTH) {
throw new IllegalStateException(String.format("Component key (%s) length (%s) is longer than the maximum authorized (%s)", key, key.length(), MAX_KEY_LENGTH));
}
}
@Override
public String relativePath() {
return sensorStrategy.isGlobal() ? projectRelativePath : moduleRelativePath;
}
public String getModuleRelativePath() {
return moduleRelativePath;
}
public String getProjectRelativePath() {
return projectRelativePath;
}
@Override
public String absolutePath() {
return PathUtils.sanitize(path().toString());
}
@Override
public File file() {
return path().toFile();
}
@Override
public Path path() {
return absolutePath;
}
@CheckForNull
public String oldRelativePath() {
return oldRelativeFilePath;
}
@Override
public InputStream inputStream() throws IOException {
return Files.newInputStream(path());
}
@CheckForNull
@Override
public String language() {
return language;
}
@Override
public Type type() {
return type;
}
/**
* Component key (without branch).
*/
@Override
public String key() {
return String.join(":", projectKey, projectRelativePath);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || o.getClass() != this.getClass()) {
return false;
}
DefaultIndexedFile that = (DefaultIndexedFile) o;
return projectRelativePath.equals(that.projectRelativePath);
}
@Override
public int hashCode() {
return projectRelativePath.hashCode();
}
@Override
public String toString() {
return projectRelativePath;
}
@Override
public boolean isFile() {
return true;
}
@Override
public String filename() {
return path().getFileName().toString();
}
@Override
public URI uri() {
return path().toUri();
}
}
| 5,544 | 27.880208 | 171 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputComponent.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.batch.fs.internal;
import java.util.HashSet;
import java.util.Set;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.measure.Metric;
/**
* @since 5.2
*/
public abstract class DefaultInputComponent implements InputComponent {
private int id;
private Set<String> storedMetricKeys = new HashSet<>();
public DefaultInputComponent(int scannerId) {
this.id = scannerId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || this.getClass() != o.getClass()) {
return false;
}
DefaultInputComponent that = (DefaultInputComponent) o;
return key().equals(that.key());
}
public int scannerId() {
return id;
}
@Override
public int hashCode() {
return key().hashCode();
}
@Override
public String toString() {
return "[key=" + key() + "]";
}
public void setHasMeasureFor(Metric metric) {
storedMetricKeys.add(metric.key());
}
public boolean hasMeasureFor(Metric metric) {
return storedMetricKeys.contains(metric.key());
}
}
| 1,951 | 25.026667 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputDir.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.batch.fs.internal;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.utils.PathUtils;
/**
* @since 4.5
*/
public class DefaultInputDir extends DefaultInputComponent implements InputDir {
private final String relativePath;
private final String moduleKey;
private Path moduleBaseDir;
public DefaultInputDir(String moduleKey, String relativePath) {
super(-1);
this.moduleKey = moduleKey;
this.relativePath = PathUtils.sanitize(relativePath);
}
@Override
public String relativePath() {
return relativePath;
}
@Override
public String absolutePath() {
return PathUtils.sanitize(path().toString());
}
@Override
public File file() {
return path().toFile();
}
@Override
public Path path() {
if (moduleBaseDir == null) {
throw new IllegalStateException("Can not return the java.nio.file.Path because module baseDir is not set (see method setModuleBaseDir(java.io.File))");
}
return moduleBaseDir.resolve(relativePath);
}
public String moduleKey() {
return moduleKey;
}
@Override
public String key() {
StringBuilder sb = new StringBuilder().append(moduleKey).append(":");
if (StringUtils.isEmpty(relativePath)) {
sb.append("/");
} else {
sb.append(relativePath);
}
return sb.toString();
}
/**
* For testing purpose. Will be automatically set when dir is added to {@link DefaultFileSystem}
*/
public DefaultInputDir setModuleBaseDir(Path moduleBaseDir) {
this.moduleBaseDir = moduleBaseDir.normalize();
return this;
}
@Override
public boolean isFile() {
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || this.getClass() != o.getClass()) {
return false;
}
DefaultInputDir that = (DefaultInputDir) o;
return moduleKey.equals(that.moduleKey) && relativePath.equals(that.relativePath);
}
@Override
public int hashCode() {
return moduleKey.hashCode() + relativePath.hashCode() * 13;
}
@Override
public String toString() {
return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", basedir=" + moduleBaseDir + "]";
}
@Override
public URI uri() {
return path().toUri();
}
}
| 3,256 | 25.479675 | 157 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputFile.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.batch.fs.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.TextRange;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
/**
* @since 4.2
* To create {@link InputFile} in tests, use TestInputFileBuilder.
*/
public class DefaultInputFile extends DefaultInputComponent implements InputFile {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private final DefaultIndexedFile indexedFile;
private final String contents;
private final Consumer<DefaultInputFile> metadataGenerator;
private final Consumer<DefaultInputFile> scmStatusGenerator;
private boolean published;
private boolean excludedForCoverage;
private boolean excludedForDuplication;
private boolean ignoreAllIssues;
// Lazy init to save memory
private BitSet noSonarLines;
private Status status;
private Charset charset;
private Metadata metadata;
private Collection<int[]> ignoreIssuesOnlineRanges;
private BitSet executableLines;
private boolean markedAsUnchanged;
public DefaultInputFile(DefaultIndexedFile indexedFile, Consumer<DefaultInputFile> metadataGenerator, Consumer<DefaultInputFile> scmStatusGenerator) {
this(indexedFile, metadataGenerator, null, scmStatusGenerator);
}
// For testing
public DefaultInputFile(DefaultIndexedFile indexedFile, Consumer<DefaultInputFile> metadataGenerator, @Nullable String contents,
Consumer<DefaultInputFile> scmStatusGenerator) {
super(indexedFile.scannerId());
this.indexedFile = indexedFile;
this.metadataGenerator = metadataGenerator;
this.scmStatusGenerator = scmStatusGenerator;
this.metadata = null;
this.markedAsUnchanged = false;
this.published = false;
this.excludedForCoverage = false;
this.contents = contents;
}
public void checkMetadata() {
if (metadata == null) {
metadataGenerator.accept(this);
}
}
private void checkScmStatus() {
if(status == null) {
scmStatusGenerator.accept(this);
}
}
@Override
public InputStream inputStream() throws IOException {
return contents != null ? new ByteArrayInputStream(contents.getBytes(charset()))
: new BOMInputStream(Files.newInputStream(path()),
ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
}
public boolean isMarkedAsUnchanged() {
return markedAsUnchanged;
}
public DefaultInputComponent setMarkedAsUnchanged(boolean markedAsUnchanged) {
this.markedAsUnchanged = markedAsUnchanged;
return this;
}
@Override
public String contents() throws IOException {
if (contents != null) {
return contents;
} else {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (InputStream inputStream = inputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
}
return result.toString(charset().name());
}
}
public DefaultInputFile setPublished(boolean published) {
this.published = published;
return this;
}
public boolean isPublished() {
return published;
}
public DefaultInputFile setExcludedForCoverage(boolean excludedForCoverage) {
this.excludedForCoverage = excludedForCoverage;
return this;
}
public boolean isExcludedForCoverage() {
return excludedForCoverage;
}
public DefaultInputFile setExcludedForDuplication(boolean excludedForDuplication) {
this.excludedForDuplication = excludedForDuplication;
return this;
}
public boolean isExcludedForDuplication() {
return excludedForDuplication;
}
/**
* @deprecated since 6.6
*/
@Deprecated
@Override
public String relativePath() {
return indexedFile.relativePath();
}
public String getModuleRelativePath() {
return indexedFile.getModuleRelativePath();
}
public String getProjectRelativePath() {
return indexedFile.getProjectRelativePath();
}
@Override
public String absolutePath() {
return indexedFile.absolutePath();
}
@CheckForNull
public String oldRelativePath() {
return indexedFile.oldRelativePath();
}
@Override
public File file() {
return indexedFile.file();
}
@Override
public Path path() {
return indexedFile.path();
}
@CheckForNull
@Override
public String language() {
return indexedFile.language();
}
@Override
public Type type() {
return indexedFile.type();
}
/**
* Component key (without branch).
*/
@Override
public String key() {
return indexedFile.key();
}
@Override
public int hashCode() {
return indexedFile.hashCode();
}
@Override
public String toString() {
return indexedFile.toString();
}
/**
* {@link #setStatus(Status)}
*/
@Override
public Status status() {
checkScmStatus();
if(status == null) {
// scm might not be available, fallback to using hashes in the metadata
checkMetadata();
}
return status;
}
public boolean isStatusSet() {
return status != null;
}
@Override
public int lines() {
checkMetadata();
return metadata.lines();
}
@Override
public boolean isEmpty() {
checkMetadata();
return metadata.isEmpty();
}
@Override
public Charset charset() {
checkMetadata();
return charset;
}
public int lastValidOffset() {
checkMetadata();
return metadata.lastValidOffset();
}
/**
* Digest hash of the file.
*/
@Override
public String md5Hash() {
checkMetadata();
return metadata.hash();
}
public int nonBlankLines() {
checkMetadata();
return metadata.nonBlankLines();
}
public int[] originalLineStartOffsets() {
checkMetadata();
checkState(metadata.originalLineStartOffsets() != null, "InputFile is not properly initialized.");
checkState(metadata.originalLineStartOffsets().length == metadata.lines(),
"InputFile is not properly initialized. 'originalLineStartOffsets' property length should be equal to 'lines'");
return metadata.originalLineStartOffsets();
}
public int[] originalLineEndOffsets() {
checkMetadata();
checkState(metadata.originalLineEndOffsets() != null, "InputFile is not properly initialized.");
checkState(metadata.originalLineEndOffsets().length == metadata.lines(),
"InputFile is not properly initialized. 'originalLineEndOffsets' property length should be equal to 'lines'");
return metadata.originalLineEndOffsets();
}
@Override
public TextPointer newPointer(int line, int lineOffset) {
checkMetadata();
DefaultTextPointer textPointer = new DefaultTextPointer(line, lineOffset);
checkValid(textPointer, "pointer");
return textPointer;
}
@Override
public TextRange newRange(TextPointer start, TextPointer end) {
checkMetadata();
checkValid(start, "start pointer");
checkValid(end, "end pointer");
return newRangeValidPointers(start, end, false);
}
@Override
public TextRange newRange(int startLine, int startLineOffset, int endLine, int endLineOffset) {
checkMetadata();
TextPointer start = newPointer(startLine, startLineOffset);
TextPointer end = newPointer(endLine, endLineOffset);
return newRangeValidPointers(start, end, false);
}
@Override
public TextRange selectLine(int line) {
checkMetadata();
TextPointer startPointer = newPointer(line, 0);
TextPointer endPointer = newPointer(line, lineLength(line));
return newRangeValidPointers(startPointer, endPointer, true);
}
public void validate(TextRange range) {
checkMetadata();
checkValid(range.start(), "start pointer");
checkValid(range.end(), "end pointer");
}
/**
* Create Range from global offsets. Used for backward compatibility with older API.
*/
public TextRange newRange(int startOffset, int endOffset) {
checkMetadata();
return newRangeValidPointers(newPointer(startOffset), newPointer(endOffset), false);
}
public TextPointer newPointer(int globalOffset) {
checkMetadata();
checkArgument(globalOffset >= 0, "%s is not a valid offset for a file", globalOffset);
checkArgument(globalOffset <= lastValidOffset(), "%s is not a valid offset for file %s. Max offset is %s", globalOffset, this, lastValidOffset());
int line = findLine(globalOffset);
int startLineOffset = originalLineStartOffsets()[line - 1];
// In case the global offset is between \r and \n, move the pointer to a valid location
return new DefaultTextPointer(line, Math.min(globalOffset, originalLineEndOffsets()[line - 1]) - startLineOffset);
}
public DefaultInputFile setStatus(Status status) {
this.status = status;
return this;
}
public DefaultInputFile setCharset(Charset charset) {
this.charset = charset;
return this;
}
private void checkValid(TextPointer pointer, String owner) {
checkArgument(pointer.line() >= 1, "%s is not a valid line for a file", pointer.line());
checkArgument(pointer.line() <= this.metadata.lines(), "%s is not a valid line for %s. File %s has %s line(s)", pointer.line(), owner, this, metadata.lines());
checkArgument(pointer.lineOffset() >= 0, "%s is not a valid line offset for a file", pointer.lineOffset());
int lineLength = lineLength(pointer.line());
checkArgument(pointer.lineOffset() <= lineLength,
"%s is not a valid line offset for %s. File %s has %s character(s) at line %s", pointer.lineOffset(), owner, this, lineLength, pointer.line());
}
public int lineLength(int line) {
return originalLineEndOffsets()[line - 1] - originalLineStartOffsets()[line - 1];
}
private static TextRange newRangeValidPointers(TextPointer start, TextPointer end, boolean acceptEmptyRange) {
checkArgument(acceptEmptyRange ? (start.compareTo(end) <= 0) : (start.compareTo(end) < 0),
"Start pointer %s should be before end pointer %s", start, end);
return new DefaultTextRange(start, end);
}
private int findLine(int globalOffset) {
return Math.abs(Arrays.binarySearch(originalLineStartOffsets(), globalOffset) + 1);
}
public DefaultInputFile setMetadata(Metadata metadata) {
this.metadata = metadata;
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
DefaultInputFile that = (DefaultInputFile) obj;
return this.getProjectRelativePath().equals(that.getProjectRelativePath());
}
@Override
public boolean isFile() {
return true;
}
@Override
public String filename() {
return indexedFile.filename();
}
@Override
public URI uri() {
return indexedFile.uri();
}
public void noSonarAt(Set<Integer> noSonarLines) {
if (this.noSonarLines == null) {
this.noSonarLines = new BitSet(lines());
}
noSonarLines.forEach(l -> this.noSonarLines.set(l - 1));
}
public boolean hasNoSonarAt(int line) {
if (this.noSonarLines == null) {
return false;
}
return this.noSonarLines.get(line - 1);
}
public boolean isIgnoreAllIssues() {
checkMetadata();
return ignoreAllIssues;
}
public void setIgnoreAllIssues(boolean ignoreAllIssues) {
this.ignoreAllIssues = ignoreAllIssues;
}
public void addIgnoreIssuesOnLineRanges(Collection<int[]> lineRanges) {
if (this.ignoreIssuesOnlineRanges == null) {
this.ignoreIssuesOnlineRanges = new ArrayList<>();
}
this.ignoreIssuesOnlineRanges.addAll(lineRanges);
}
public boolean isIgnoreAllIssuesOnLine(@Nullable Integer line) {
checkMetadata();
if (line == null || ignoreIssuesOnlineRanges == null) {
return false;
}
return ignoreIssuesOnlineRanges.stream().anyMatch(r -> r[0] <= line && line <= r[1]);
}
public void setExecutableLines(Set<Integer> executableLines) {
checkState(this.executableLines == null, "Executable lines have already been saved for file: {}", this.toString());
this.executableLines = new BitSet(lines());
executableLines.forEach(l -> this.executableLines.set(l - 1));
}
public Optional<Set<Integer>> getExecutableLines() {
if (this.executableLines == null) {
return Optional.empty();
}
return Optional.of(this.executableLines.stream().map(i -> i + 1).boxed().collect(Collectors.toSet()));
}
}
| 14,083 | 28.526205 | 163 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputModule.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.batch.fs.internal;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.scan.filesystem.PathResolver;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;
@Immutable
public class DefaultInputModule extends AbstractProjectOrModule implements InputModule {
private final List<Path> sourceDirsOrFiles;
private final List<Path> testDirsOrFiles;
/**
* For testing only!
*/
public DefaultInputModule(ProjectDefinition definition) {
this(definition, 0);
}
public DefaultInputModule(ProjectDefinition definition, int scannerComponentId) {
super(definition, scannerComponentId);
this.sourceDirsOrFiles = initSources(definition, ProjectDefinition.SOURCES_PROPERTY);
this.testDirsOrFiles = initSources(definition, ProjectDefinition.TESTS_PROPERTY);
}
@CheckForNull
private List<Path> initSources(ProjectDefinition module, String propertyKey) {
if (!module.properties().containsKey(propertyKey)) {
return null;
}
List<Path> result = new ArrayList<>();
PathResolver pathResolver = new PathResolver();
String srcPropValue = module.properties().get(propertyKey);
if (srcPropValue != null) {
for (String sourcePath : parseAsCsv(propertyKey, srcPropValue)) {
File dirOrFile = pathResolver.relativeFile(getBaseDir().toFile(), sourcePath);
if (dirOrFile.exists()) {
result.add(dirOrFile.toPath());
}
}
}
return result;
}
public Optional<List<Path>> getSourceDirsOrFiles() {
return Optional.ofNullable(sourceDirsOrFiles);
}
public Optional<List<Path>> getTestDirsOrFiles() {
return Optional.ofNullable(testDirsOrFiles);
}
}
| 2,820 | 33.402439 | 89 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputProject.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.batch.fs.internal;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.scanner.fs.InputProject;
@Immutable
public class DefaultInputProject extends AbstractProjectOrModule implements InputProject {
/**
* For testing only!
*/
public DefaultInputProject(ProjectDefinition definition) {
super(definition, 0);
}
public DefaultInputProject(ProjectDefinition definition, int scannerComponentId) {
super(definition, scannerComponentId);
}
}
| 1,398 | 33.975 | 90 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultTextPointer.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.batch.fs.internal;
import org.sonar.api.batch.fs.TextPointer;
/**
* @since 5.2
*/
public class DefaultTextPointer implements TextPointer {
private final int line;
private final int lineOffset;
public DefaultTextPointer(int line, int lineOffset) {
this.line = line;
this.lineOffset = lineOffset;
}
@Override
public int line() {
return line;
}
@Override
public int lineOffset() {
return lineOffset;
}
@Override
public String toString() {
return "[line=" + line + ", lineOffset=" + lineOffset + "]";
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
DefaultTextPointer other = (DefaultTextPointer) obj;
return other.line == this.line && other.lineOffset == this.lineOffset;
}
@Override
public int hashCode() {
return 37 * this.line + lineOffset;
}
@Override
public int compareTo(TextPointer o) {
if (this.line == o.line()) {
return Integer.compare(this.lineOffset, o.lineOffset());
}
return Integer.compare(this.line, o.line());
}
}
| 1,986 | 25.493333 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/DefaultTextRange.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.batch.fs.internal;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.TextRange;
/**
* @since 5.2
*/
public class DefaultTextRange implements TextRange {
private final TextPointer start;
private final TextPointer end;
public DefaultTextRange(TextPointer start, TextPointer end) {
this.start = start;
this.end = end;
}
@Override
public TextPointer start() {
return start;
}
@Override
public TextPointer end() {
return end;
}
@Override
public boolean overlap(TextRange another) {
// [A,B] and [C,D]
// B > C && D > A
return this.end.compareTo(another.start()) > 0 && another.end().compareTo(this.start) > 0;
}
@Override
public String toString() {
return "Range[from " + start + " to " + end + "]";
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
DefaultTextRange other = (DefaultTextRange) obj;
return start.equals(other.start) && end.equals(other.end);
}
@Override
public int hashCode() {
return start.hashCode() * 17 + end.hashCode();
}
}
| 2,013 | 25.853333 | 94 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/FileMetadata.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.batch.fs.internal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.charhandler.CharHandler;
import org.sonar.api.batch.fs.internal.charhandler.FileHashComputer;
import org.sonar.api.batch.fs.internal.charhandler.LineCounter;
import org.sonar.api.batch.fs.internal.charhandler.LineHashComputer;
import org.sonar.api.batch.fs.internal.charhandler.LineOffsetCounter;
import org.sonar.api.notifications.AnalysisWarnings;
/**
* Computes hash of files. Ends of Lines are ignored, so files with
* same content but different EOL encoding have the same hash.
*/
@Immutable
public class FileMetadata {
private static final char LINE_FEED = '\n';
private static final char CARRIAGE_RETURN = '\r';
private final AnalysisWarnings analysisWarnings;
public FileMetadata(AnalysisWarnings analysisWarnings) {
this.analysisWarnings = analysisWarnings;
}
/**
* Compute hash of a file ignoring line ends differences.
* Maximum performance is needed.
*/
public Metadata readMetadata(InputStream stream, Charset encoding, String filePath, @Nullable CharHandler otherHandler) {
LineCounter lineCounter = new LineCounter(analysisWarnings, filePath, encoding);
FileHashComputer fileHashComputer = new FileHashComputer(filePath);
LineOffsetCounter lineOffsetCounter = new LineOffsetCounter();
if (otherHandler != null) {
CharHandler[] handlers = {lineCounter, fileHashComputer, lineOffsetCounter, otherHandler};
readFile(stream, encoding, filePath, handlers);
} else {
CharHandler[] handlers = {lineCounter, fileHashComputer, lineOffsetCounter};
readFile(stream, encoding, filePath, handlers);
}
return new Metadata(lineCounter.lines(), lineCounter.nonBlankLines(), fileHashComputer.getHash(), lineOffsetCounter.getOriginalLineStartOffsets(),
lineOffsetCounter.getOriginalLineEndOffsets(),
lineOffsetCounter.getLastValidOffset());
}
public Metadata readMetadata(InputStream stream, Charset encoding, String filePath) {
return readMetadata(stream, encoding, filePath, null);
}
/**
* For testing purpose
*/
public Metadata readMetadata(Reader reader) {
LineCounter lineCounter = new LineCounter(analysisWarnings, "fromString", StandardCharsets.UTF_16);
FileHashComputer fileHashComputer = new FileHashComputer("fromString");
LineOffsetCounter lineOffsetCounter = new LineOffsetCounter();
CharHandler[] handlers = {lineCounter, fileHashComputer, lineOffsetCounter};
try {
read(reader, handlers);
} catch (IOException e) {
throw new IllegalStateException("Should never occur", e);
}
return new Metadata(lineCounter.lines(), lineCounter.nonBlankLines(), fileHashComputer.getHash(), lineOffsetCounter.getOriginalLineStartOffsets(),
lineOffsetCounter.getOriginalLineEndOffsets(),
lineOffsetCounter.getLastValidOffset());
}
public static void readFile(InputStream stream, Charset encoding, String filePath, CharHandler[] handlers) {
try (Reader reader = new BufferedReader(new InputStreamReader(stream, encoding))) {
read(reader, handlers);
} catch (IOException e) {
throw new IllegalStateException(String.format("Fail to read file '%s' with encoding '%s'", filePath, encoding), e);
}
}
private static void read(Reader reader, CharHandler[] handlers) throws IOException {
char c;
int i = reader.read();
boolean afterCR = false;
while (i != -1) {
c = (char) i;
if (afterCR) {
for (CharHandler handler : handlers) {
if (c == CARRIAGE_RETURN) {
handler.newLine();
handler.handleAll(c);
} else if (c == LINE_FEED) {
handler.handleAll(c);
handler.newLine();
} else {
handler.newLine();
handler.handleIgnoreEoL(c);
handler.handleAll(c);
}
}
afterCR = c == CARRIAGE_RETURN;
} else if (c == LINE_FEED) {
for (CharHandler handler : handlers) {
handler.handleAll(c);
handler.newLine();
}
} else if (c == CARRIAGE_RETURN) {
afterCR = true;
for (CharHandler handler : handlers) {
handler.handleAll(c);
}
} else {
for (CharHandler handler : handlers) {
handler.handleIgnoreEoL(c);
handler.handleAll(c);
}
}
i = reader.read();
}
for (CharHandler handler : handlers) {
if (afterCR) {
handler.newLine();
}
handler.eof();
}
}
@FunctionalInterface
public interface LineHashConsumer {
void consume(int lineIdx, @Nullable byte[] hash);
}
/**
* Compute a MD5 hash of each line of the file after removing of all blank chars
*/
public static void computeLineHashesForIssueTracking(InputFile f, LineHashConsumer consumer) {
try {
readFile(f.inputStream(), f.charset(), f.absolutePath(), new CharHandler[] {new LineHashComputer(consumer, f.file())});
} catch (IOException e) {
throw new IllegalStateException("Failed to compute line hashes for " + f.absolutePath(), e);
}
}
}
| 6,325 | 36.654762 | 150 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/Metadata.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.batch.fs.internal;
import java.util.Arrays;
import javax.annotation.concurrent.Immutable;
@Immutable
public class Metadata {
private final int lines;
private final int nonBlankLines;
private final String hash;
private final int[] originalLineStartOffsets;
private final int[] originalLineEndOffsets;
private final int lastValidOffset;
public Metadata(int lines, int nonBlankLines, String hash, int[] originalLineStartOffsets, int[] originalLineEndOffsets, int lastValidOffset) {
this.lines = lines;
this.nonBlankLines = nonBlankLines;
this.hash = hash;
this.originalLineStartOffsets = Arrays.copyOf(originalLineStartOffsets, originalLineStartOffsets.length);
this.originalLineEndOffsets = Arrays.copyOf(originalLineEndOffsets, originalLineEndOffsets.length);
this.lastValidOffset = lastValidOffset;
}
public int lines() {
return lines;
}
public int nonBlankLines() {
return nonBlankLines;
}
public String hash() {
return hash;
}
public int[] originalLineStartOffsets() {
return originalLineStartOffsets;
}
public int[] originalLineEndOffsets() {
return originalLineEndOffsets;
}
public int lastValidOffset() {
return lastValidOffset;
}
public boolean isEmpty() {
return lastValidOffset == 0;
}
}
| 2,168 | 29.125 | 145 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/PathPattern.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.batch.fs.internal;
import java.nio.file.Path;
import java.util.Arrays;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.PathUtils;
import org.sonar.api.utils.WildcardPattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ThreadSafe
public abstract class PathPattern {
private static final Logger LOG = LoggerFactory.getLogger(PathPattern.class);
/**
* @deprecated since 6.6
*/
@Deprecated
private static final String ABSOLUTE_PATH_PATTERN_PREFIX = "file:";
final WildcardPattern pattern;
PathPattern(String pattern) {
this.pattern = WildcardPattern.create(pattern);
}
public abstract boolean match(Path absolutePath, Path relativePath);
public abstract boolean match(Path absolutePath, Path relativePath, boolean caseSensitiveFileExtension);
public static PathPattern create(String s) {
String trimmed = StringUtils.trim(s);
if (StringUtils.startsWithIgnoreCase(trimmed, ABSOLUTE_PATH_PATTERN_PREFIX)) {
LOG.warn("Using absolute path pattern is deprecated. Please use relative path instead of '" + trimmed + "'");
return new AbsolutePathPattern(StringUtils.substring(trimmed, ABSOLUTE_PATH_PATTERN_PREFIX.length()));
}
return new RelativePathPattern(trimmed);
}
public static PathPattern[] create(String[] s) {
return Arrays.stream(s).map(PathPattern::create).toArray(PathPattern[]::new);
}
/**
* @deprecated since 6.6
*/
@Deprecated
private static class AbsolutePathPattern extends PathPattern {
private AbsolutePathPattern(String pattern) {
super(pattern);
}
@Override
public boolean match(Path absolutePath, Path relativePath) {
return match(absolutePath, relativePath, true);
}
@Override
public boolean match(Path absolutePath, Path relativePath, boolean caseSensitiveFileExtension) {
String path = PathUtils.sanitize(absolutePath.toString());
if (!caseSensitiveFileExtension) {
String extension = sanitizeExtension(FilenameUtils.getExtension(path));
if (StringUtils.isNotBlank(extension)) {
path = StringUtils.removeEndIgnoreCase(path, extension);
path = path + extension;
}
}
return pattern.match(path);
}
@Override
public String toString() {
return ABSOLUTE_PATH_PATTERN_PREFIX + pattern.toString();
}
}
/**
* Path relative to module basedir
*/
private static class RelativePathPattern extends PathPattern {
private RelativePathPattern(String pattern) {
super(pattern);
}
@Override
public boolean match(Path absolutePath, Path relativePath) {
return match(absolutePath, relativePath, true);
}
@Override
public boolean match(Path absolutePath, Path relativePath, boolean caseSensitiveFileExtension) {
String path = PathUtils.sanitize(relativePath.toString());
if (!caseSensitiveFileExtension) {
String extension = sanitizeExtension(FilenameUtils.getExtension(path));
if (StringUtils.isNotBlank(extension)) {
path = StringUtils.removeEndIgnoreCase(path, extension);
path = path + extension;
}
}
return path != null && pattern.match(path);
}
@Override
public String toString() {
return pattern.toString();
}
}
static String sanitizeExtension(String suffix) {
return StringUtils.lowerCase(StringUtils.removeStart(suffix, "."));
}
}
| 4,405 | 31.880597 | 115 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/SensorStrategy.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.batch.fs.internal;
import org.sonar.api.batch.fs.InputFile;
/**
* A shared, mutable object in the project container.
* It's used during the execution of sensors to decide whether
* sensors should be executed once for the entire project, or per-module.
* It is also injected into each InputFile to change the behavior of {@link InputFile#relativePath()}
*/
public class SensorStrategy {
private boolean global = true;
public boolean isGlobal() {
return global;
}
public void setGlobal(boolean global) {
this.global = global;
}
}
| 1,421 | 32.857143 | 101 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/TestInputFileBuilder.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.batch.fs.internal;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.PathUtils;
/**
* Intended to be used in unit tests that need to create {@link InputFile}s.
* An InputFile is unambiguously identified by a <b>module key</b> and a <b>relative path</b>, so these parameters are mandatory.
* <p>
* A module base directory is only needed to construct absolute paths.
* <p>
* Examples of usage of the constructors:
*
* <pre>
* InputFile file1 = TestInputFileBuilder.create("module1", "myfile.java").build();
* InputFile file2 = TestInputFileBuilder.create("", fs.baseDir(), myfile).build();
* </pre>
* <p>
* file1 will have the "module1" as both module key and module base directory.
* file2 has an empty string as module key, and a relative path which is the path from the filesystem base directory to myfile.
*
* @since 6.3
*/
public class TestInputFileBuilder {
private static int batchId = 1;
private final int id;
private final String relativePath;
private String oldRelativePath;
private final String projectKey;
@CheckForNull
private Path projectBaseDir;
private Path moduleBaseDir;
private String language;
private InputFile.Type type = InputFile.Type.MAIN;
private InputFile.Status status;
private int lines = -1;
private Charset charset;
private String hash;
private int nonBlankLines;
private int[] originalLineStartOffsets = new int[0];
private int[] originalLineEndOffsets = new int[0];
private int lastValidOffset = -1;
private boolean publish = true;
private String contents;
/**
* Create a InputFile identified by the given project key and relative path.
*/
public TestInputFileBuilder(String projectKey, String relativePath) {
this(projectKey, relativePath, batchId++);
}
/**
* Create a InputFile with a given module key and module base directory.
* The relative path is generated comparing the file path to the module base directory.
* filePath must point to a file that is within the module base directory.
*/
public TestInputFileBuilder(String projectKey, File moduleBaseDir, File filePath) {
String relativePathStr = moduleBaseDir.toPath().relativize(filePath.toPath()).toString();
this.projectKey = projectKey;
setModuleBaseDir(moduleBaseDir.toPath());
this.relativePath = PathUtils.sanitize(relativePathStr);
this.id = batchId++;
}
public TestInputFileBuilder(String projectKey, String relativePath, int id) {
this.projectKey = projectKey;
setModuleBaseDir(Paths.get(projectKey));
this.relativePath = PathUtils.sanitize(relativePath);
this.id = id;
}
public TestInputFileBuilder(String projectKey, String relativePath, String oldRelativePath, int id) {
this.projectKey = projectKey;
setModuleBaseDir(Paths.get(projectKey));
this.relativePath = PathUtils.sanitize(relativePath);
this.oldRelativePath = oldRelativePath;
this.id = id;
}
public static TestInputFileBuilder create(String moduleKey, File moduleBaseDir, File filePath) {
return new TestInputFileBuilder(moduleKey, moduleBaseDir, filePath);
}
public static TestInputFileBuilder create(String moduleKey, String relativePath) {
return new TestInputFileBuilder(moduleKey, relativePath);
}
public static int nextBatchId() {
return batchId++;
}
public TestInputFileBuilder setProjectBaseDir(Path projectBaseDir) {
this.projectBaseDir = normalize(projectBaseDir);
return this;
}
public TestInputFileBuilder setModuleBaseDir(Path moduleBaseDir) {
this.moduleBaseDir = normalize(moduleBaseDir);
return this;
}
private static Path normalize(Path path) {
try {
return path.normalize().toRealPath(LinkOption.NOFOLLOW_LINKS);
} catch (IOException e) {
return path.normalize();
}
}
public TestInputFileBuilder setLanguage(@Nullable String language) {
this.language = language;
return this;
}
public TestInputFileBuilder setType(InputFile.Type type) {
this.type = type;
return this;
}
public TestInputFileBuilder setStatus(InputFile.Status status) {
this.status = status;
return this;
}
public TestInputFileBuilder setLines(int lines) {
this.lines = lines;
return this;
}
public TestInputFileBuilder setCharset(Charset charset) {
this.charset = charset;
return this;
}
public TestInputFileBuilder setHash(String hash) {
this.hash = hash;
return this;
}
/**
* Set contents of the file and calculates metadata from it.
* The contents will be returned by {@link InputFile#contents()} and {@link InputFile#inputStream()} and can be
* inconsistent with the actual physical file pointed by {@link InputFile#path()}, {@link InputFile#absolutePath()}, etc.
*/
public TestInputFileBuilder setContents(String content) {
this.contents = content;
initMetadata(content);
return this;
}
public TestInputFileBuilder setNonBlankLines(int nonBlankLines) {
this.nonBlankLines = nonBlankLines;
return this;
}
public TestInputFileBuilder setLastValidOffset(int lastValidOffset) {
this.lastValidOffset = lastValidOffset;
return this;
}
public TestInputFileBuilder setOriginalLineStartOffsets(int[] originalLineStartOffsets) {
this.originalLineStartOffsets = originalLineStartOffsets;
return this;
}
public TestInputFileBuilder setOriginalLineEndOffsets(int[] originalLineEndOffsets) {
this.originalLineEndOffsets = originalLineEndOffsets;
return this;
}
public TestInputFileBuilder setPublish(boolean publish) {
this.publish = publish;
return this;
}
public TestInputFileBuilder setMetadata(Metadata metadata) {
this.setLines(metadata.lines());
this.setLastValidOffset(metadata.lastValidOffset());
this.setNonBlankLines(metadata.nonBlankLines());
this.setHash(metadata.hash());
this.setOriginalLineStartOffsets(metadata.originalLineStartOffsets());
this.setOriginalLineEndOffsets(metadata.originalLineEndOffsets());
return this;
}
public TestInputFileBuilder initMetadata(String content) {
AnalysisWarnings analysisWarnings = warning -> {};
return setMetadata(new FileMetadata(analysisWarnings).readMetadata(new StringReader(content)));
}
public DefaultInputFile build() {
Path absolutePath = moduleBaseDir.resolve(relativePath);
if (projectBaseDir == null) {
projectBaseDir = moduleBaseDir;
}
String projectRelativePath = projectBaseDir.relativize(absolutePath).toString();
DefaultIndexedFile indexedFile = new DefaultIndexedFile(absolutePath, projectKey, projectRelativePath, relativePath, type, language, id, new SensorStrategy(), oldRelativePath);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile,
f -> f.setMetadata(new Metadata(lines, nonBlankLines, hash, originalLineStartOffsets, originalLineEndOffsets, lastValidOffset)),
contents, f -> {});
inputFile.setStatus(status);
inputFile.setCharset(charset);
inputFile.setPublished(publish);
return inputFile;
}
public static DefaultInputModule newDefaultInputModule(String moduleKey, File baseDir) {
ProjectDefinition definition = ProjectDefinition.create()
.setKey(moduleKey)
.setBaseDir(baseDir)
.setWorkDir(new File(baseDir, ".sonar"));
return newDefaultInputModule(definition);
}
public static DefaultInputModule newDefaultInputModule(ProjectDefinition projectDefinition) {
return new DefaultInputModule(projectDefinition, TestInputFileBuilder.nextBatchId());
}
public static DefaultInputModule newDefaultInputModule(AbstractProjectOrModule parent, String key) throws IOException {
Path basedir = parent.getBaseDir().resolve(key);
Files.createDirectory(basedir);
return newDefaultInputModule(key, basedir.toFile());
}
public static DefaultInputProject newDefaultInputProject(String projectKey, File baseDir) {
ProjectDefinition definition = ProjectDefinition.create()
.setKey(projectKey)
.setBaseDir(baseDir)
.setWorkDir(new File(baseDir, ".sonar"));
return newDefaultInputProject(definition);
}
public static DefaultInputProject newDefaultInputProject(ProjectDefinition projectDefinition) {
return new DefaultInputProject(projectDefinition, TestInputFileBuilder.nextBatchId());
}
public static DefaultInputProject newDefaultInputProject(String key, Path baseDir) throws IOException {
Files.createDirectory(baseDir);
return newDefaultInputProject(key, baseDir.toFile());
}
public static DefaultInputDir newDefaultInputDir(AbstractProjectOrModule module, String relativePath) throws IOException {
Path basedir = module.getBaseDir().resolve(relativePath);
Files.createDirectory(basedir);
return new DefaultInputDir(module.key(), relativePath)
.setModuleBaseDir(module.getBaseDir());
}
public static DefaultInputFile newDefaultInputFile(Path projectBaseDir, AbstractProjectOrModule module, String relativePath) {
return new TestInputFileBuilder(module.key(), relativePath)
.setStatus(InputFile.Status.SAME)
.setProjectBaseDir(projectBaseDir)
.setModuleBaseDir(module.getBaseDir())
.build();
}
}
| 10,490 | 35.175862 | 180 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/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.api.batch.fs.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 972 | 37.92 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/CharHandler.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.batch.fs.internal.charhandler;
public abstract class CharHandler {
public void handleAll(char c) {
}
public void handleIgnoreEoL(char c) {
}
public void newLine() {
}
public void eof() {
}
}
| 1,077 | 28.944444 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/FileHashComputer.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.batch.fs.internal.charhandler;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
public class FileHashComputer extends CharHandler {
private static final char LINE_FEED = '\n';
private MessageDigest globalMd5Digest = DigestUtils.getMd5Digest();
private StringBuilder sb = new StringBuilder();
private final CharsetEncoder encoder;
private final String filePath;
public FileHashComputer(String filePath) {
encoder = StandardCharsets.UTF_8.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
this.filePath = filePath;
}
@Override
public void handleIgnoreEoL(char c) {
sb.append(c);
}
@Override
public void newLine() {
sb.append(LINE_FEED);
processBuffer();
sb.setLength(0);
}
@Override
public void eof() {
if (sb.length() > 0) {
processBuffer();
}
}
private void processBuffer() {
try {
if (sb.length() > 0) {
ByteBuffer encoded = encoder.encode(CharBuffer.wrap(sb));
globalMd5Digest.update(encoded.array(), 0, encoded.limit());
}
} catch (CharacterCodingException e) {
throw new IllegalStateException("Error encoding line hash in file: " + filePath, e);
}
}
public String getHash() {
return Hex.encodeHexString(globalMd5Digest.digest());
}
}
| 2,528 | 29.841463 | 90 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/IntArrayList.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.batch.fs.internal.charhandler;
import java.util.Arrays;
import java.util.Collection;
/**
* Specialization of {@link java.util.ArrayList} to create a list of int (only append elements) and then produce an int[].
*/
class IntArrayList {
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final int[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the IntArrayList is the length of this array buffer. Any
* empty IntArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
private int[] elementData;
/**
* The size of the IntArrayList (the number of elements it contains).
*/
private int size;
/**
* Constructs an empty list with an initial capacity of ten.
*/
public IntArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Trims the capacity of this <tt>IntArrayList</tt> instance to be the
* list's current size and return the internal array. An application can use this operation to minimize
* the storage of an <tt>IntArrayList</tt> instance.
*/
public int[] trimAndGet() {
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
}
return elementData;
}
private void ensureCapacityInternal(int minCapacity) {
int capacity = minCapacity;
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
capacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(capacity);
}
private void ensureExplicitCapacity(int minCapacity) {
if (minCapacity - elementData.length > 0) {
grow(minCapacity);
}
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(int e) {
ensureCapacityInternal(size + 1);
elementData[size] = e;
size++;
return true;
}
}
| 3,694 | 30.313559 | 122 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/LineCounter.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.batch.fs.internal.charhandler;
import java.nio.charset.Charset;
import org.sonar.api.CoreProperties;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LineCounter extends CharHandler {
private static final Logger LOG = LoggerFactory.getLogger(LineCounter.class);
private final AnalysisWarnings analysisWarnings;
private final String filePath;
private final Charset encoding;
private int lines = 1;
private int nonBlankLines = 0;
private boolean blankLine = true;
boolean alreadyLoggedInvalidCharacter = false;
public LineCounter(AnalysisWarnings analysisWarnings, String filePath, Charset encoding) {
this.analysisWarnings = analysisWarnings;
this.filePath = filePath;
this.encoding = encoding;
}
@Override
public void handleAll(char c) {
if (!alreadyLoggedInvalidCharacter && c == '\ufffd') {
analysisWarnings.addUnique("There are problems with file encoding in the source code. Please check the scanner logs for more details.");
LOG.warn("Invalid character encountered in file {} at line {} for encoding {}. Please fix file content or configure the encoding to be used using property '{}'.", filePath,
lines, encoding, CoreProperties.ENCODING_PROPERTY);
alreadyLoggedInvalidCharacter = true;
}
}
@Override
public void newLine() {
lines++;
if (!blankLine) {
nonBlankLines++;
}
blankLine = true;
}
@Override
public void handleIgnoreEoL(char c) {
if (!Character.isWhitespace(c)) {
blankLine = false;
}
}
@Override
public void eof() {
if (!blankLine) {
nonBlankLines++;
}
}
public int lines() {
return lines;
}
public int nonBlankLines() {
return nonBlankLines;
}
}
| 2,670 | 29.352273 | 178 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/LineHashComputer.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.batch.fs.internal.charhandler;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import org.apache.commons.codec.digest.DigestUtils;
import org.sonar.api.batch.fs.internal.FileMetadata;
public class LineHashComputer extends CharHandler {
private final MessageDigest lineMd5Digest = DigestUtils.getMd5Digest();
private final CharsetEncoder encoder;
private final StringBuilder sb = new StringBuilder();
private final FileMetadata.LineHashConsumer consumer;
private final File file;
private int line = 1;
public LineHashComputer(FileMetadata.LineHashConsumer consumer, File f) {
this.consumer = consumer;
this.file = f;
this.encoder = StandardCharsets.UTF_8.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
@Override
public void handleIgnoreEoL(char c) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
@Override
public void newLine() {
processBuffer();
sb.setLength(0);
line++;
}
@Override
public void eof() {
if (this.line > 0) {
processBuffer();
}
}
private void processBuffer() {
try {
if (sb.length() > 0) {
ByteBuffer encoded = encoder.encode(CharBuffer.wrap(sb));
lineMd5Digest.update(encoded.array(), 0, encoded.limit());
consumer.consume(line, lineMd5Digest.digest());
}
} catch (CharacterCodingException e) {
throw new IllegalStateException("Error encoding line hash in file: " + file.getAbsolutePath(), e);
}
}
}
| 2,654 | 31.378049 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/LineOffsetCounter.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.batch.fs.internal.charhandler;
public class LineOffsetCounter extends CharHandler {
private long currentOriginalLineStartOffset = 0;
private long currentOriginalLineEndOffset = 0;
private final IntArrayList originalLineStartOffsets = new IntArrayList();
private final IntArrayList originalLineEndOffsets = new IntArrayList();
private long lastValidOffset = 0;
public LineOffsetCounter() {
originalLineStartOffsets.add(0);
}
@Override
public void handleAll(char c) {
currentOriginalLineStartOffset++;
}
@Override
public void handleIgnoreEoL(char c) {
currentOriginalLineEndOffset++;
}
@Override
public void newLine() {
if (currentOriginalLineStartOffset > Integer.MAX_VALUE) {
throw new IllegalStateException("File is too big: " + currentOriginalLineStartOffset);
}
originalLineStartOffsets.add((int) currentOriginalLineStartOffset);
originalLineEndOffsets.add((int) currentOriginalLineEndOffset);
currentOriginalLineEndOffset = currentOriginalLineStartOffset;
}
@Override
public void eof() {
originalLineEndOffsets.add((int) currentOriginalLineEndOffset);
lastValidOffset = currentOriginalLineStartOffset;
}
public int[] getOriginalLineStartOffsets() {
return originalLineStartOffsets.trimAndGet();
}
public int[] getOriginalLineEndOffsets() {
return originalLineEndOffsets.trimAndGet();
}
public int getLastValidOffset() {
if (lastValidOffset > Integer.MAX_VALUE) {
throw new IllegalStateException("File is too big: " + lastValidOffset);
}
return (int) lastValidOffset;
}
}
| 2,472 | 31.973333 | 92 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/charhandler/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.api.batch.fs.internal.charhandler;
import javax.annotation.ParametersAreNonnullByDefault;
| 984 | 38.4 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/AbsolutePathPredicate.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.batch.fs.internal.predicates;
import java.io.File;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.PathUtils;
/**
* @since 4.2
*/
class AbsolutePathPredicate extends AbstractFilePredicate {
private final String path;
private final Path baseDir;
AbsolutePathPredicate(String path, Path baseDir) {
this.baseDir = baseDir;
this.path = PathUtils.sanitize(path);
}
@Override
public boolean apply(InputFile f) {
return path.equals(f.absolutePath());
}
@Override
public Iterable<InputFile> get(Index index) {
String relative = PathUtils.sanitize(new PathResolver().relativePath(baseDir.toFile(), new File(path)));
if (relative == null) {
return Collections.emptyList();
}
InputFile f = index.inputFile(relative);
return f != null ? Arrays.asList(f) : Collections.emptyList();
}
@Override
public int priority() {
return USE_INDEX;
}
}
| 1,970 | 29.796875 | 108 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/AbstractFilePredicate.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.batch.fs.internal.predicates;
import java.util.stream.StreamSupport;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
/**
* Partial implementation of {@link OptimizedFilePredicate}.
* @since 5.1
*/
public abstract class AbstractFilePredicate implements OptimizedFilePredicate {
protected static final int DEFAULT_PRIORITY = 10;
protected static final int USE_INDEX = 20;
@Override
public Iterable<InputFile> filter(Iterable<InputFile> target) {
return () -> StreamSupport.stream(target.spliterator(), false)
.filter(this::apply)
.iterator();
}
@Override
public Iterable<InputFile> get(Index index) {
return filter(index.inputFiles());
}
@Override
public int priority() {
return DEFAULT_PRIORITY;
}
@Override
public final int compareTo(OptimizedFilePredicate o) {
return o.priority() - priority();
}
}
| 1,773 | 29.586207 | 79 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/AndPredicate.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.batch.fs.internal.predicates;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
import static java.util.stream.Collectors.toList;
/**
* @since 4.2
*/
class AndPredicate extends AbstractFilePredicate implements OperatorPredicate {
private final List<OptimizedFilePredicate> predicates = new ArrayList<>();
private AndPredicate() {
}
public static FilePredicate create(Collection<FilePredicate> predicates) {
if (predicates.isEmpty()) {
return TruePredicate.TRUE;
}
AndPredicate result = new AndPredicate();
for (FilePredicate filePredicate : predicates) {
if (filePredicate == TruePredicate.TRUE) {
continue;
} else if (filePredicate == FalsePredicate.FALSE) {
return FalsePredicate.FALSE;
} else if (filePredicate instanceof AndPredicate) {
result.predicates.addAll(((AndPredicate) filePredicate).predicates);
} else {
result.predicates.add(OptimizedFilePredicateAdapter.create(filePredicate));
}
}
Collections.sort(result.predicates);
return result;
}
@Override
public boolean apply(InputFile f) {
for (OptimizedFilePredicate predicate : predicates) {
if (!predicate.apply(f)) {
return false;
}
}
return true;
}
@Override
public Iterable<InputFile> filter(Iterable<InputFile> target) {
Iterable<InputFile> result = target;
for (OptimizedFilePredicate predicate : predicates) {
result = predicate.filter(result);
}
return result;
}
@Override
public Iterable<InputFile> get(Index index) {
if (predicates.isEmpty()) {
return index.inputFiles();
}
// Optimization, use get on first predicate then filter with next predicates
Iterable<InputFile> result = predicates.get(0).get(index);
for (int i = 1; i < predicates.size(); i++) {
result = predicates.get(i).filter(result);
}
return result;
}
Collection<OptimizedFilePredicate> predicates() {
return predicates;
}
@Override
public List<FilePredicate> operands() {
return predicates.stream().map(p -> (FilePredicate) p).collect(toList());
}
}
| 3,197 | 29.75 | 83 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/ChangedFilePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
public class ChangedFilePredicate implements FilePredicate {
private final FilePredicate originalPredicate;
public ChangedFilePredicate(FilePredicate originalPredicate) {
this.originalPredicate = originalPredicate;
}
@Override
public boolean apply(InputFile inputFile) {
return originalPredicate.apply(inputFile) && InputFile.Status.SAME != inputFile.status();
}
}
| 1,372 | 34.205128 | 93 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/DefaultFilePredicates.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.batch.fs.internal.predicates;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.internal.PathPattern;
/**
* Factory of {@link FilePredicate}
*
* @since 4.2
*/
public class DefaultFilePredicates implements FilePredicates {
private final Path baseDir;
/**
* Client code should use {@link org.sonar.api.batch.fs.FileSystem#predicates()} to get an instance
*/
public DefaultFilePredicates(Path baseDir) {
this.baseDir = baseDir;
}
/**
* Returns a predicate that always evaluates to true
*/
@Override
public FilePredicate all() {
return TruePredicate.TRUE;
}
/**
* Returns a predicate that always evaluates to false
*/
@Override
public FilePredicate none() {
return FalsePredicate.FALSE;
}
@Override
public FilePredicate hasAbsolutePath(String s) {
return new AbsolutePathPredicate(s, baseDir);
}
/**
* non-normalized path and Windows-style path are supported
*/
@Override
public FilePredicate hasRelativePath(String s) {
return new RelativePathPredicate(s);
}
@Override
public FilePredicate hasFilename(String s) {
return new FilenamePredicate(s);
}
@Override
public FilePredicate hasExtension(String s) {
return new FileExtensionPredicate(s);
}
@Override
public FilePredicate hasURI(URI uri) {
return new URIPredicate(uri, baseDir);
}
@Override
public FilePredicate matchesPathPattern(String inclusionPattern) {
return new PathPatternPredicate(PathPattern.create(inclusionPattern));
}
@Override
public FilePredicate matchesPathPatterns(String[] inclusionPatterns) {
if (inclusionPatterns.length == 0) {
return TruePredicate.TRUE;
}
FilePredicate[] predicates = new FilePredicate[inclusionPatterns.length];
for (int i = 0; i < inclusionPatterns.length; i++) {
predicates[i] = new PathPatternPredicate(PathPattern.create(inclusionPatterns[i]));
}
return or(predicates);
}
@Override
public FilePredicate doesNotMatchPathPattern(String exclusionPattern) {
return not(matchesPathPattern(exclusionPattern));
}
@Override
public FilePredicate doesNotMatchPathPatterns(String[] exclusionPatterns) {
if (exclusionPatterns.length == 0) {
return TruePredicate.TRUE;
}
return not(matchesPathPatterns(exclusionPatterns));
}
@Override
public FilePredicate hasPath(String s) {
File file = new File(s);
if (file.isAbsolute()) {
return hasAbsolutePath(s);
}
return hasRelativePath(s);
}
@Override
public FilePredicate is(File ioFile) {
if (ioFile.isAbsolute()) {
return hasAbsolutePath(ioFile.getAbsolutePath());
}
return hasRelativePath(ioFile.getPath());
}
@Override
public FilePredicate hasLanguage(String language) {
return new LanguagePredicate(language);
}
@Override
public FilePredicate hasLanguages(Collection<String> languages) {
List<FilePredicate> list = new ArrayList<>();
for (String language : languages) {
list.add(hasLanguage(language));
}
return or(list);
}
@Override
public FilePredicate hasLanguages(String... languages) {
List<FilePredicate> list = new ArrayList<>();
for (String language : languages) {
list.add(hasLanguage(language));
}
return or(list);
}
@Override
public FilePredicate hasType(InputFile.Type type) {
return new TypePredicate(type);
}
@Override
public FilePredicate not(FilePredicate p) {
return new NotPredicate(p);
}
@Override
public FilePredicate or(Collection<FilePredicate> or) {
return OrPredicate.create(or);
}
@Override
public FilePredicate or(FilePredicate... or) {
return OrPredicate.create(Arrays.asList(or));
}
@Override
public FilePredicate or(FilePredicate first, FilePredicate second) {
return OrPredicate.create(Arrays.asList(first, second));
}
@Override
public FilePredicate and(Collection<FilePredicate> and) {
return AndPredicate.create(and);
}
@Override
public FilePredicate and(FilePredicate... and) {
return AndPredicate.create(Arrays.asList(and));
}
@Override
public FilePredicate and(FilePredicate first, FilePredicate second) {
return AndPredicate.create(Arrays.asList(first, second));
}
@Override
public FilePredicate hasStatus(Status status) {
return new StatusPredicate(status);
}
@Override
public FilePredicate hasAnyStatus() {
return new StatusPredicate(null);
}
}
| 5,662 | 25.339535 | 101 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/FalsePredicate.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.batch.fs.internal.predicates;
import java.util.Collections;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
class FalsePredicate extends AbstractFilePredicate {
static final FilePredicate FALSE = new FalsePredicate();
@Override
public boolean apply(InputFile inputFile) {
return false;
}
@Override
public Iterable<InputFile> filter(Iterable<InputFile> target) {
return Collections.emptyList();
}
@Override
public Iterable<InputFile> get(Index index) {
return Collections.emptyList();
}
}
| 1,477 | 31.130435 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/FileExtensionPredicate.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.batch.fs.internal.predicates;
import java.util.Locale;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 6.3
*/
public class FileExtensionPredicate extends AbstractFilePredicate {
private final String extension;
public FileExtensionPredicate(String extension) {
this.extension = lowercase(extension);
}
@Override
public boolean apply(InputFile inputFile) {
return extension.equals(getExtension(inputFile));
}
@Override
public Iterable<InputFile> get(FileSystem.Index index) {
return index.getFilesByExtension(extension);
}
public static String getExtension(InputFile inputFile) {
return getExtension(inputFile.filename());
}
static String getExtension(String name) {
int index = name.lastIndexOf('.');
if (index < 0) {
return "";
}
return lowercase(name.substring(index + 1));
}
private static String lowercase(String extension) {
return extension.toLowerCase(Locale.ENGLISH);
}
}
| 1,875 | 28.777778 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/FilenamePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 6.3
*/
public class FilenamePredicate extends AbstractFilePredicate {
private final String filename;
public FilenamePredicate(String filename) {
this.filename = filename;
}
@Override
public boolean apply(InputFile inputFile) {
return filename.equals(inputFile.filename());
}
@Override
public Iterable<InputFile> get(FileSystem.Index index) {
return index.getFilesByName(filename);
}
}
| 1,414 | 29.76087 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/LanguagePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 4.2
*/
class LanguagePredicate extends AbstractFilePredicate {
private final String language;
LanguagePredicate(String language) {
this.language = language;
}
@Override
public boolean apply(InputFile f) {
return language.equals(f.language());
}
}
| 1,222 | 30.358974 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/NotPredicate.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.batch.fs.internal.predicates;
import java.util.Arrays;
import java.util.List;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 4.2
*/
class NotPredicate extends AbstractFilePredicate implements OperatorPredicate {
private final FilePredicate predicate;
NotPredicate(FilePredicate predicate) {
this.predicate = predicate;
}
@Override
public boolean apply(InputFile f) {
return !predicate.apply(f);
}
@Override
public List<FilePredicate> operands() {
return Arrays.asList(predicate);
}
}
| 1,440 | 28.408163 | 79 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/OperatorPredicate.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.batch.fs.internal.predicates;
import java.util.List;
import org.sonar.api.batch.fs.FilePredicate;
/**
* A predicate that associate other predicates
*/
public interface OperatorPredicate extends FilePredicate {
List<FilePredicate> operands();
}
| 1,117 | 32.878788 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/OptimizedFilePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
/**
* Optimized version of FilePredicate allowing to speed up query by looking at InputFile by index.
*/
public interface OptimizedFilePredicate extends FilePredicate, Comparable<OptimizedFilePredicate> {
/**
* Filter provided files to keep only the ones that are valid for this predicate
*/
Iterable<InputFile> filter(Iterable<InputFile> inputFiles);
/**
* Get all files that are valid for this predicate.
*/
Iterable<InputFile> get(FileSystem.Index index);
/**
* For optimization. FilePredicates will be applied in priority order. For example when doing
* p.and(p1, p2, p3) then p1, p2 and p3 will be applied according to their priority value. Higher priority value
* are applied first.
* Assign a high priority when the predicate will likely highly reduce the set of InputFiles to filter. Also
* {@link RelativePathPredicate} and AbsolutePathPredicate have a high priority since they are using cache index.
*/
int priority();
}
| 2,003 | 39.08 | 115 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/OptimizedFilePredicateAdapter.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
public class OptimizedFilePredicateAdapter extends AbstractFilePredicate {
private FilePredicate unoptimizedPredicate;
private OptimizedFilePredicateAdapter(FilePredicate unoptimizedPredicate) {
this.unoptimizedPredicate = unoptimizedPredicate;
}
@Override
public boolean apply(InputFile inputFile) {
return unoptimizedPredicate.apply(inputFile);
}
public static OptimizedFilePredicate create(FilePredicate predicate) {
if (predicate instanceof OptimizedFilePredicate) {
return (OptimizedFilePredicate) predicate;
} else {
return new OptimizedFilePredicateAdapter(predicate);
}
}
}
| 1,618 | 33.446809 | 77 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/OrPredicate.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.batch.fs.internal.predicates;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 4.2
*/
class OrPredicate extends AbstractFilePredicate implements OperatorPredicate {
private final List<FilePredicate> predicates = new ArrayList<>();
private OrPredicate() {
}
public static FilePredicate create(Collection<FilePredicate> predicates) {
if (predicates.isEmpty()) {
return TruePredicate.TRUE;
}
OrPredicate result = new OrPredicate();
for (FilePredicate filePredicate : predicates) {
if (filePredicate == TruePredicate.TRUE) {
return TruePredicate.TRUE;
} else if (filePredicate == FalsePredicate.FALSE) {
continue;
} else if (filePredicate instanceof OrPredicate) {
result.predicates.addAll(((OrPredicate) filePredicate).predicates);
} else {
result.predicates.add(filePredicate);
}
}
return result;
}
@Override
public boolean apply(InputFile f) {
for (FilePredicate predicate : predicates) {
if (predicate.apply(f)) {
return true;
}
}
return false;
}
Collection<FilePredicate> predicates() {
return predicates;
}
@Override
public List<FilePredicate> operands() {
return predicates;
}
}
| 2,246 | 28.181818 | 78 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/PathPatternPredicate.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.batch.fs.internal.predicates;
import java.nio.file.Paths;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.PathPattern;
/**
* @since 4.2
*/
class PathPatternPredicate extends AbstractFilePredicate {
private final PathPattern pattern;
PathPatternPredicate(PathPattern pattern) {
this.pattern = pattern;
}
@Override
public boolean apply(InputFile f) {
return pattern.match(f.path(), Paths.get(f.relativePath()));
}
}
| 1,339 | 30.162791 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/RelativePathPredicate.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.batch.fs.internal.predicates;
import java.util.Collections;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.utils.PathUtils;
/**
* @since 4.2
*/
public class RelativePathPredicate extends AbstractFilePredicate {
@Nullable
private final String path;
RelativePathPredicate(String path) {
this.path = PathUtils.sanitize(path);
}
public String path() {
return path;
}
@Override
public boolean apply(InputFile f) {
if (path == null) {
return false;
}
return path.equals(f.relativePath());
}
@Override
public Iterable<InputFile> get(Index index) {
if (path != null) {
InputFile f = index.inputFile(this.path);
if (f != null) {
return Collections.singletonList(f);
}
}
return Collections.emptyList();
}
@Override
public int priority() {
return USE_INDEX;
}
}
| 1,823 | 25.057143 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/StatusPredicate.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.batch.fs.internal.predicates;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
/**
* @deprecated since 7.8
*/
@Deprecated
public class StatusPredicate extends AbstractFilePredicate {
private final InputFile.Status status;
StatusPredicate(@Nullable InputFile.Status status) {
this.status = status;
}
@Override
public boolean apply(InputFile f) {
return status == null || status == f.status();
}
}
| 1,315 | 29.604651 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/TruePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
class TruePredicate extends AbstractFilePredicate {
static final FilePredicate TRUE = new TruePredicate();
@Override
public boolean apply(InputFile inputFile) {
return true;
}
@Override
public Iterable<InputFile> get(Index index) {
return index.inputFiles();
}
@Override
public Iterable<InputFile> filter(Iterable<InputFile> target) {
return target;
}
}
| 1,421 | 30.6 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/TypePredicate.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.batch.fs.internal.predicates;
import org.sonar.api.batch.fs.InputFile;
/**
* @since 4.2
*/
class TypePredicate extends AbstractFilePredicate {
private final InputFile.Type type;
TypePredicate(InputFile.Type type) {
this.type = type;
}
@Override
public boolean apply(InputFile f) {
return type == f.type();
}
}
| 1,203 | 28.365854 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/URIPredicate.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.batch.fs.internal.predicates;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import org.sonar.api.batch.fs.FileSystem.Index;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.scan.filesystem.PathResolver;
/**
* @since 6.6
*/
class URIPredicate extends AbstractFilePredicate {
private final URI uri;
private final Path baseDir;
URIPredicate(URI uri, Path baseDir) {
this.baseDir = baseDir;
this.uri = uri;
}
@Override
public boolean apply(InputFile f) {
return uri.equals(f.uri());
}
@Override
public Iterable<InputFile> get(Index index) {
Path path = Paths.get(uri);
Optional<String> relative = PathResolver.relativize(baseDir, path);
if (!relative.isPresent()) {
return Collections.emptyList();
}
InputFile f = index.inputFile(relative.get());
return f != null ? Arrays.asList(f) : Collections.emptyList();
}
@Override
public int priority() {
return USE_INDEX;
}
}
| 1,935 | 28.333333 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/fs/internal/predicates/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.api.batch.fs.internal.predicates;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 38.36 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/postjob/internal/DefaultPostJobDescriptor.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.batch.postjob.internal;
import java.util.Arrays;
import java.util.Collection;
import org.sonar.api.batch.postjob.PostJobDescriptor;
public class DefaultPostJobDescriptor implements PostJobDescriptor {
private String name;
private String[] properties = new String[0];
public String name() {
return name;
}
public Collection<String> properties() {
return Arrays.asList(properties);
}
@Override
public DefaultPostJobDescriptor name(String name) {
this.name = name;
return this;
}
@Override
public DefaultPostJobDescriptor requireProperty(String... propertyKey) {
return requireProperties(propertyKey);
}
@Override
public DefaultPostJobDescriptor requireProperties(String... propertyKeys) {
this.properties = propertyKeys;
return this;
}
}
| 1,668 | 28.280702 | 77 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/postjob/internal/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.api.batch.postjob.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 977 | 38.12 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/ActiveRulesBuilder.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.batch.rule.internal;
import java.util.LinkedHashMap;
import java.util.Map;
import org.sonar.api.rule.RuleKey;
/**
* Builds instances of {@link org.sonar.api.batch.rule.ActiveRules}.
* <b>For unit testing and internal use only</b>.
*
* @since 4.2
*/
public class ActiveRulesBuilder {
private final Map<RuleKey, NewActiveRule> map = new LinkedHashMap<>();
public ActiveRulesBuilder addRule(NewActiveRule newActiveRule) {
if (map.containsKey(newActiveRule.ruleKey())) {
throw new IllegalStateException(String.format("Rule '%s' is already activated", newActiveRule.ruleKey()));
}
map.put(newActiveRule.ruleKey(), newActiveRule);
return this;
}
public DefaultActiveRules build() {
return new DefaultActiveRules(map.values());
}
}
| 1,636 | 33.104167 | 112 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultActiveRule.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.batch.rule.internal;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.rule.RuleKey;
@Immutable
public class DefaultActiveRule implements ActiveRule {
private final RuleKey ruleKey;
private final String severity;
private final String internalKey;
private final String language;
private final String templateRuleKey;
private final Map<String, String> params;
private final long createdAt;
private final long updatedAt;
private final String qProfileKey;
private final Set<RuleKey> deprecatedKeys;
public DefaultActiveRule(NewActiveRule newActiveRule) {
this.severity = newActiveRule.severity;
this.internalKey = newActiveRule.internalKey;
this.templateRuleKey = newActiveRule.templateRuleKey;
this.ruleKey = newActiveRule.ruleKey;
this.params = Collections.unmodifiableMap(new HashMap<>(newActiveRule.params));
this.language = newActiveRule.language;
this.createdAt = newActiveRule.createdAt;
this.updatedAt = newActiveRule.updatedAt;
this.qProfileKey = newActiveRule.qProfileKey;
this.deprecatedKeys = Collections.unmodifiableSet(new HashSet<>(newActiveRule.deprecatedKeys));
}
@Override
public RuleKey ruleKey() {
return ruleKey;
}
@Override
public String severity() {
return severity;
}
@Override
public String language() {
return language;
}
@Override
public String param(String key) {
return params.get(key);
}
@Override
public Map<String, String> params() {
// already immutable
return params;
}
@Override
public String internalKey() {
return internalKey;
}
@Override
public String templateRuleKey() {
return templateRuleKey;
}
public long createdAt() {
return createdAt;
}
public long updatedAt() {
return updatedAt;
}
@Override
public String qpKey() {
return qProfileKey;
}
public Set<RuleKey> getDeprecatedKeys() {
// already immutable
return deprecatedKeys;
}
}
| 3,012 | 26.144144 | 99 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultActiveRules.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.batch.rule.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.WildcardPattern;
import static java.util.Collections.emptySet;
@Immutable
public class DefaultActiveRules implements ActiveRules {
private final Map<RuleKey, Set<String>> deprecatedRuleKeysByRuleKey = new LinkedHashMap<>();
private final Map<String, List<ActiveRule>> activeRulesByRepository = new HashMap<>();
private final Map<String, Map<String, ActiveRule>> activeRulesByRepositoryAndKey = new HashMap<>();
private final Map<String, Map<String, ActiveRule>> activeRulesByRepositoryAndInternalKey = new HashMap<>();
private final Map<String, List<ActiveRule>> activeRulesByLanguage = new HashMap<>();
public DefaultActiveRules(Collection<NewActiveRule> newActiveRules) {
for (NewActiveRule newAR : newActiveRules) {
DefaultActiveRule ar = new DefaultActiveRule(newAR);
String repo = ar.ruleKey().repository();
activeRulesByRepository.computeIfAbsent(repo, x -> new ArrayList<>()).add(ar);
if (ar.language() != null) {
activeRulesByLanguage.computeIfAbsent(ar.language(), x -> new ArrayList<>()).add(ar);
}
activeRulesByRepositoryAndKey.computeIfAbsent(repo, r -> new HashMap<>()).put(ar.ruleKey().rule(), ar);
String internalKey = ar.internalKey();
if (internalKey != null) {
activeRulesByRepositoryAndInternalKey.computeIfAbsent(repo, r -> new HashMap<>()).put(internalKey, ar);
}
deprecatedRuleKeysByRuleKey.put(ar.ruleKey(), ar.getDeprecatedKeys().stream().map(RuleKey::toString).collect(Collectors.toSet()));
}
}
public Set<String> getDeprecatedRuleKeys(RuleKey ruleKey) {
return deprecatedRuleKeysByRuleKey.getOrDefault(ruleKey, emptySet());
}
public boolean matchesDeprecatedKeys(RuleKey ruleKey, WildcardPattern rulePattern) {
return getDeprecatedRuleKeys(ruleKey).contains(rulePattern.toString());
}
@Override
public ActiveRule find(RuleKey ruleKey) {
return activeRulesByRepositoryAndKey.getOrDefault(ruleKey.repository(), Collections.emptyMap())
.get(ruleKey.rule());
}
@Override
public Collection<ActiveRule> findAll() {
return activeRulesByRepository.entrySet().stream().flatMap(x -> x.getValue().stream()).collect(Collectors.toList());
}
@Override
public Collection<ActiveRule> findByRepository(String repository) {
return activeRulesByRepository.getOrDefault(repository, Collections.emptyList());
}
@Override
public Collection<ActiveRule> findByLanguage(String language) {
return activeRulesByLanguage.getOrDefault(language, Collections.emptyList());
}
@Override
public ActiveRule findByInternalKey(String repository, String internalKey) {
return activeRulesByRepositoryAndInternalKey.containsKey(repository) ? activeRulesByRepositoryAndInternalKey.get(repository).get(internalKey) : null;
}
}
| 4,125 | 40.26 | 153 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRule.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.batch.rule.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.rule.Rule;
import org.sonar.api.batch.rule.RuleParam;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
@Immutable
public class DefaultRule implements Rule {
private final RuleKey key;
private final String name;
private final String severity;
private final String type;
private final String description;
private final String internalKey;
private final RuleStatus status;
private final Map<String, RuleParam> params;
public DefaultRule(NewRule newRule) {
this.key = newRule.key;
this.name = newRule.name;
this.severity = newRule.severity;
this.type = newRule.type;
this.description = newRule.description;
this.internalKey = newRule.internalKey;
this.status = newRule.status;
Map<String, RuleParam> builder = new HashMap<>();
for (NewRuleParam newRuleParam : newRule.params.values()) {
builder.put(newRuleParam.key, new DefaultRuleParam(newRuleParam));
}
params = Collections.unmodifiableMap(builder);
}
@Override
public RuleKey key() {
return key;
}
@Override
public String name() {
return name;
}
@Override
public String severity() {
return severity;
}
@CheckForNull
public String type() {
return type;
}
@Override
public String description() {
return description;
}
@Override
public String internalKey() {
return internalKey;
}
@Override
public RuleStatus status() {
return status;
}
@Override
public RuleParam param(String paramKey) {
return params.get(paramKey);
}
@Override
public Collection<RuleParam> params() {
return params.values();
}
}
| 2,747 | 24.924528 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRuleParam.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.batch.rule.internal;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.rule.RuleParam;
@Immutable
class DefaultRuleParam implements RuleParam {
private final String key;
private final String description;
DefaultRuleParam(NewRuleParam p) {
this.key = p.key;
this.description = p.description;
}
@Override
public String key() {
return key;
}
@Override
@Nullable
public String description() {
return description;
}
}
| 1,379 | 27.75 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/DefaultRules.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.batch.rule.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.rule.Rule;
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.rule.RuleKey;
@Immutable
class DefaultRules implements Rules {
private final Map<String, List<Rule>> rulesByRepository;
private final Map<String, Map<String, List<Rule>>> rulesByRepositoryAndInternalKey;
private final Map<RuleKey, Rule> rulesByRuleKey;
DefaultRules(Collection<NewRule> newRules) {
Map<String, List<Rule>> rulesByRepositoryBuilder = new HashMap<>();
Map<String, Map<String, List<Rule>>> rulesByRepositoryAndInternalKeyBuilder = new HashMap<>();
Map<RuleKey, Rule> rulesByRuleKeyBuilder = new HashMap<>();
for (NewRule newRule : newRules) {
DefaultRule r = new DefaultRule(newRule);
rulesByRuleKeyBuilder.put(r.key(), r);
rulesByRepositoryBuilder.computeIfAbsent(r.key().repository(), x -> new ArrayList<>()).add(r);
addToTable(rulesByRepositoryAndInternalKeyBuilder, r);
}
rulesByRuleKey = Collections.unmodifiableMap(rulesByRuleKeyBuilder);
rulesByRepository = Collections.unmodifiableMap(rulesByRepositoryBuilder);
rulesByRepositoryAndInternalKey = Collections.unmodifiableMap(rulesByRepositoryAndInternalKeyBuilder);
}
private static void addToTable(Map<String, Map<String, List<Rule>>> rulesByRepositoryAndInternalKeyBuilder, DefaultRule r) {
if (r.internalKey() == null) {
return;
}
rulesByRepositoryAndInternalKeyBuilder
.computeIfAbsent(r.key().repository(), x -> new HashMap<>())
.computeIfAbsent(r.internalKey(), x -> new ArrayList<>())
.add(r);
}
@Override
public Rule find(RuleKey ruleKey) {
return rulesByRuleKey.get(ruleKey);
}
@Override
public Collection<Rule> findAll() {
return rulesByRepository.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
@Override
public Collection<Rule> findByRepository(String repository) {
return rulesByRepository.getOrDefault(repository, Collections.emptyList());
}
@Override
public Collection<Rule> findByInternalKey(String repository, String internalKey) {
return rulesByRepositoryAndInternalKey
.getOrDefault(repository, Collections.emptyMap())
.getOrDefault(internalKey, Collections.emptyList());
}
}
| 3,382 | 36.588889 | 126 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewActiveRule.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.batch.rule.internal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
/**
* @since 4.2
*/
@Immutable
public class NewActiveRule {
final RuleKey ruleKey;
final String name;
final String severity;
final Map<String, String> params;
final long createdAt;
final long updatedAt;
final String internalKey;
final String language;
final String templateRuleKey;
final String qProfileKey;
final Set<RuleKey> deprecatedKeys;
NewActiveRule(Builder builder) {
this.ruleKey = builder.ruleKey;
this.name = builder.name;
this.severity = builder.severity;
this.params = builder.params;
this.createdAt = builder.createdAt;
this.updatedAt = builder.updatedAt;
this.internalKey = builder.internalKey;
this.language = builder.language;
this.templateRuleKey = builder.templateRuleKey;
this.qProfileKey = builder.qProfileKey;
this.deprecatedKeys = builder.deprecatedKeys;
}
public RuleKey ruleKey() {
return this.ruleKey;
}
public static class Builder {
private RuleKey ruleKey;
private String name;
private String severity = Severity.defaultSeverity();
private Map<String, String> params = new HashMap<>();
private long createdAt;
private long updatedAt;
private String internalKey;
private String language;
private String templateRuleKey;
private String qProfileKey;
private Set<RuleKey> deprecatedKeys = new HashSet<>();
public Builder setRuleKey(RuleKey ruleKey) {
this.ruleKey = ruleKey;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setSeverity(@Nullable String severity) {
this.severity = StringUtils.defaultIfBlank(severity, Severity.defaultSeverity());
return this;
}
public Builder setParam(String key, @Nullable String value) {
// possible improvement : check that the param key exists in rule definition
if (value == null) {
params.remove(key);
} else {
params.put(key, value);
}
return this;
}
public Builder setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
public Builder setUpdatedAt(long updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public Builder setInternalKey(@Nullable String internalKey) {
this.internalKey = internalKey;
return this;
}
public Builder setLanguage(@Nullable String language) {
this.language = language;
return this;
}
public Builder setTemplateRuleKey(@Nullable String templateRuleKey) {
this.templateRuleKey = templateRuleKey;
return this;
}
public Builder setQProfileKey(String qProfileKey) {
this.qProfileKey = qProfileKey;
return this;
}
public Builder setDeprecatedKeys(Set<RuleKey> deprecatedKeys) {
this.deprecatedKeys = deprecatedKeys;
return this;
}
public NewActiveRule build() {
return new NewActiveRule(this);
}
}
}
| 4,152 | 27.641379 | 87 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRule.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.batch.rule.internal;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
public class NewRule {
private static final String DEFAULT_SEVERITY = Severity.defaultSeverity();
final RuleKey key;
String name;
String description;
String severity = DEFAULT_SEVERITY;
String type;
String internalKey;
RuleStatus status = RuleStatus.defaultStatus();
Map<String, NewRuleParam> params = new HashMap<>();
public NewRule(RuleKey key) {
this.key = key;
}
public NewRule setDescription(@Nullable String description) {
this.description = description;
return this;
}
public NewRule setName(@Nullable String s) {
this.name = s;
return this;
}
public NewRule setSeverity(@Nullable String severity) {
this.severity = StringUtils.defaultIfBlank(severity, DEFAULT_SEVERITY);
return this;
}
public NewRule setType(@Nullable String type) {
this.type = type;
return this;
}
public NewRule setStatus(@Nullable RuleStatus s) {
this.status = (RuleStatus) ObjectUtils.defaultIfNull(s, RuleStatus.defaultStatus());
return this;
}
public NewRule setInternalKey(@Nullable String s) {
this.internalKey = s;
return this;
}
public NewRuleParam addParam(String paramKey) {
if (params.containsKey(paramKey)) {
throw new IllegalStateException(String.format("Parameter '%s' already exists on rule '%s'", paramKey, key));
}
NewRuleParam param = new NewRuleParam(paramKey);
params.put(paramKey, param);
return param;
}
}
| 2,611 | 29.022989 | 114 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/NewRuleParam.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.batch.rule.internal;
import javax.annotation.Nullable;
public class NewRuleParam {
final String key;
String description;
NewRuleParam(String key) {
this.key = key;
}
public NewRuleParam setDescription(@Nullable String s) {
description = s;
return this;
}
}
| 1,150 | 30.108108 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/RulesBuilder.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.batch.rule.internal;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.rule.RuleKey;
/**
* For unit testing and internal use only.
*
* @since 4.2
*/
public class RulesBuilder {
private final Map<RuleKey, NewRule> map = new HashMap<>();
public NewRule add(RuleKey key) {
if (map.containsKey(key)) {
throw new IllegalStateException(String.format("Rule '%s' already exists", key));
}
NewRule newRule = new NewRule(key);
map.put(key, newRule);
return newRule;
}
public Rules build() {
return new DefaultRules(map.values());
}
}
| 1,497 | 28.96 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/rule/internal/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.api.batch.rule.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 974 | 38 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/code/internal/DefaultSignificantCode.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.batch.sensor.code.internal;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.utils.Preconditions;
public class DefaultSignificantCode extends DefaultStorable implements NewSignificantCode {
private SortedMap<Integer, TextRange> significantCodePerLine = new TreeMap<>();
private InputFile inputFile;
public DefaultSignificantCode() {
super();
}
public DefaultSignificantCode(@Nullable SensorStorage storage) {
super(storage);
}
@Override
public DefaultSignificantCode onFile(InputFile inputFile) {
this.inputFile = inputFile;
return this;
}
@Override
public DefaultSignificantCode addRange(TextRange range) {
Preconditions.checkState(this.inputFile != null, "addRange() should be called after on()");
int line = range.start().line();
Preconditions.checkArgument(line == range.end().line(), "Ranges of significant code must be located in a single line");
Preconditions.checkState(!significantCodePerLine.containsKey(line), "Significant code was already reported for line '%s'. Can only report once per line.", line);
significantCodePerLine.put(line, range);
return this;
}
@Override
protected void doSave() {
Preconditions.checkState(inputFile != null, "Call onFile() first");
storage.store(this);
}
public InputFile inputFile() {
return inputFile;
}
public SortedMap<Integer, TextRange> significantCodePerLine() {
return significantCodePerLine;
}
}
| 2,638 | 33.272727 | 165 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.