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 |
|---|---|---|---|---|---|---|
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/impl/AbstractPMDProcessorTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageProcessor;
class AbstractPMDProcessorTest {
@Test
void shouldUseMonoThreadProcessorForZeroOnly() {
AbstractPMDProcessor processor = AbstractPMDProcessor.newFileProcessor(createTask(0));
assertSame(MonoThreadProcessor.class, processor.getClass());
processor = AbstractPMDProcessor.newFileProcessor(createTask(1));
assertSame(MultiThreadProcessor.class, processor.getClass());
}
private LanguageProcessor.AnalysisTask createTask(int threads) {
LanguageProcessor.AnalysisTask task = new LanguageProcessor.AnalysisTask(null, null, null, threads, null, null, null);
return task;
}
}
| 913 | 31.642857 | 126 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import net.sourceforge.pmd.PmdCoreTestUtils;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.document.TextFileContent;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
class FileAnalysisCacheTest {
@TempDir
private Path tempFolder;
private File unexistingCacheFile;
private File newCacheFile;
private File emptyCacheFile;
private TextDocument sourceFile;
private TextFile sourceFileBackend;
private final LanguageVersion dummyVersion = PmdCoreTestUtils.dummyVersion();
@BeforeEach
public void setUp() throws IOException {
unexistingCacheFile = tempFolder.resolve("non-existing-file.cache").toFile();
newCacheFile = tempFolder.resolve("pmd-analysis.cache").toFile();
emptyCacheFile = Files.createTempFile(tempFolder, null, null).toFile();
Path sourceFile = tempFolder.resolve("Source.java");
Files.write(sourceFile, listOf("dummy text"));
this.sourceFileBackend = TextFile.forPath(sourceFile, Charset.defaultCharset(), dummyVersion);
this.sourceFile = TextDocument.create(sourceFileBackend);
}
@Test
void testLoadFromNonExistingFile() throws IOException {
final FileAnalysisCache cache = new FileAnalysisCache(unexistingCacheFile);
assertNotNull(cache, "Cache creation from non existing file failed.");
}
@Test
void testLoadFromEmptyFile() throws IOException {
final FileAnalysisCache cache = new FileAnalysisCache(emptyCacheFile);
assertNotNull(cache, "Cache creation from empty file failed.");
}
@Test
void testLoadFromDirectoryShouldntThrow() throws IOException {
new FileAnalysisCache(tempFolder.toFile());
}
@Test
void testLoadFromUnreadableFileShouldntThrow() throws IOException {
emptyCacheFile.setReadable(false);
new FileAnalysisCache(emptyCacheFile);
}
@Test
void testStoreCreatesFile() throws Exception {
final FileAnalysisCache cache = new FileAnalysisCache(unexistingCacheFile);
cache.persist();
assertTrue(unexistingCacheFile.exists(), "Cache file doesn't exist after store");
}
@Test
void testStoreOnUnwritableFileShouldntThrow() throws IOException {
emptyCacheFile.setWritable(false);
final FileAnalysisCache cache = new FileAnalysisCache(emptyCacheFile);
cache.persist();
}
@Test
void testStorePersistsFilesWithViolations() throws IOException {
final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile);
cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend));
final FileAnalysisListener cacheListener = cache.startFileAnalysis(sourceFile);
cache.isUpToDate(sourceFile);
final RuleViolation rv = mock(RuleViolation.class);
final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4);
when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getFileId(), textLocation));
final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS);
when(rule.getLanguage()).thenReturn(mock(Language.class));
when(rv.getRule()).thenReturn(rule);
cacheListener.onRuleViolation(rv);
cache.persist();
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend));
assertTrue(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file with violations is not up to date");
final List<RuleViolation> cachedViolations = reloadedCache.getCachedViolations(sourceFile);
assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch");
final RuleViolation cachedViolation = cachedViolations.get(0);
assertSame(sourceFile.getFileId(), cachedViolation.getFileId());
assertEquals(textLocation.getStartLine(), cachedViolation.getBeginLine());
assertEquals(textLocation.getStartColumn(), cachedViolation.getBeginColumn());
assertEquals(textLocation.getEndLine(), cachedViolation.getEndLine());
assertEquals(textLocation.getEndColumn(), cachedViolation.getEndColumn());
}
@Test
void testDisplayNameIsRespected() throws Exception {
// This checks that the display name of the file is respected even if
// the file is assigned a different display name across runs. The path
// id is saved into the cache file, and the cache implementation updates the
// display name of the violations to match their current display name.
final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS);
when(rule.getLanguage()).thenReturn(mock(Language.class));
final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4);
TextFile mockFile = mock(TextFile.class);
when(mockFile.getFileId()).thenReturn(FileId.fromPathLikeString("a/bc"));
when(mockFile.getLanguageVersion()).thenReturn(dummyVersion);
when(mockFile.readContents()).thenReturn(TextFileContent.fromCharSeq("abc"));
final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile);
cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend));
try (TextDocument doc0 = TextDocument.create(mockFile)) {
cache.isUpToDate(doc0);
try (FileAnalysisListener listener = cache.startFileAnalysis(doc0)) {
listener.onRuleViolation(new ParametricRuleViolation(rule, FileLocation.range(doc0.getFileId(), textLocation), "message"));
}
} finally {
cache.persist();
}
reloadWithOneViolation(mockFile);
}
private void reloadWithOneViolation(TextFile mockFile) throws IOException {
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(mockFile));
try (TextDocument doc1 = TextDocument.create(mockFile)) {
assertTrue(reloadedCache.isUpToDate(doc1),
"Cache believes unmodified file with violations is not up to date");
List<RuleViolation> cachedViolations = reloadedCache.getCachedViolations(doc1);
assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch");
final RuleViolation cachedViolation = cachedViolations.get(0);
assertEquals(mockFile.getFileId(), cachedViolation.getLocation().getFileId());
}
}
@Test
void testCacheValidityWithNoChanges() throws IOException {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
setupCacheWithFiles(newCacheFile, rs, cl);
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend));
assertTrue(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file is not up to date without ruleset / classpath changes");
}
@Test
void testCacheValidityWithIrrelevantChanges() throws IOException {
final RuleSets rs = mock(RuleSets.class);
final URLClassLoader cl = mock(URLClassLoader.class);
when(cl.getURLs()).thenReturn(new URL[] {});
setupCacheWithFiles(newCacheFile, rs, cl);
final File classpathFile = Files.createTempFile(tempFolder, null, "foo.xml").toFile();
when(cl.getURLs()).thenReturn(new URL[] { classpathFile.toURI().toURL(), });
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend));
assertTrue(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file is not up to date without ruleset / classpath changes");
}
@Test
void testRulesetChangeInvalidatesCache() throws IOException {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
setupCacheWithFiles(newCacheFile, rs, cl);
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
when(rs.getChecksum()).thenReturn(1L);
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file is up to date after ruleset changed");
}
@Test
void testAuxClasspathNonExistingAuxclasspathEntriesIgnored() throws MalformedURLException, IOException {
final RuleSets rs = mock(RuleSets.class);
final URLClassLoader cl = mock(URLClassLoader.class);
when(cl.getURLs()).thenReturn(new URL[] { tempFolder.resolve("non-existing-dir").toFile().toURI().toURL(), });
setupCacheWithFiles(newCacheFile, rs, cl);
final FileAnalysisCache analysisCache = new FileAnalysisCache(newCacheFile);
when(cl.getURLs()).thenReturn(new URL[] {});
analysisCache.checkValidity(rs, cl, setOf(sourceFileBackend));
assertTrue(analysisCache.isUpToDate(sourceFile),
"Cache believes unmodified file is not up to date after non-existing auxclasspath entry removed");
}
@Test
void testAuxClasspathChangeWithoutDFAorTypeResolutionDoesNotInvalidatesCache() throws MalformedURLException, IOException {
final RuleSets rs = mock(RuleSets.class);
final URLClassLoader cl = mock(URLClassLoader.class);
when(cl.getURLs()).thenReturn(new URL[] { });
setupCacheWithFiles(newCacheFile, rs, cl);
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
when(cl.getURLs()).thenReturn(new URL[] { Files.createTempFile(tempFolder, null, null).toFile().toURI().toURL(), });
reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend));
assertTrue(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file is not up to date after auxclasspath changed when no rule cares");
}
@Test
void testAuxClasspathChangeInvalidatesCache() throws MalformedURLException, IOException {
final RuleSets rs = mock(RuleSets.class);
final URLClassLoader cl = mock(URLClassLoader.class);
when(cl.getURLs()).thenReturn(new URL[] { });
setupCacheWithFiles(newCacheFile, rs, cl);
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile();
when(cl.getURLs()).thenReturn(new URL[] { classpathFile.toURI().toURL(), });
// Make sure the auxclasspath file is not empty
Files.write(classpathFile.toPath(), "some text".getBytes());
final net.sourceforge.pmd.Rule r = mock(net.sourceforge.pmd.Rule.class);
when(r.getLanguage()).thenReturn(mock(Language.class));
when(rs.getAllRules()).thenReturn(Collections.singleton(r));
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes unmodified file is up to date after auxclasspath changed");
}
@Test
void testAuxClasspathJarContentsChangeInvalidatesCache() throws MalformedURLException, IOException {
final RuleSets rs = mock(RuleSets.class);
final URLClassLoader cl = mock(URLClassLoader.class);
final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile();
when(cl.getURLs()).thenReturn(new URL[] { classpathFile.toURI().toURL(), });
final net.sourceforge.pmd.Rule r = mock(net.sourceforge.pmd.Rule.class);
when(r.getLanguage()).thenReturn(mock(Language.class));
when(rs.getAllRules()).thenReturn(Collections.singleton(r));
setupCacheWithFiles(newCacheFile, rs, cl);
// Edit the auxclasspath referenced file
Files.write(classpathFile.toPath(), "some text".getBytes());
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes cache is up to date when a auxclasspath file changed");
}
@Test
void testClasspathNonExistingEntryIsIgnored() throws Exception {
restoreSystemProperties(() -> {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator
+ tempFolder.toFile().getAbsolutePath() + File.separator + "non-existing-dir");
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
try {
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
} catch (final Exception e) {
fail("Validity check failed when classpath includes non-existing directories");
}
});
}
@Test
void testClasspathChangeInvalidatesCache() throws Exception {
restoreSystemProperties(() -> {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile();
setupCacheWithFiles(newCacheFile, rs, cl);
// Edit the classpath referenced file
Files.write(classpathFile.toPath(), "some text".getBytes());
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + classpathFile.getAbsolutePath());
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes cache is up to date when the classpath changed");
});
}
@Test
void testClasspathContentsChangeInvalidatesCache() throws Exception {
restoreSystemProperties(() -> {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile();
// Add a file to classpath
Files.write(classpathFile.toPath(), "some text".getBytes());
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + classpathFile.getAbsolutePath());
setupCacheWithFiles(newCacheFile, rs, cl);
// Change the file's contents
Files.write(classpathFile.toPath(), "some other text".getBytes());
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes cache is up to date when a classpath file changed");
});
}
@Test
void testWildcardClasspath() throws Exception {
restoreSystemProperties(() -> {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
setupCacheWithFiles(newCacheFile, rs, cl);
// Prepare two class files
createZipFile("mylib1.jar");
createZipFile("mylib2.jar");
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + tempFolder.toFile().getAbsolutePath() + "/*");
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes cache is up to date when the classpath changed");
});
}
@Test
void testWildcardClasspathContentsChangeInvalidatesCache() throws Exception {
restoreSystemProperties(() -> {
final RuleSets rs = mock(RuleSets.class);
final ClassLoader cl = mock(ClassLoader.class);
// Prepare two jar files
final File classpathJar1 = createZipFile("mylib1.jar");
createZipFile("mylib2.jar");
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + tempFolder.toFile().getAbsolutePath() + "/*");
setupCacheWithFiles(newCacheFile, rs, cl);
// Change one file's contents (ie: adding more entries)
classpathJar1.delete();
createZipFile(classpathJar1.getName(), 2);
final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile);
reloadedCache.checkValidity(rs, cl, Collections.emptySet());
assertFalse(reloadedCache.isUpToDate(sourceFile),
"Cache believes cache is up to date when the classpath changed");
});
}
@Test
void testUnknownFileIsNotUpToDate() throws IOException {
final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile);
assertFalse(cache.isUpToDate(sourceFile),
"Cache believes an unknown file is up to date");
}
@Test
void testFileIsUpToDate() throws IOException {
setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class));
final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile);
cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend));
assertTrue(cache.isUpToDate(sourceFile),
"Cache believes a known, unchanged file is not up to date");
}
@Test
void testFileIsNotUpToDateWhenEdited() throws IOException {
setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class));
// Edit the file
TextFileContent text = TextFileContent.fromCharSeq("some text");
assertEquals(System.lineSeparator(), text.getLineTerminator());
sourceFileBackend.writeContents(text);
sourceFile = TextDocument.create(sourceFileBackend);
final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile);
assertFalse(cache.isUpToDate(sourceFile),
"Cache believes a known, changed file is up to date");
}
private void setupCacheWithFiles(final File cacheFile,
final RuleSets ruleSets,
final ClassLoader classLoader) throws IOException {
// Setup a cache file with an entry for an empty Source.java with no violations
final FileAnalysisCache cache = new FileAnalysisCache(cacheFile);
cache.checkValidity(ruleSets, classLoader, setOf(sourceFileBackend));
cache.isUpToDate(sourceFile);
cache.persist();
}
private File createZipFile(String fileName) throws IOException {
return createZipFile(fileName, 1);
}
private File createZipFile(String fileName, int numEntries) throws IOException {
final File zipFile = Files.createTempFile(tempFolder, null, fileName).toFile();
try (ZipOutputStream zipOS = new ZipOutputStream(Files.newOutputStream(zipFile.toPath()))) {
for (int i = 0; i < numEntries; i++) {
zipOS.putNextEntry(new ZipEntry("lib/foo" + i + ".class"));
zipOS.write(("content of " + fileName + " entry " + i).getBytes(StandardCharsets.UTF_8));
zipOS.closeEntry();
}
}
return zipFile;
}
}
| 21,773 | 44.268191 | 157 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cache/internal/RawFileFingerprinterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.google.common.io.Files;
class RawFileFingerprinterTest extends AbstractClasspathEntryFingerprinterTest {
@Override
protected ClasspathEntryFingerprinter newFingerPrinter() {
return new RawFileFingerprinter();
}
@Override
protected String[] getValidFileExtensions() {
return new String[] { "class" };
}
@Override
protected String[] getInvalidFileExtensions() {
return new String[] { "xml" };
}
@Override
protected File createValidNonEmptyFile() throws IOException {
File file = tempDir.resolve("Foo.class").toFile();
Files.write("some content", file, StandardCharsets.UTF_8);
return file;
}
}
| 931 | 23.526316 | 80 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cache/internal/AbstractClasspathEntryFingerprinterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
abstract class AbstractClasspathEntryFingerprinterTest {
@TempDir
Path tempDir;
protected ClasspathEntryFingerprinter fingerprinter = newFingerPrinter();
protected Checksum checksum = new Adler32();
@BeforeEach
void setUp() {
checksum.reset();
}
protected abstract ClasspathEntryFingerprinter newFingerPrinter();
protected abstract String[] getValidFileExtensions();
protected abstract String[] getInvalidFileExtensions();
protected abstract File createValidNonEmptyFile() throws IOException;
@Test
void appliesToNullIsSafe() {
fingerprinter.appliesTo(null);
}
@ParameterizedTest
@MethodSource("getValidFileExtensions")
void appliesToValidFile(final String extension) {
assertTrue(fingerprinter.appliesTo(extension));
}
@ParameterizedTest
@MethodSource("getInvalidFileExtensions")
void doesNotApplyToInvalidFile(final String extension) {
assertFalse(fingerprinter.appliesTo(extension));
}
@Test
void fingerprintNonExistingFile() throws MalformedURLException, IOException {
final long prevValue = checksum.getValue();
fingerprinter.fingerprint(new File("non-existing").toURI().toURL(), checksum);
assertEquals(prevValue, checksum.getValue());
}
@Test
void fingerprintExistingValidFile() throws IOException {
final long prevValue = checksum.getValue();
final File file = createValidNonEmptyFile();
assertNotEquals(prevValue, updateFingerprint(file));
}
protected long updateFingerprint(final File file) throws MalformedURLException, IOException {
fingerprinter.fingerprint(file.toURI().toURL(), checksum);
return checksum.getValue();
}
}
| 2,639 | 29.344828 | 97 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cache/internal/ZipFileFingerprinterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.Test;
class ZipFileFingerprinterTest extends AbstractClasspathEntryFingerprinterTest {
@Test
void zipEntryMetadataDoesNotAffectFingerprint() throws IOException {
final File file = createValidNonEmptyFile();
final long baselineFingerprint = getBaseLineFingerprint(file);
final long originalFileSize = file.length();
// Change zip entry's metadata
try (ZipFile zip = new ZipFile(file)) {
final ZipEntry zipEntry = zip.entries().nextElement();
zipEntry.setComment("some comment");
zipEntry.setTime(System.currentTimeMillis() + 1000);
overwriteZipFileContents(file, zipEntry);
}
assertEquals(baselineFingerprint, updateFingerprint(file));
assertNotEquals(originalFileSize, file.length());
}
@Test
void zipEntryOrderDoesNotAffectFingerprint() throws IOException {
final File zipFile = tempDir.resolve("foo.jar").toFile();
final ZipEntry fooEntry = new ZipEntry("lib/Foo.class");
final ZipEntry barEntry = new ZipEntry("lib/Bar.class");
overwriteZipFileContents(zipFile, fooEntry, barEntry);
final long baselineFingerprint = getBaseLineFingerprint(zipFile);
// swap order
overwriteZipFileContents(zipFile, barEntry, fooEntry);
assertEquals(baselineFingerprint, updateFingerprint(zipFile));
}
@Test
void nonClassZipEntryDoesNotAffectFingerprint() throws IOException {
final File zipFile = tempDir.resolve("foo.jar").toFile();
final ZipEntry fooEntry = new ZipEntry("lib/Foo.class");
final ZipEntry barEntry = new ZipEntry("bar.properties");
overwriteZipFileContents(zipFile, fooEntry);
final long baselineFingerprint = getBaseLineFingerprint(zipFile);
// add a properties file to the jar
overwriteZipFileContents(zipFile, fooEntry, barEntry);
assertEquals(baselineFingerprint, updateFingerprint(zipFile));
}
@Override
protected ClasspathEntryFingerprinter newFingerPrinter() {
return new ZipFileFingerprinter();
}
@Override
protected String[] getValidFileExtensions() {
return new String[] { "zip", "jar" };
}
@Override
protected String[] getInvalidFileExtensions() {
return new String[] { "xml" };
}
@Override
protected File createValidNonEmptyFile() throws IOException {
final File zipFile = tempDir.resolve("foo.jar").toFile();
overwriteZipFileContents(zipFile, new ZipEntry("lib/Foo.class"));
return zipFile;
}
private void overwriteZipFileContents(final File zipFile, final ZipEntry... zipEntries) throws IOException {
try (ZipOutputStream zipOS = new ZipOutputStream(Files.newOutputStream(zipFile.toPath()))) {
for (final ZipEntry zipEntry : zipEntries) {
zipOS.putNextEntry(zipEntry);
zipOS.write("content of zip entry".getBytes(StandardCharsets.UTF_8));
zipOS.closeEntry();
}
}
}
private long getBaseLineFingerprint(final File file) throws MalformedURLException, IOException {
final Checksum checksum = new Adler32();
fingerprinter.fingerprint(file.toURI().toURL(), checksum);
return checksum.getValue();
}
}
| 3,957 | 35.648148 | 112 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.processor;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.contains;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.internal.SystemProps;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.util.ContextedAssertionError;
import net.sourceforge.pmd.util.log.MessageReporter;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class PmdRunnableTest {
public static final String TEST_MESSAGE_SEMANTIC_ERROR = "An error occurred!";
private static final String PARSER_REPORTS_SEMANTIC_ERROR = "1.9-semantic_error";
private static final String THROWS_SEMANTIC_ERROR = "1.9-throws_semantic_error";
private static final String THROWS_ASSERTION_ERROR = "1.9-throws";
private PMDConfiguration configuration;
private MessageReporter reporter;
private Rule rule;
@BeforeEach
void prepare() {
// reset data
rule = spy(new RuleThatThrows());
configuration = new PMDConfiguration(LanguageRegistry.singleton(ThrowingLanguageModule.INSTANCE));
reporter = mock(MessageReporter.class);
configuration.setReporter(reporter);
// exceptions thrown on a worker thread are not thrown by the main thread,
// so this test only makes sense without separate threads
configuration.setThreads(0);
}
private Report process(LanguageVersion lv) {
configuration.setForceLanguageVersion(lv);
configuration.setIgnoreIncrementalAnalysis(true);
try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) {
pmd.files().addSourceFile(FileId.fromPathLikeString("test.dummy"), "foo");
pmd.addRuleSet(RuleSet.forSingleRule(rule));
return pmd.performAnalysisAndCollectReport();
}
}
@Test
void inErrorRecoveryModeErrorsShouldBeLoggedByParser() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.setProperty(SystemProps.PMD_ERROR_RECOVERY, "");
Report report = process(versionWithParserThatThrowsAssertionError());
assertEquals(1, report.getProcessingErrors().size());
});
}
@Test
void inErrorRecoveryModeErrorsShouldBeLoggedByRule() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.setProperty(SystemProps.PMD_ERROR_RECOVERY, "");
Report report = process(ThrowingLanguageModule.INSTANCE.getDefaultVersion());
List<ProcessingError> errors = report.getProcessingErrors();
assertThat(errors, hasSize(1));
assertThat(errors.get(0).getError(), instanceOf(ContextedAssertionError.class));
});
}
@Test
void withoutErrorRecoveryModeProcessingShouldBeAbortedByParser() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.clearProperty(SystemProps.PMD_ERROR_RECOVERY);
assertThrows(AssertionError.class, () -> process(versionWithParserThatThrowsAssertionError()));
});
}
@Test
void withoutErrorRecoveryModeProcessingShouldBeAbortedByRule() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.clearProperty(SystemProps.PMD_ERROR_RECOVERY);
assertThrows(AssertionError.class, () -> process(ThrowingLanguageModule.INSTANCE.getDefaultVersion()));
});
}
@Test
void semanticErrorShouldAbortTheRun() {
Report report = process(versionWithParserThatReportsSemanticError());
verify(reporter, times(1))
.log(eq(Level.ERROR), eq("at test.dummy:1:1: " + TEST_MESSAGE_SEMANTIC_ERROR));
verify(rule, never()).apply(Mockito.any(), Mockito.any());
assertEquals(1, report.getProcessingErrors().size());
}
@Test
void semanticErrorThrownShouldAbortTheRun() {
Report report = process(getVersionWithParserThatThrowsSemanticError());
verify(reporter, times(1)).log(eq(Level.ERROR), contains(TEST_MESSAGE_SEMANTIC_ERROR));
verify(rule, never()).apply(Mockito.any(), Mockito.any());
assertEquals(1, report.getProcessingErrors().size());
}
private static LanguageVersion versionWithParserThatThrowsAssertionError() {
return ThrowingLanguageModule.INSTANCE.getVersion(THROWS_ASSERTION_ERROR);
}
private static LanguageVersion getVersionWithParserThatThrowsSemanticError() {
return ThrowingLanguageModule.INSTANCE.getVersion(THROWS_SEMANTIC_ERROR);
}
private static LanguageVersion versionWithParserThatReportsSemanticError() {
return ThrowingLanguageModule.INSTANCE.getVersion(PARSER_REPORTS_SEMANTIC_ERROR);
}
private static class ThrowingLanguageModule extends SimpleLanguageModuleBase {
static final ThrowingLanguageModule INSTANCE = new ThrowingLanguageModule();
ThrowingLanguageModule() {
super(LanguageMetadata.withId("foo").name("Foo").extensions("foo")
.addVersion(THROWS_ASSERTION_ERROR)
.addVersion(THROWS_SEMANTIC_ERROR)
.addVersion(PARSER_REPORTS_SEMANTIC_ERROR)
.addDefaultVersion("defalt"),
ThrowingLanguageModule::makeParser);
}
private static Parser makeParser() {
return task -> {
switch (task.getLanguageVersion().getVersion()) {
case THROWS_ASSERTION_ERROR:
throw new AssertionError("test error while parsing");
case PARSER_REPORTS_SEMANTIC_ERROR: {
RootNode root = DummyLanguageModule.readLispNode(task);
task.getReporter().error(root, TEST_MESSAGE_SEMANTIC_ERROR);
return root;
}
case THROWS_SEMANTIC_ERROR: {
RootNode root = DummyLanguageModule.readLispNode(task);
throw task.getReporter().error(root, TEST_MESSAGE_SEMANTIC_ERROR);
}
default:
return DummyLanguageModule.readLispNode(task);
}
};
}
}
private static class RuleThatThrows extends AbstractRule {
RuleThatThrows() {
setLanguage(ThrowingLanguageModule.INSTANCE);
}
@Override
public void apply(Node target, RuleContext ctx) {
throw new AssertionError("test");
}
}
}
| 7,905 | 37.378641 | 115 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/OptionalBoolTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static net.sourceforge.pmd.util.OptionalBool.NO;
import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN;
import static net.sourceforge.pmd.util.OptionalBool.YES;
import static net.sourceforge.pmd.util.OptionalBool.definitely;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class OptionalBoolTest {
@Test
void testDefinitely() {
assertEquals(YES, definitely(true));
assertEquals(NO, definitely(false));
}
@Test
void testIsKnown() {
assertTrue(YES.isKnown());
assertTrue(NO.isKnown());
assertFalse(UNKNOWN.isKnown());
}
@Test
void testIsTrue() {
assertTrue(YES.isTrue());
assertFalse(NO.isTrue());
assertFalse(UNKNOWN.isTrue());
}
@Test
void testComplement() {
assertEquals(YES, NO.complement());
assertEquals(NO, YES.complement());
assertEquals(UNKNOWN, UNKNOWN.complement());
}
}
| 1,225 | 25.652174 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/IOUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.util.IOUtil;
class IOUtilTest {
@Test
void testReadAllBytes() throws IOException {
byte[] data = "12345".getBytes(StandardCharsets.UTF_8);
try (InputStream stream = new ByteArrayInputStream(data)) {
byte[] bytes = IOUtil.toByteArray(stream);
assertEquals(5, bytes.length);
assertArrayEquals(data, bytes);
}
}
@Test
void testToByteArrayResize() throws IOException {
int size = 8192 + 8192 + 10;
byte[] data = new byte[size];
for (int i = 0; i < size; i++) {
data[i] = 'A';
}
try (InputStream stream = new ByteArrayInputStream(data)) {
byte[] bytes = IOUtil.toByteArray(stream);
assertEquals(size, bytes.length);
assertArrayEquals(data, bytes);
}
}
@Test
void testSkipFully() throws IOException {
byte[] data = "12345".getBytes(StandardCharsets.UTF_8);
try (InputStream stream = new ByteArrayInputStream(data)) {
assertThrows(IllegalArgumentException.class, () -> IOUtil.skipFully(stream, -1));
assertEquals(3, IOUtil.skipFully(stream, 3));
byte[] bytes = IOUtil.toByteArray(stream);
assertEquals(2, bytes.length);
assertArrayEquals("45".getBytes(StandardCharsets.UTF_8), bytes);
}
}
@Test
void testSkipFully2() throws IOException {
byte[] data = "12345".getBytes(StandardCharsets.UTF_8);
try (InputStream stream = new ByteArrayInputStream(data)) {
// skip more bytes than the stream contains
assertEquals(data.length, IOUtil.skipFully(stream, data.length + 1));
byte[] bytes = IOUtil.toByteArray(stream);
assertEquals(0, bytes.length);
}
}
@Test
void testNormalizePath() {
if (SystemUtils.IS_OS_UNIX) {
assertEquals("ab/cd.txt", IOUtil.normalizePath("ab/ef/../cd.txt"));
assertEquals("/a.txt", IOUtil.normalizePath("/x/../../a.txt"));
assertEquals("/foo", IOUtil.normalizePath("//../foo"));
assertEquals("/foo", IOUtil.normalizePath("/foo//"));
assertEquals("/foo", IOUtil.normalizePath("/foo/./"));
assertEquals("/bar", IOUtil.normalizePath("/foo/../bar"));
assertEquals("/bar", IOUtil.normalizePath("/foo/../bar/"));
assertEquals("/baz", IOUtil.normalizePath("/foo/../bar/../baz"));
assertEquals("/foo/bar", IOUtil.normalizePath("//foo//./bar"));
assertEquals("foo", IOUtil.normalizePath("foo/bar/.."));
assertEquals("bar", IOUtil.normalizePath("foo/../bar"));
assertEquals("/foo/baz", IOUtil.normalizePath("//foo/bar/../baz"));
assertEquals("~/bar", IOUtil.normalizePath("~/foo/../bar/"));
assertEquals("/", IOUtil.normalizePath("/../"));
assertEquals("bar", IOUtil.normalizePath("~/../bar"));
assertEquals("bar", IOUtil.normalizePath("./bar"));
assertNull(IOUtil.normalizePath("../foo"));
assertNull(IOUtil.normalizePath("foo/../../bar"));
assertNull(IOUtil.normalizePath("."));
assertTrue(IOUtil.equalsNormalizedPaths("foo/../bar", "bar/./"));
}
if (SystemUtils.IS_OS_WINDOWS) {
assertEquals("ab\\cd.txt", IOUtil.normalizePath("ab\\ef\\..\\cd.txt"));
assertEquals("\\a.txt", IOUtil.normalizePath("\\x\\..\\..\\a.txt"));
assertEquals("\\foo", IOUtil.normalizePath("\\foo\\\\"));
assertEquals("\\foo", IOUtil.normalizePath("\\foo\\.\\"));
assertEquals("\\bar", IOUtil.normalizePath("\\foo\\..\\bar"));
assertEquals("\\bar", IOUtil.normalizePath("\\foo\\..\\bar\\"));
assertEquals("\\baz", IOUtil.normalizePath("\\foo\\..\\bar\\..\\baz"));
assertEquals("\\\\foo\\bar\\", IOUtil.normalizePath("\\\\foo\\bar"));
assertEquals("\\\\foo\\bar\\baz", IOUtil.normalizePath("\\\\foo\\bar\\..\\baz"));
assertEquals("foo", IOUtil.normalizePath("foo\\bar\\.."));
assertEquals("bar", IOUtil.normalizePath("foo\\..\\bar"));
assertEquals("\\foo\\baz", IOUtil.normalizePath("\\foo\\bar\\..\\baz"));
assertEquals("\\", IOUtil.normalizePath("\\..\\"));
assertEquals("bar", IOUtil.normalizePath(".\\bar"));
assertNull(IOUtil.normalizePath("\\\\..\\foo"));
assertNull(IOUtil.normalizePath("..\\foo"));
assertNull(IOUtil.normalizePath("foo\\..\\..\\bar"));
assertNull(IOUtil.normalizePath("."));
assertNull(IOUtil.normalizePath("\\\\foo\\\\.\\bar"));
assertNull(IOUtil.normalizePath("\\\\foo\\.\\bar"));
assertTrue(IOUtil.equalsNormalizedPaths("foo\\..\\bar", "bar\\.\\"));
assertEquals("C:\\bar", IOUtil.normalizePath("C:\\..\\bar"));
assertEquals("ab\\cd.txt", IOUtil.normalizePath("ab\\ef\\..\\cd.txt"));
assertEquals("C:\\ab\\cd.txt", IOUtil.normalizePath("C:\\ab\\ef\\..\\.\\cd.txt"));
assertNull(IOUtil.normalizePath("..\\foo"));
assertNull(IOUtil.normalizePath("foo\\..\\..\\bar"));
}
}
@Test
void testFilenameExtension() {
assertEquals("txt", IOUtil.getFilenameExtension("ab/cd.txt"));
assertEquals("txt", IOUtil.getFilenameExtension("ab.cd.txt"));
assertEquals("", IOUtil.getFilenameExtension("ab/cd"));
assertEquals("html", IOUtil.getFilenameExtension("cd.html"));
}
@Test
void testFilenameBase() {
assertEquals("cd", IOUtil.getFilenameBase("ab/cd.txt"));
assertEquals("ab.cd", IOUtil.getFilenameBase("ab.cd.txt"));
assertEquals("cd", IOUtil.getFilenameBase("ab/cd"));
}
@Test
void testBomAwareStream() throws IOException {
assertBomStream("No BOM".getBytes(StandardCharsets.UTF_8), "No BOM", null);
assertBomStream("\ufeffBOM".getBytes(StandardCharsets.UTF_8), "BOM", StandardCharsets.UTF_8.name());
assertBomStream("\ufeffBOM".getBytes(StandardCharsets.UTF_16LE), "BOM", StandardCharsets.UTF_16LE.name());
assertBomStream("\ufeffBOM".getBytes(StandardCharsets.UTF_16BE), "BOM", StandardCharsets.UTF_16BE.name());
}
private void assertBomStream(byte[] data, String expectedData, String expectedCharset) throws IOException {
try (IOUtil.BomAwareInputStream stream = new IOUtil.BomAwareInputStream(new ByteArrayInputStream(data))) {
if (expectedCharset != null) {
assertTrue(stream.hasBom());
assertEquals(expectedCharset, stream.getBomCharsetName());
assertEquals(expectedData, new String(IOUtil.toByteArray(stream), stream.getBomCharsetName()));
} else {
assertFalse(stream.hasBom());
assertNull(stream.getBomCharsetName());
assertEquals(expectedData, new String(IOUtil.toByteArray(stream), StandardCharsets.UTF_8));
}
}
}
@Test
void testOutputStreamFromWriter() throws IOException {
StringWriter writer = new StringWriter();
try (OutputStream outputStream = IOUtil.fromWriter(writer, "UTF-8")) {
outputStream.write("abc".getBytes(StandardCharsets.UTF_8));
}
assertEquals("abc", writer.toString());
}
@Test
void testInputStreamFromReader() throws IOException {
try (InputStream inputStream = IOUtil.fromReader(new StringReader("abc"))) {
byte[] bytes = IOUtil.toByteArray(inputStream);
assertEquals("abc", new String(bytes, StandardCharsets.UTF_8));
}
}
@Test
void testInputStreamFromReader2() throws IOException {
int size = 8192 + 8192 + 10;
char[] data = new char[size];
for (int i = 0; i < size; i++) {
data[i] = 'A';
}
data[8192] = 'ä'; // block size border - in UTF-8 these are two bytes. Decoding needs to take the bytes
// from previous block and new block
try (InputStream inputStream = IOUtil.fromReader(new StringReader(new String(data)))) {
byte[] bytes = IOUtil.toByteArray(inputStream);
assertEquals(new String(data), new String(bytes, StandardCharsets.UTF_8));
}
}
@Test
void testCopyStream() throws IOException {
int size = 8192 + 8192 + 10;
byte[] data = new byte[size];
for (int i = 0; i < size; i++) {
data[i] = 'A';
}
try (InputStream stream = new ByteArrayInputStream(data);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
IOUtil.copy(stream, out);
byte[] bytes = out.toByteArray();
assertEquals(size, bytes.length);
assertArrayEquals(data, bytes);
}
}
@Test
void testCopyReader() throws IOException {
int size = 8192 + 8192 + 10;
char[] data = new char[size];
for (int i = 0; i < size; i++) {
data[i] = 'A';
}
try (Reader reader = new CharArrayReader(data);
StringWriter writer = new StringWriter()) {
IOUtil.copy(reader, writer);
char[] chars = writer.toString().toCharArray();
assertEquals(size, chars.length);
assertArrayEquals(data, chars);
}
}
@Test
void testReadEmptyStream() throws IOException {
try (InputStream in = new ByteArrayInputStream(new byte[0])) {
byte[] bytes = IOUtil.toByteArray(in);
assertNotNull(bytes);
assertEquals(0, bytes.length);
}
}
@Test
void testCloseQuietly() {
class Stream extends InputStream {
private boolean closed = false;
@Override
public int read() throws IOException {
return 0;
}
@Override
public void close() throws IOException {
closed = true;
throw new IOException("test");
}
public boolean isClosed() {
return closed;
}
}
Stream stream = new Stream();
IOUtil.closeQuietly(stream);
assertTrue(stream.isClosed());
}
@Test
void testReadFileToString() throws IOException {
String testString = "Test ABC";
Path tempFile = Files.createTempFile("pmd", ".txt");
Files.write(tempFile, testString.getBytes(Charset.defaultCharset()));
assertEquals(testString, IOUtil.readFileToString(tempFile.toFile()));
}
@Test
void testReadToString() throws IOException {
String testString = "testReadToString";
Reader reader = new StringReader(testString);
assertEquals(testString, IOUtil.readToString(reader));
}
@Test
void testReadStreamToString() throws IOException {
String testString = "testReadStreamToString";
InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
assertEquals(testString, IOUtil.readToString(stream, StandardCharsets.UTF_8));
}
@Test
void testCreateWriterStdout() throws IOException {
PrintStream originalOut = System.out;
ByteArrayOutputStream data = new ByteArrayOutputStream();
PrintStream out = new PrintStream(new FilterOutputStream(data) {
@Override
public void close() {
fail("Stream must not be closed");
}
});
try {
System.setOut(out);
Writer writer = IOUtil.createWriter();
writer.write("Test");
writer.close();
assertEquals("Test", data.toString());
} finally {
System.setOut(originalOut);
}
}
}
| 13,079 | 38.756839 | 114 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/CollectionUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.Chars;
/**
* @author Clément Fournier
*/
class CollectionUtilTest {
@Test
void testJoinOn() {
testJoinOn(listOf("a", "b", "c"), ".",
"a.b.c");
testJoinOn(Collections.emptyList(), ".",
"");
}
private void testJoinOn(List<String> toJoin, String delimiter, String expected) {
String actual = CollectionUtil.joinCharsIntoStringBuilder(
CollectionUtil.map(toJoin, Chars::wrap),
delimiter
).toString();
assertEquals(expected, actual);
}
}
| 938 | 23.710526 | 85 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/IteratorUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static java.util.Collections.emptyIterator;
import static java.util.Collections.emptyList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
class IteratorUtilTest {
@Test
void testAnyMatchPos() {
Iterator<String> iter = iterOf("a", "b", "cd");
boolean match = IteratorUtil.anyMatch(iter, it -> it.length() > 1);
assertTrue(match);
}
@Test
void testAnyMatchNeg() {
Iterator<String> iter = iterOf("a", "b", "");
boolean match = IteratorUtil.anyMatch(iter, it -> it.length() > 1);
assertFalse(match);
}
@Test
void testAnyMatchEmpty() {
Iterator<String> iter = emptyIterator();
boolean match = IteratorUtil.anyMatch(iter, it -> it.length() > 1);
assertFalse(match);
}
@Test
void testAllMatchPos() {
Iterator<String> iter = iterOf("ap", "bcd", "cd");
boolean match = IteratorUtil.allMatch(iter, it -> it.length() > 1);
assertTrue(match);
}
@Test
void testAllMatchNeg() {
Iterator<String> iter = iterOf("a", "bcd", "");
boolean match = IteratorUtil.allMatch(iter, it -> it.length() > 1);
assertFalse(match);
}
@Test
void testAllMatchEmpty() {
Iterator<String> iter = emptyIterator();
boolean match = IteratorUtil.allMatch(iter, it -> it.length() > 1);
assertTrue(match);
}
@Test
void testNoneMatchPos() {
Iterator<String> iter = iterOf("ap", "bcd", "cd");
boolean match = IteratorUtil.noneMatch(iter, it -> it.length() < 1);
assertTrue(match);
}
@Test
void testNoneMatchNeg() {
Iterator<String> iter = iterOf("a", "bcd", "");
boolean match = IteratorUtil.noneMatch(iter, it -> it.length() < 1);
assertFalse(match);
}
@Test
void testNoneMatchEmpty() {
Iterator<String> iter = emptyIterator();
boolean match = IteratorUtil.noneMatch(iter, it -> it.length() < 1);
assertTrue(match);
}
@Test
void testFlatmap() {
Iterator<String> iter = iterOf("ab", "cd", "e", "", "f");
Function<String, Iterator<String>> fun = s -> s.chars().mapToObj(i -> (char) i).map(String::valueOf).iterator();
Iterator<String> mapped = IteratorUtil.flatMap(iter, fun);
assertThat(() -> mapped, contains("a", "b", "c", "d", "e", "f"));
}
@Test
void testFlatmapEmpty() {
Iterator<String> iter = emptyIterator();
Function<String, Iterator<String>> fun = s -> s.chars().mapToObj(i -> (char) i).map(String::valueOf).iterator();
Iterator<String> mapped = IteratorUtil.flatMap(iter, fun);
assertExhausted(mapped);
}
@Test
void testFlatmapEmpty2() {
Iterator<String> iter = iterOf("ab", "cd", "e", "", "f");
Function<String, Iterator<String>> fun = s -> emptyIterator();
Iterator<String> mapped = IteratorUtil.flatMap(iter, fun);
assertExhausted(mapped);
}
@Test
void testFlatmapIsLazy() {
Iterator<String> iter = iterOf("a", "b");
Function<String, Iterator<String>> fun = s -> {
if (s.equals("a")) {
return iterOf("a");
} else {
throw new AssertionError("This statement shouldn't be reached");
}
};
Iterator<String> mapped = IteratorUtil.flatMap(iter, fun);
assertTrue(mapped.hasNext());
assertEquals("a", mapped.next());
assertThrows(AssertionError.class, () -> mapped.hasNext());
}
@Test
void testFlatmapWithSelf() {
Iterator<String> iter = iterOf("ab", "e", null, "f");
Function<String, Iterator<String>> fun = s -> s == null ? null // test null safety
: iterOf(s + "1", s + "2");
Iterator<String> mapped = IteratorUtil.flatMapWithSelf(iter, fun);
assertThat(IteratorUtil.toList(mapped), contains("ab", "ab1", "ab2", "e", "e1", "e2", null, "f", "f1", "f2"));
}
@Test
void testMapNotNull() {
Iterator<String> iter = iterOf("ab", "cdde", "e", "", "f", "fe");
Function<String, Integer> fun = s -> s.length() < 2 ? null : s.length();
Iterator<Integer> mapped = IteratorUtil.mapNotNull(iter, fun);
assertThat(() -> mapped, contains(2, 4, 2));
}
@Test
void testMapNotNullEmpty() {
Iterator<String> iter = emptyIterator();
Function<String, Integer> fun = s -> s.length() < 2 ? null : s.length();
Iterator<Integer> mapped = IteratorUtil.mapNotNull(iter, fun);
assertExhausted(mapped);
}
@Test
void testMapNotNullEmpty2() {
Iterator<String> iter = iterOf("a", "b");
Function<String, Iterator<String>> fun = s -> null;
Iterator<String> mapped = IteratorUtil.flatMap(iter, fun);
assertExhausted(mapped);
}
@Test
void testFilterNotNull() {
Iterator<String> iter = iterOf("ab", null, "e", null, "", "fe");
Iterator<String> mapped = IteratorUtil.filterNotNull(iter);
assertThat(() -> mapped, contains("ab", "e", "", "fe"));
assertExhausted(iter);
}
@Test
void testDistinct() {
Iterator<String> iter = iterOf("ab", null, "e", null, "fe", "ab", "c");
Iterator<String> mapped = IteratorUtil.distinct(iter);
assertThat(() -> mapped, contains("ab", null, "e", "fe", "c"));
assertExhausted(iter);
}
@Test
void testTakeWhile() {
Iterator<String> iter = iterOf("ab", "null", "e", null, "", "fe");
Predicate<String> predicate = Objects::nonNull;
Iterator<String> mapped = IteratorUtil.takeWhile(iter, predicate);
assertThat(() -> mapped, contains("ab", "null", "e"));
assertExhausted(mapped);
}
@Test
void testTakeWhileWithEmpty() {
Iterator<String> iter = iterOf();
Predicate<String> predicate = Objects::nonNull;
Iterator<String> mapped = IteratorUtil.takeWhile(iter, predicate);
assertExhausted(mapped);
}
@Test
void testPeek() {
Iterator<String> iter = iterOf("ab", null, "c");
List<String> seen = new ArrayList<>();
Consumer<String> action = seen::add;
Iterator<String> mapped = IteratorUtil.peek(iter, action);
assertEquals("ab", mapped.next());
assertThat(seen, contains("ab"));
assertNull(mapped.next());
assertThat(seen, contains("ab", null));
assertEquals("c", mapped.next());
assertThat(seen, contains("ab", null, "c"));
assertExhausted(mapped);
}
@Test
void testTakeNegative() {
Iterator<String> iter = iterOf("a", "b", "c");
assertThrows(IllegalArgumentException.class, () -> IteratorUtil.take(iter, -5));
}
@Test
void testTake0() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.take(iter, 0);
assertExhausted(mapped);
}
@Test
void testTake() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.take(iter, 1);
assertThat(() -> mapped, contains("a"));
assertExhausted(mapped);
}
@Test
void testTakeOverflow() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.take(iter, 12);
assertThat(() -> mapped, contains("a", "b", "c"));
assertExhausted(mapped);
}
@Test
void testDropNegative() {
Iterator<String> iter = iterOf("a", "b", "c");
assertThrows(IllegalArgumentException.class, () -> IteratorUtil.advance(iter, -5));
}
@Test
void testDrop0() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.drop(iter, 0);
assertThat(() -> mapped, contains("a", "b", "c"));
assertExhausted(mapped);
}
@Test
void testDrop() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.drop(iter, 1);
assertThat(() -> mapped, contains("b", "c"));
assertExhausted(mapped);
}
@Test
void testDropOverflow() {
Iterator<String> iter = iterOf("a", "b", "c");
Iterator<String> mapped = IteratorUtil.drop(iter, 12);
assertExhausted(mapped);
}
@Test
void testGetNegative() {
Iterator<String> iter = iterOf("a", "b", "c");
assertThrows(IllegalArgumentException.class, () -> IteratorUtil.getNth(iter, -5));
}
@Test
void testGet0() {
Iterator<String> iter = iterOf("a", "b", "c");
String elt = IteratorUtil.getNth(iter, 0);
assertEquals("a", elt);
}
@Test
void testGetNth() {
Iterator<String> iter = iterOf("a", "b", "c");
String elt = IteratorUtil.getNth(iter, 1);
assertEquals("b", elt);
}
@Test
void testGetOverflow() {
Iterator<String> iter = iterOf("a", "b", "c");
String elt = IteratorUtil.getNth(iter, 12);
assertNull(elt);
}
@Test
void testLast() {
Iterator<String> iter = iterOf("a", "b", "c");
String elt = IteratorUtil.last(iter);
assertEquals("c", elt);
assertExhausted(iter);
}
@Test
void testLastEmpty() {
Iterator<String> iter = emptyIterator();
String elt = IteratorUtil.last(iter);
assertNull(elt);
}
@Test
void testCount() {
Iterator<String> iter = iterOf("a", "b", "c");
int size = IteratorUtil.count(iter);
assertEquals(size, 3);
assertExhausted(iter);
}
@Test
void testCountEmpty() {
Iterator<String> iter = emptyIterator();
int size = IteratorUtil.count(iter);
assertEquals(size, 0);
}
@Test
void testToList() {
Iterator<String> iter = iterOf("a", "b", "c");
List<String> lst = IteratorUtil.toList(iter);
assertEquals(lst, listOf("a", "b", "c"));
assertExhausted(iter);
}
@Test
void testAsReversed() {
List<String> iter = listOf("a", "b", "c");
Iterable<String> mapped = IteratorUtil.asReversed(iter);
assertThat(mapped, contains("c", "b", "a"));
}
@Test
void testAsReversedIsRepeatable() {
List<String> iter = listOf("a", "b", "c");
Iterable<String> mapped = IteratorUtil.asReversed(iter);
// doesn't exhaust iterator
assertThat(mapped, contains("c", "b", "a"));
assertThat(mapped, contains("c", "b", "a"));
assertThat(mapped, contains("c", "b", "a"));
}
@Test
void testDropLast() {
Iterator<String> iter = iterOf("ab", "cdde", "e", "", "f", "fe");
Iterator<String> dropped = IteratorUtil.dropLast(iter, 2);
assertEquals(listOf("ab", "cdde", "e", ""), IteratorUtil.toList(dropped));
}
@Test
void testDropLastOne() {
Iterator<String> iter = iterOf("ab", "cdde", "e", "", "f", "fe");
Iterator<String> dropped = IteratorUtil.dropLast(iter, 1);
assertEquals(listOf("ab", "cdde", "e", "", "f"), IteratorUtil.toList(dropped));
}
@Test
void testDropMoreThanSize() {
Iterator<String> iter = iterOf("ab", "c");
Iterator<String> dropped = IteratorUtil.dropLast(iter, 4);
assertEquals(emptyList(), IteratorUtil.toList(dropped));
}
@Test
void testDropLastZero() {
Iterator<String> iter = iterOf("ab", "c");
Iterator<String> dropped = IteratorUtil.dropLast(iter, 0);
assertEquals(listOf("ab", "c"), IteratorUtil.toList(dropped));
}
@Test
void testDropLastNegative() {
Iterator<String> iter = iterOf("ab", "c");
assertThrows(IllegalArgumentException.class, () -> IteratorUtil.dropLast(iter, -3));
}
private void assertExhausted(Iterator<?> mapped) {
assertFalse(mapped.hasNext());
assertThrows(NoSuchElementException.class, () -> mapped.next());
}
static <T> Iterator<T> iterOf(T... ts) {
return Arrays.asList(ts).iterator();
}
static <T> List<T> listOf(T... ts) {
return Arrays.asList(ts);
}
}
| 13,171 | 24.726563 | 120 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.Chars;
class StringUtilTest {
@Test
void testColumnNumber() {
assertEquals(-1, StringUtil.columnNumberAt("f\rah\nb", -1));
assertEquals(1, StringUtil.columnNumberAt("f\rah\nb", 0));
assertEquals(2, StringUtil.columnNumberAt("f\rah\nb", 1));
assertEquals(1, StringUtil.columnNumberAt("f\rah\nb", 2));
assertEquals(2, StringUtil.columnNumberAt("f\rah\nb", 3));
assertEquals(3, StringUtil.columnNumberAt("f\rah\nb", 4));
assertEquals(1, StringUtil.columnNumberAt("f\rah\nb", 5));
assertEquals(2, StringUtil.columnNumberAt("f\rah\nb", 6));
assertEquals(-1, StringUtil.columnNumberAt("f\rah\nb", 7));
}
@Test
void testColumnNumberCrLf() {
assertEquals(-1, StringUtil.columnNumberAt("f\r\nb", -1));
assertEquals(1, StringUtil.columnNumberAt("f\r\nb", 0));
assertEquals(2, StringUtil.columnNumberAt("f\r\nb", 1));
assertEquals(3, StringUtil.columnNumberAt("f\r\nb", 2));
assertEquals(1, StringUtil.columnNumberAt("f\r\nb", 3));
assertEquals(2, StringUtil.columnNumberAt("f\r\nb", 4));
assertEquals(-1, StringUtil.columnNumberAt("f\r\nb", 5));
}
@Test
void testColumnNumberTrailing() {
assertEquals(1, StringUtil.columnNumberAt("\n", 0));
assertEquals(2, StringUtil.columnNumberAt("\n", 1));
assertEquals(-1, StringUtil.columnNumberAt("\n", 2));
}
@Test
void testColumnNumberEmpty() {
assertEquals(1, StringUtil.columnNumberAt("", 0));
assertEquals(-1, StringUtil.columnNumberAt("", 1));
}
@Test
void testRemoveSurrounding() {
assertThat(StringUtil.removeSurrounding("", 'q'), equalTo(""));
assertThat(StringUtil.removeSurrounding("q", 'q'), equalTo("q"));
assertThat(StringUtil.removeSurrounding("qq", 'q'), equalTo(""));
assertThat(StringUtil.removeSurrounding("qqq", 'q'), equalTo("q"));
}
@Test
void testTrimIndent() {
assertTrimIndent(" \n b \n c",
"\nb\nc");
assertTrimIndent(" \nb \n c",
"\nb\n c");
assertTrimIndent(" \n b \n c\n ",
"\nb\nc\n");
assertTrimIndent("", "");
}
private void assertTrimIndent(String input, String output) {
String actual = StringUtil.trimIndent(Chars.wrap(input)).toString();
assertThat(actual, equalTo(output));
}
@Test
void testElide() {
assertThat(StringUtil.elide("abc", 2, ""), equalTo("ab"));
assertThat(StringUtil.elide("abc", 2, "."), equalTo("a."));
assertThat(StringUtil.elide("abc", 2, ".."), equalTo(".."));
assertThat(StringUtil.elide("abc", 3, ".."), equalTo("abc"));
}
@Test
void substringAfterLast() {
assertEquals("abc", StringUtil.substringAfterLast("a.abc", '.'));
assertEquals("abc", StringUtil.substringAfterLast("abc", '.'));
}
}
| 3,334 | 34.105263 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/FooRuleWithLanguageSetInJava.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRule;
public class FooRuleWithLanguageSetInJava extends AbstractRule {
public FooRuleWithLanguageSetInJava() {
setLanguage(DummyLanguageModule.getInstance());
}
@Override
public void apply(Node node, RuleContext ctx) {
// do nothing
}
}
| 580 | 23.208333 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/treeexport/XmlTreeRendererTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.util.treeexport.XmlTreeRenderer.XmlRenderingConfig;
/**
*/
class XmlTreeRendererTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
DummyNode dummyTree1() {
return TreeRenderersTest.dummyTree1(helper);
}
@Test
void testRenderWithAttributes() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strat = new XmlRenderingConfig();
strat.lineSeparator("\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyNode foo='bar' ohio='4'>\n"
+ " <dummyNode o='ha' />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testRenderWithCustomLineSep() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strat = new XmlRenderingConfig();
strat.lineSeparator("\r\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>\r\n"
+ "<dummyNode foo='bar' ohio='4'>\r\n"
+ " <dummyNode o='ha' />\r\n"
+ " <dummyNode />\r\n"
+ "</dummyNode>\r\n", out.toString());
}
@Test
void testRenderWithCustomIndent() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strat = new XmlRenderingConfig().lineSeparator("").indentWith("");
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>"
+ "<dummyNode foo='bar' ohio='4'>"
+ "<dummyNode o='ha' />"
+ "<dummyNode />"
+ "</dummyNode>", out.toString());
}
@Test
void testRenderWithNoAttributes() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strat = new XmlRenderingConfig() {
@Override
public boolean takeAttribute(Node node, Attribute attribute) {
return false;
}
}.lineSeparator("\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyNode>\n"
+ " <dummyNode />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testRenderFilterAttributes() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strategy = new XmlRenderingConfig() {
@Override
public boolean takeAttribute(Node node, Attribute attribute) {
return attribute.getName().equals("ohio");
}
}.lineSeparator("\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(strategy);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyNode ohio='4'>\n"
+ " <dummyNode />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testInvalidAttributeName() throws IOException {
DummyNode dummy = dummyTree1();
dummy.setXPathAttribute("¬AName", "foo");
XmlRenderingConfig config = new XmlRenderingConfig();
config.lineSeparator("\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(config);
StringBuilder out = new StringBuilder();
assertThrows(IllegalArgumentException.class, () -> renderer.renderSubtree(dummy, out));
}
@Test
void testEscapeAttributes() throws IOException {
DummyNode dummy = dummyTree1();
dummy.setXPathAttribute("eh", " 'a &> b\" ");
XmlRenderingConfig strat = new XmlRenderingConfig().lineSeparator("\n");
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyNode eh=' 'a &> b\" ' foo='bar' ohio='4'>\n"
+ " <dummyNode o='ha' />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testEscapeDoubleAttributes() throws IOException {
DummyNode dummy = dummyTree1();
dummy.setXPathAttribute("eh", " 'a &> b\" ");
XmlRenderingConfig strat = new XmlRenderingConfig().lineSeparator("\n").singleQuoteAttributes(false);
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<dummyNode eh=\" 'a &> b" \" foo=\"bar\" ohio=\"4\">\n"
+ " <dummyNode o=\"ha\" />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testNoProlog() throws IOException {
DummyNode dummy = dummyTree1();
XmlRenderingConfig strat = new XmlRenderingConfig().lineSeparator("\n").renderProlog(false);
XmlTreeRenderer renderer = new XmlTreeRenderer(strat);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<dummyNode foo='bar' ohio='4'>\n"
+ " <dummyNode o='ha' />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
@Test
void testDefaultLineSep() throws IOException {
DummyNode dummy = dummyTree1();
XmlTreeRenderer renderer = new XmlTreeRenderer();
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummy, out);
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>" + System.lineSeparator()
+ "<dummyNode foo='bar' ohio='4'>" + System.lineSeparator()
+ " <dummyNode o='ha' />" + System.lineSeparator()
+ " <dummyNode />" + System.lineSeparator()
+ "</dummyNode>" + System.lineSeparator(), out.toString());
}
}
| 7,976 | 29.918605 | 109 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/treeexport/TreeRenderersTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.properties.PropertySource;
/**
*
*/
class TreeRenderersTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@Test
void testStandardRenderersAreRegistered() {
assertEquals(TreeRenderers.XML, TreeRenderers.findById(TreeRenderers.XML.id()));
}
@Test
void testXmlPropertiesAvailable() {
PropertySource properties = TreeRenderers.XML.newPropertyBundle();
assertThat(properties.getPropertyDescriptors(),
containsInAnyOrder(TreeRenderers.XML_LINE_SEPARATOR,
TreeRenderers.XML_RENDER_COMMON_ATTRIBUTES,
TreeRenderers.XML_RENDER_PROLOG,
TreeRenderers.XML_USE_SINGLE_QUOTES));
}
@Test
void testXmlDescriptorDump() throws IOException {
PropertySource bundle = TreeRenderers.XML.newPropertyBundle();
bundle.setProperty(TreeRenderers.XML_RENDER_PROLOG, false);
bundle.setProperty(TreeRenderers.XML_USE_SINGLE_QUOTES, false);
bundle.setProperty(TreeRenderers.XML_LINE_SEPARATOR, "\n");
TreeRenderer renderer = TreeRenderers.XML.produceRenderer(bundle);
StringBuilder out = new StringBuilder();
renderer.renderSubtree(dummyTree1(helper), out);
assertEquals("<dummyNode foo=\"bar\" ohio=\"4\">\n"
+ " <dummyNode o=\"ha\" />\n"
+ " <dummyNode />\n"
+ "</dummyNode>\n", out.toString());
}
static DummyNode dummyTree1(DummyParsingHelper helper) {
DummyNode dummy = helper.parse("(parent(child1)(child2))").getChild(0);
dummy.clearXPathAttributes();
dummy.setXPathAttribute("foo", "bar");
dummy.setXPathAttribute("ohio", "4");
DummyNode dummy1 = dummy.getChild(0);
dummy1.clearXPathAttributes();
dummy1.setXPathAttribute("o", "ha");
dummy.getChild(1).clearXPathAttributes();
return dummy;
}
}
| 2,759 | 30.724138 | 120 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/database/ResourceResolverTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.xml.transform.Source;
import org.junit.jupiter.api.Test;
/**
*
* @author sturton
*/
class ResourceResolverTest {
/**
* Test of resolve method, of class ResourceResolver.
*/
@Test
void testResolve() throws Exception {
System.out.println("resolve");
String href = "";
String base = "";
ResourceResolver instance = new ResourceResolver();
Source expResult = null;
Source result = instance.resolve(href, base);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
}
| 885 | 23.611111 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/database/DBTypeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.ResourceBundle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
*
* @author sturton
*/
class DBTypeTest {
private File absoluteFile;
private Properties testProperties;
private Properties includeProperties;
@TempDir
private Path folder;
@BeforeEach
void setUp() throws Exception {
testProperties = new Properties();
testProperties.put("prop1", "value1");
testProperties.put("prop2", "value2");
testProperties.put("prop3", "value3");
includeProperties = new Properties();
includeProperties.putAll(testProperties);
includeProperties.put("prop3", "include3");
absoluteFile = folder.resolve("dbtypetest.properties").toFile();
try (FileOutputStream fileOutputStream = new FileOutputStream(absoluteFile);
PrintStream printStream = new PrintStream(fileOutputStream)) {
for (Entry<?, ?> entry : testProperties.entrySet()) {
printStream.printf("%s=%s\n", entry.getKey(), entry.getValue());
}
}
}
@AfterEach
void tearDown() throws Exception {
testProperties = null;
}
/**
* Test of getProperties method, of class DBType.
*/
@Test
void testGetPropertiesFromFile() throws Exception {
System.out.println("getPropertiesFromFile");
DBType instance = new DBType(absoluteFile.getAbsolutePath());
Properties expResult = testProperties;
Properties result = instance.getProperties();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getProperties method, of class DBType.
*/
@Test
void testGetProperties() throws Exception {
System.out.println("testGetProperties");
DBType instance = new DBType("test");
Properties expResult = testProperties;
System.out.println("testGetProperties: expected results " + testProperties);
Properties result = instance.getProperties();
System.out.println("testGetProperties: actual results " + result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getProperties method, of class DBType.
*/
@Test
void testGetIncludeProperties() throws Exception {
System.out.println("testGetIncludeProperties");
DBType instance = new DBType("include");
Properties expResult = includeProperties;
System.out.println("testGetIncludeProperties: expected results " + includeProperties);
Properties result = instance.getProperties();
System.out.println("testGetIncludeProperties: actual results " + result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getResourceBundleAsProperties method, of class DBType.
*/
@Test
void testAsProperties() {
System.out.println("asProperties");
ResourceBundle bundle = ResourceBundle.getBundle(DBType.class.getPackage().getName() + ".test");
Properties expResult = testProperties;
Properties result = DBType.getResourceBundleAsProperties(bundle);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
}
| 4,180 | 32.448 | 104 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/database/DBMSMetadataTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.io.Reader;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author sturton
*/
@Disabled
class DBMSMetadataTest {
private static final Logger LOG = LoggerFactory.getLogger(DBMSMetadataTest.class);
static final String C_ORACLE_THIN_1 = "jdbc:oracle:thin:scott/tiger@//192.168.100.21:5521/customer_db?characterset=utf8&schemas=scott,hr,sh,system&objectTypes=procedures,functions,triggers,package,types&languages=plsql,java&name=PKG_%25%7C%7CPRC_%25";
static final String C_ORACLE_THIN_3 = "jdbc:oracle:thin:scott/oracle@//192.168.100.21:1521/orcl?characterset=utf8&schemas=scott,hr,sh,system&objectTypes=procedures,functions,triggers,package,types&languages=plsql,java&name=PKG_%25%7C%7CPRC_%25";
static final String C_ORACLE_THIN_4 = "jdbc:oracle:thin:system/oracle@//192.168.100.21:1521/ORCL?characterset=utf8&schemas=scott,hr,sh,system&objectTypes=procedures,functions,triggers,package,types&languages=plsql,java&name=PKG_%25%7C%7CPRC_%25";
static final String C_ORACLE_THIN_5 = "jdbc:oracle:thin:@//192.168.100.21:1521/ORCL?characterset=utf8&schemas=scott,hr,sh,system&objectTypes=procedures,functions,triggers,package,types&languages=plsql,java&name=PKG_%25%7C%7CPRC_%25&user=system&password=oracle";
/**
* URI with minimum information, relying on defaults in
* testdefaults.properties
*/
static final String C_TEST_DEFAULTS = "jdbc:oracle:testdefault://192.168.100.21:1521/ORCL";
private DBURI dbURI;
private DBURI dbURI4;
private DBURI dbURI5;
private DBURI dbURIDefault;
DBMSMetadataTest() throws URISyntaxException, Exception {
dbURI = new DBURI(C_ORACLE_THIN_3);
dbURI4 = new DBURI(C_ORACLE_THIN_4);
dbURI5 = new DBURI(C_ORACLE_THIN_5);
dbURIDefault = new DBURI(C_TEST_DEFAULTS);
}
/**
* Convert Readers to Strings for eay output and comparison.
*/
private static String getStringFromReader(Reader reader) throws IOException {
StringBuilder stringBuilder = new StringBuilder(1024);
char[] charArray = new char[1024];
int readChars;
while ((readChars = reader.read(charArray)) > 0) {
System.out.println("Reader.read(CharArray)==" + readChars);
stringBuilder.append(charArray, 0, readChars);
}
reader.close();
return stringBuilder.toString();
}
/**
* Dump ResultSet
*/
private static void dumpResultSet(ResultSet resultSet, String description) {
try {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
System.out.format("ResultSet \"%s\" has %d columns and contains ...\n[", description, columnCount);
/*
* Walk through the column names, writing out a header line
*/
for (int columnNumber = 1; columnNumber <= columnCount; columnNumber++) {
System.out.format("%s%s", ((columnNumber > 1) ? "," : ""), metaData.getColumnName(columnNumber));
}
System.out.format("\n");
// Output each row
while (resultSet.next()) {
/*
* Walk through the columns of this row, writing out a row line
*/
for (int columnNumber = 1; columnNumber <= columnCount; columnNumber++) {
System.out.format("%s%s", ((columnNumber > 0) ? "," : ""), resultSet.getString(columnNumber));
}
System.out.format("\n");
}
} catch (SQLException ex) {
LOG.error(ex.getMessage(), ex);
}
System.out.format("...\n]\n");
}
/**
* Verify getConnection method, of class DBMSMetadata.
*/
@Test
void testGetConnection() throws Exception {
System.out.println("getConnection");
String driverClass = dbURI.getDriverClass();
System.out.println("driverClass==" + driverClass);
System.out.println("URL==" + dbURI.getURL());
Class.forName(driverClass);
Object object = DriverManager.getDriver(dbURI.getURL());
// Object object = DriverManager.getDriver(C_ORACLE_OCI_3) ;
Properties properties = new Properties();
properties.put("user", "system");
properties.put("password", "oracle");
Connection expResult = DriverManager.getDriver(dbURI.getURL()).connect(dbURI.getURL(), properties);
DBMSMetadata instance = new DBMSMetadata(dbURI);
Connection result = instance.getConnection();
assertNotNull(result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify getConnection method, of class DBMSMetadata.
*/
@Test
void testGetConnectionWithConnectionParameters() throws Exception {
System.out.println("getConnection");
String driverClass = dbURI5.getDriverClass();
System.out.println("driverClass==" + driverClass);
System.out.println("URL==" + dbURI5.getURL());
Class.forName(driverClass);
Object object = DriverManager.getDriver(dbURI5.getURL());
// Object object = DriverManager.getDriver(C_ORACLE_OCI_3) ;
Properties properties = new Properties();
properties.putAll(dbURI5.getParameters());
Connection expResult = DriverManager.getDriver(dbURI5.getURL()).connect(dbURI5.getURL(), properties);
DBMSMetadata instance = new DBMSMetadata(dbURI5);
Connection result = instance.getConnection();
assertNotNull(result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSourceCode method, of class DBMSMetadata.
*/
@Test
void testGetSourceCode() throws Exception {
System.out.println("getSourceCode");
// String objectType = "PACKAGE";
// String name = "DBMS_REPCAT_AUTH";
// String schema = "SYSTEM";
String objectType = "TABLE";
String name = "EMP";
String schema = "SCOTT";
System.out.println("dbURI.driverClass==" + dbURI.getDriverClass());
System.out.println("dbURI.URL==" + dbURI.getURL());
System.out.println("dbURI.getDBType.getProperties()==" + dbURI.getDbType().getProperties());
System.out.println("dbURI.getDBType.getSourceCodeReturnType()==" + dbURI.getDbType().getSourceCodeReturnType());
System.out.println("dbURI.getDBType.getProperties()=="
+ dbURI.getDbType().getProperties().getProperty("getSourceCodeStatement"));
DBMSMetadata instance = new DBMSMetadata(dbURI);
Reader expResult = null;
Reader result = instance.getSourceCode(objectType, name, schema);
/*
* StringBuilder stringBuilder = new StringBuilder(1024); char[]
* charArray = new char[1024]; int readChars = 0; while(( readChars =
* result.read(charArray)) > 0 ) {
* System.out.println("Reader.read(CharArray)=="+readChars);
* stringBuilder.append(charArray, 0, readChars); } result.close();
*
* System.out.println("getSourceCode()==\""+stringBuilder.toString()+
* "\"" );
*
* assertTrue(stringBuilder.toString().startsWith("\n CREATE "));
*/
String resultString = getStringFromReader(result);
System.out.println("getSourceCode()==\"" + resultString);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify getSchemas method, of class DBMSMetadata.
*/
@Test
void testGetSchemas() throws Exception {
System.out.println("getSchemas");
DBURI testURI = dbURI4;
String driverClass = testURI.getDriverClass();
System.out.println("driverClass==" + driverClass);
System.out.println("URL==" + testURI.getURL());
Class.forName(driverClass);
Object object = DriverManager.getDriver(testURI.getURL());
// Object object = DriverManager.getDriver(C_ORACLE_OCI_3) ;
Properties properties = new Properties();
properties.put("user", "system");
properties.put("password", "oracle");
Connection expResult = DriverManager.getDriver(testURI.getURL()).connect(testURI.getURL(), properties);
DBMSMetadata instance = new DBMSMetadata(testURI);
Connection result = instance.getConnection();
assertNotNull(result);
ResultSet allSchemas = result.getMetaData().getSchemas();
dumpResultSet(allSchemas, "All Schemas");
ResultSet allCatalogues = result.getMetaData().getCatalogs();
dumpResultSet(allCatalogues, "All Catalogues");
String catalog = null;
String schemasPattern = "PHPDEMO";
String tablesPattern = null;
String proceduresPattern = null;
// Not until Java6 ResultSet matchedSchemas =
// result.getMetaData().getSchemas(catalog, schemasPattern) ;
// Not until Java6 dumpResultSet (matchedSchemas, "Matched Schemas") ;
ResultSet matchedTables = result.getMetaData().getTables(catalog, schemasPattern, tablesPattern, null);
dumpResultSet(matchedTables, "Matched Tables");
ResultSet matchedProcedures = result.getMetaData().getProcedures(catalog, schemasPattern, proceduresPattern);
dumpResultSet(matchedProcedures, "Matched Procedures");
System.out.format("testURI=%s,\ngetParameters()=%s\n", C_ORACLE_THIN_4, testURI.getParameters());
System.out.format(
"testURI=%s,\ngetSchemasList()=%s\n,getSourceCodeTypesList()=%s\n,getSourceCodeNmesList()=%s\n",
testURI, testURI.getSchemasList(), testURI.getSourceCodeTypesList(), testURI.getSourceCodeNamesList());
}
/**
* Verify getSchemas method, of class DBMSMetadata.
*/
@Test
void testGetSourceObjectList() throws Exception {
System.out.println("getConnection");
DBURI testURI = dbURI4;
String driverClass = testURI.getDriverClass();
System.out.println("driverClass==" + driverClass);
System.out.println("URL==" + testURI.getURL());
Class.forName(driverClass);
Object object = DriverManager.getDriver(testURI.getURL());
// Object object = DriverManager.getDriver(C_ORACLE_OCI_3) ;
Properties properties = new Properties();
properties.put("user", "system");
properties.put("password", "oracle");
Connection expResult = DriverManager.getDriver(testURI.getURL()).connect(testURI.getURL(), properties);
DBMSMetadata instance = new DBMSMetadata(testURI);
Connection result = instance.getConnection();
assertNotNull(result);
List<SourceObject> sourceObjectList = instance.getSourceObjectList();
assertNotNull(sourceObjectList);
System.out.format("testURI=%s,\ngetParameters()=%s\n", C_ORACLE_THIN_4, testURI.getParameters());
System.out.format(
"testURI=%s,\ngetSchemasList()=%s\n,getSourceCodeTypesList()=%s\n,getSourceCodeNmesList()=%s\n",
testURI, testURI.getSchemasList(), testURI.getSourceCodeTypesList(), testURI.getSourceCodeNamesList());
System.out.print("sourceObjectList ...\n");
for (SourceObject sourceObject : sourceObjectList) {
System.out.printf("sourceObject=%s\n", sourceObject);
System.out.printf("sourceCode=[%s]\n", getStringFromReader(instance.getSourceCode(sourceObject)));
}
}
}
| 12,302 | 41.133562 | 273 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/database/ResourceLoaderTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.InputStream;
import org.junit.jupiter.api.Test;
/**
*
* @author sturton
*/
class ResourceLoaderTest {
/**
* Test of getResourceStream method, of class ResourceLoader.
*/
@Test
void testGetResourceStream() throws Exception {
System.out.println("getResourceStream");
String path = "";
ResourceLoader instance = new ResourceLoader();
InputStream expResult = null;
InputStream result = instance.getResourceStream(path);
assertNotNull(result);
// assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
}
| 923 | 24.666667 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/database/DBURITest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
/**
*
* @author sturton
*/
class DBURITest {
/**
* URI with minimum information, relying on defaults in
* testdefaults.properties
*/
static final String C_TEST_DEFAULTS = "jdbc:oracle:testdefault://192.168.100.21:1521/ORCL";
/*
* Expected values from testdefaults.properties
*/
static final String C_DEFAULT_USER = "scott";
static final String C_DEFAULT_PASSWORD = "tiger";
static final String C_DEFAULT_LANGUAGES = "java,plsql";
static final String C_DEFAULT_SCHEMAS = "scott,system";
static final String C_DEFAULT_SOURCE_CODE_TYPES = "table,view";
static final String C_DEFAULT_SOURCE_CODE_NAMES = "emp,dept";
static final String C_DEFAULT_CHARACTERSET = "utf8";
/**
* Fully specified URI, overriding defaults in testdefaults.properties
*/
static final String C_TEST_EXPLICIT = "jdbc:oracle:testdefault:system/oracle@//192.168.100.21:1521/ORCL?characterset=us7ascii&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java&sourcecodenames=PKG_%25%25,PRC_%25%25";
/*
* Expected values from testdefaults.properties, with values overridden by
* URI query parameters
*/
static final String C_EXPLICIT_USER = "system";
static final String C_EXPLICIT_PASSWORD = "oracle";
static final String C_EXPLICIT_LANGUAGES = "plsql,java";
static final String C_EXPLICIT_SCHEMAS = "scott,hr,sh,system";
static final String C_EXPLICIT_SOURCE_CODE_TYPES = "procedures,functions,triggers,package,types";
static final String C_EXPLICIT_SOURCE_CODE_NAMES = "PKG_%%,PRC_%%";
static final String C_EXPLICIT_CHARACTERSET = "us7ascii";
static final String C_TEST_URI = "test?param1=x%261¶m2=¶m3=";
static final String C_ORACLE_OCI_1 = "jdbc:oracle:oci:system/oracle@//192.168.100.21:1521/ORCL";
static final String C_ORACLE_OCI_2 = "jdbc:oracle:oci:system/oracle@//192.168.100.21:1521/ORCL?characterset=utf8&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java";
static final String C_ORACLE_OCI_3 = "jdbc:oracle:oci:system/oracle@//myserver.com:1521/customer_db?characterset=utf8&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java&sourcecodenames=PKG_%25%25,PRC_%25%25";
static final String C_ORACLE_THIN_1 = "jdbc:oracle:thin:system/oracle@//192.168.100.21:1521/ORCL";
static final String C_ORACLE_THIN_2 = "jdbc:oracle:thin:system/oracle@//192.168.100.21:1521/ORCL?characterset=utf8&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java";
static final String C_ORACLE_THIN_3 = "jdbc:oracle:thin:system/oracle@//myserver.com:1521/customer_db?characterset=utf8&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java&sourcecodenames=PKG_%25%25,PRC_%25%25";
static final String C_POSTGRES_1 = "jdbc:postgresql://host/database";
static final String C_HTTP = "http://localhost:80?characterset=utf8&schemas=scott,hr,sh,system&sourcecodetypes=procedures,functions,triggers,package,types&languages=plsql,java";
static void dump(String description, URI dburi) {
System.err.printf(
"Test %s\n: isOpaque=%s, isAbsolute=%s Scheme=%s,\n SchemeSpecificPart=%s,\n Host=%s,\n Port=%s,\n Path=%s,\n Fragment=%s,\n Query=%s\n",
description, dburi.isOpaque(), dburi.isAbsolute(), dburi.getScheme(), dburi.getSchemeSpecificPart(),
dburi.getHost(), dburi.getPort(), dburi.getPath(), dburi.getFragment(), dburi.getQuery());
String query = dburi.getQuery();
if (null != query && !"".equals(query)) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<>();
for (String param : params) {
String[] splits = param.split("=");
String name = splits[0];
String value = null;
if (splits.length > 1) {
value = splits[1];
}
map.put(name, value);
System.err.printf("name=%s,value=%s\n", name, value);
}
}
// return map;
}
/**
* Test of dump method, of class DBURI.
*/
@Test
void testDump() throws URISyntaxException, Exception {
System.out.println("dump");
String description = "";
DBURI dburi = new DBURI(C_TEST_URI);
DBURI.dump(description, dburi.getUri());
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getUri method, of class DBURI.
*/
@Test
void testGetUri() throws URISyntaxException, Exception {
System.out.println("getUri");
DBURI instance = new DBURI(C_ORACLE_OCI_1);
URI expResult = new URI(C_ORACLE_OCI_1);
URI result = instance.getUri();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setUri method, of class DBURI.
*/
@Test
void testSetUri() throws URISyntaxException, Exception {
System.out.println("setUri");
URI uri = new URI(C_ORACLE_OCI_1);
DBURI instance = new DBURI(C_TEST_URI);
instance.setUri(uri);
assertEquals(uri, instance.getUri());
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getDbType method, of class DBURI.
*/
@Test
void testGetDbType() throws URISyntaxException, Exception {
System.out.println("getDbType");
DBURI instance = new DBURI(C_POSTGRES_1);
DBType expResult = new DBType("postgresql");
DBType result = instance.getDbType();
// assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getDbType method, of class DBURI.
*/
@Test
void testGetDbType2() throws URISyntaxException, Exception {
System.out.println("getDbType");
DBURI instance = new DBURI(C_ORACLE_OCI_1);
DBType expResult = new DBType("oci");
DBType result = instance.getDbType();
// assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setDbType method, of class DBURI.
*/
@Test
void testSetDbType() throws URISyntaxException, Exception {
System.out.println("setDbType");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
DBType dbType = new DBType("postgresql");
instance.setDbType(dbType);
assertEquals(dbType, instance.getDbType());
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSchemasList method, of class DBURI.
*/
@Test
void testGetSchemasList() throws URISyntaxException, Exception {
System.out.println("getSchemasList");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
List<String> expResult;
expResult = Arrays.asList("scott,hr,sh,system".split(","));
List<String> result = instance.getSchemasList();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSchemasList method, of class DBURI.
*/
@Test
void testSetSchemasList() throws URISyntaxException, Exception {
System.out.println("setSchemasList");
List<String> schemasList = Arrays.asList("scott,hr,sh,system".split(","));
DBURI instance = new DBURI(C_ORACLE_OCI_1);
instance.setSchemasList(schemasList);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSourceCodeTypesList method, of class DBURI.
*/
@Test
void testGetSourceCodeTypesList() throws URISyntaxException, Exception {
System.out.println("getSourceCodeTypesList");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
List<String> expResult = Arrays.asList("procedures,functions,triggers,package,types".split(","));
List<String> result = instance.getSourceCodeTypesList();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSourceCodeTypesList method, of class DBURI.
*/
@Test
void testSetSourceCodeTypesList() throws URISyntaxException, Exception {
System.out.println("setSourceCodeTypesList");
List<String> sourcecodetypesList = Arrays.asList("procedures,functions,triggers,package,types".split(","));
DBURI instance = new DBURI(C_ORACLE_OCI_1);
instance.setSourceCodeTypesList(sourcecodetypesList);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSourceCodeNamesList method, of class DBURI.
*/
@Test
void testGetSourceCodeNamesList() throws URISyntaxException, Exception {
System.out.println("getSourceCodeNamesList");
DBURI instance = new DBURI(C_ORACLE_OCI_3);
List<String> expResult = Arrays.asList("PKG_%%,PRC_%%".split(","));
List<String> result = instance.getSourceCodeNamesList();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSourceCodeNamesList method, of class DBURI.
*/
@Test
void testSetSourceCodeNamesList() throws URISyntaxException, Exception {
System.out.println("setSourceCodeNamesList");
List<String> sourceCodeNamesList = Arrays.asList("PKG_%%,TRG_%%".split(","));
DBURI instance = new DBURI(C_ORACLE_OCI_2);
instance.setSourceCodeNamesList(sourceCodeNamesList);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getLanguagesList method, of class DBURI.
*/
@Test
void testGetLanguagesList() throws URISyntaxException, Exception {
System.out.println("getLanguagesList");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
List<String> expResult = Arrays.asList("plsql,java".split(","));
List<String> result = instance.getLanguagesList();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setLanguagesList method, of class DBURI.
*/
@Test
void testSetLanguagesList() throws URISyntaxException, Exception {
System.out.println("setLanguagesList");
List<String> languagesList = Arrays.asList("plsql,java".split(","));
DBURI instance = new DBURI(C_ORACLE_OCI_2);
instance.setLanguagesList(languagesList);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getDriverClass method, of class DBURI.
*/
@Test
void testGetDriverClass() throws URISyntaxException, Exception {
System.out.println("getDriverClass");
DBURI instance = new DBURI(C_ORACLE_OCI_1);
String expResult = "oracle.jdbc.OracleDriver";
String result = instance.getDriverClass();
System.out.println("testGetDriverClass: driverClass=" + result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getDriverClass method, of class DBURI.
*/
@Test
void testGetThinDriverClass() throws URISyntaxException, Exception {
System.out.println("getThinDriverClass");
DBURI instance = new DBURI(C_ORACLE_THIN_1);
String expResult = "oracle.jdbc.OracleDriver";
String result = instance.getDriverClass();
System.out.println("testGetThinDriverClass: driverClass=" + result);
System.out.println("testGetThinDriverClass: getDbType().getProperties() follows");
System.out
.println("testGetThinDriverClass: getDbType().getProperties()=" + instance.getDbType().getProperties());
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setDriverClass method, of class DBURI.
*/
@Test
void testSetDriverClass() throws URISyntaxException, Exception {
System.out.println("setDriverClass");
String driverClass = "oracle.jdbc.driver.OracleDriver";
DBURI instance = new DBURI(C_ORACLE_OCI_1);
instance.setDriverClass(driverClass);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getCharacterSet method, of class DBURI.
*/
@Test
void testGetCharacterSet() throws URISyntaxException, Exception {
System.out.println("getCharacterSet");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
String expResult = "utf8";
String result = instance.getCharacterSet();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setCharacterSet method, of class DBURI.
*/
@Test
void testSetCharacterSet() throws URISyntaxException, Exception {
System.out.println("setCharacterSet");
String characterSet = "utf8";
DBURI instance = new DBURI(C_POSTGRES_1);
instance.setCharacterSet(characterSet);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSourceCodeType method, of class DBURI.
*/
@Test
void testGetSourceCodeType() throws URISyntaxException, Exception {
System.out.println("getSourceCodeType");
DBURI instance = new DBURI(C_ORACLE_OCI_1);
int expResult = 2005; // CLOB
int result = instance.getSourceCodeType();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSourceCodeType method, of class DBURI.
*/
@Test
void testSetSourceCodeType() throws URISyntaxException, Exception {
System.out.println("setSourceCodeType");
int sourceCodeType = 5;
DBURI instance = new DBURI(C_ORACLE_OCI_1);
instance.setSourceCodeType(sourceCodeType);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSubprotocol method, of class DBURI.
*/
@Test
void testGetSubprotocol() throws URISyntaxException, Exception {
System.out.println("getSubprotocol");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
String expResult = "oracle";
String result = instance.getSubprotocol();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSubprotocol method, of class DBURI.
*/
@Test
void testSetSubprotocol() throws URISyntaxException, Exception {
System.out.println("setSubprotocol");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
String subprotocol = "oracle";
instance.setSubprotocol(subprotocol);
String result = instance.getSubprotocol();
assertEquals(subprotocol, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getSubnamePrefix method, of class DBURI.
*/
@Test
void testGetSubnamePrefix() throws URISyntaxException, Exception {
System.out.println("getSubnamePrefix");
DBURI instance = new DBURI(C_ORACLE_OCI_2);
String expResult = "oci";
String result = instance.getSubnamePrefix();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setSubnamePrefix method, of class DBURI.
*/
@Test
void testSetSubnamePrefix() throws URISyntaxException, Exception {
System.out.println("setSubnamePrefix");
String subnamePrefix = "oci8";
DBURI instance = new DBURI(C_ORACLE_OCI_2);
instance.setSubnamePrefix(subnamePrefix);
String result = instance.getSubnamePrefix();
assertEquals(subnamePrefix, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of getParameters method, of class DBURI.
*/
@Test
void testGetParameters() throws URISyntaxException, Exception {
System.out.println("getParameters");
DBURI instance = new DBURI(C_TEST_URI);
Map<String, String> expResult = new HashMap<>();
expResult.put("param1", "x&1");
expResult.put("param2", null);
expResult.put("param3", null);
Map<String, String> result = instance.getParameters();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Test of setParameters method, of class DBURI.
*/
@Test
void testSetParameters() throws URISyntaxException, Exception {
System.out.println("setParameters");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "x%FFF");
parameters.put("param2", "IAmParameter2");
parameters.put("param3", "IAmParameter3");
DBURI instance = new DBURI(C_TEST_URI);
instance.setParameters(parameters);
// TODO review the generated test code and remove the default call to
// fail.
assertEquals(parameters, instance.getParameters());
}
/**
* Verify that default languages are returned if non are provided in the
* DBURI.
*/
@Test
void testDefaultLanguagesList() throws URISyntaxException, Exception {
System.out.println("testDefaultLanguagesList");
List<String> defaultLanguagesList = Arrays.asList(C_DEFAULT_LANGUAGES.split(","));
DBURI instance = new DBURI(C_TEST_DEFAULTS);
List<String> result = instance.getLanguagesList();
assertEquals(defaultLanguagesList, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify that default CharacterSet are returned if non are provided in the
* DBURI.
*/
@Test
void testDefaultCharacterSet() throws URISyntaxException, Exception {
System.out.println("testDefaultCharacterSet");
DBURI instance = new DBURI(C_TEST_DEFAULTS);
String result = instance.getCharacterSet();
assertEquals(C_DEFAULT_CHARACTERSET, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify that default languages are returned if non are provided in the
* DBURI.
*/
@Test
void testDefaultSchemasList() throws URISyntaxException, Exception {
System.out.println("testDefaultSchemasList");
List<String> defaultSchemasList = Arrays.asList(C_DEFAULT_SCHEMAS.split(","));
DBURI instance = new DBURI(C_TEST_DEFAULTS);
List<String> result = instance.getSchemasList();
assertEquals(defaultSchemasList, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify that default Source Code Types are returned if non are provided in
* the DBURI.
*/
@Test
void testDefaultSourceCodeTypesList() throws URISyntaxException, Exception {
System.out.println("testDefaultSourceCodeTypesList");
List<String> defaultSourceCodeTypesList = Arrays.asList(C_DEFAULT_SOURCE_CODE_TYPES.split(","));
DBURI instance = new DBURI(C_TEST_DEFAULTS);
List<String> result = instance.getSourceCodeTypesList();
assertEquals(defaultSourceCodeTypesList, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify that default languages are returned if non are provided in the
* DBURI.
*/
@Test
void testDefaultSourceCodeNamesList() throws URISyntaxException, Exception {
System.out.println("testDefaultSourceCodeNamesList");
List<String> defaultSourceCodeNamesList = Arrays.asList(C_DEFAULT_SOURCE_CODE_NAMES.split(","));
DBURI instance = new DBURI(C_TEST_DEFAULTS);
List<String> result = instance.getSourceCodeNamesList();
assertEquals(defaultSourceCodeNamesList, result);
// TODO review the generated test code and remove the default call to
// fail.
// fail("The test case is a prototype.");
}
/**
* Verify that languages are returned if provided in the DBURI.
*/
@Test
void testExplicitLanguagesList() throws URISyntaxException, Exception {
System.out.println("testExplicitLanguagesList");
List<String> defaultLanguagesList = Arrays.asList(C_EXPLICIT_LANGUAGES.split(","));
DBURI instance = new DBURI(C_TEST_EXPLICIT);
List<String> result = instance.getLanguagesList();
assertEquals(defaultLanguagesList, result);
// TODO review the generated test code and remove the call to fail.
// fail("The test case is a prototype.");
}
/**
* Verify that CharacterSet are returned if provided in the DBURI.
*/
@Test
void testExplicitCharacterSet() throws URISyntaxException, Exception {
System.out.println("testExplicitCharacterSet");
DBURI instance = new DBURI(C_TEST_EXPLICIT);
String result = instance.getCharacterSet();
assertEquals(C_EXPLICIT_CHARACTERSET, result);
// TODO review the generated test code and remove the call to fail.
// fail("The test case is a prototype.");
}
/**
* Verify that languages are returned if provided in the DBURI.
*/
@Test
void testExplicitSchemasList() throws URISyntaxException, Exception {
System.out.println("testExplicitSchemasList");
List<String> defaultSchemasList = Arrays.asList(C_EXPLICIT_SCHEMAS.split(","));
DBURI instance = new DBURI(C_TEST_EXPLICIT);
List<String> result = instance.getSchemasList();
assertEquals(defaultSchemasList, result);
// TODO review the generated test code and remove the call to fail.
// fail("The test case is a prototype.");
}
/**
* Verify that Source Code Types are returned if provided in the DBURI.
*/
@Test
void testExplicitSourceCodeTypesList() throws URISyntaxException, Exception {
System.out.println("testExplicitSourceCodeTypesList");
List<String> defaultSourceCodeTypesList = Arrays.asList(C_EXPLICIT_SOURCE_CODE_TYPES.split(","));
DBURI instance = new DBURI(C_TEST_EXPLICIT);
List<String> result = instance.getSourceCodeTypesList();
assertEquals(defaultSourceCodeTypesList, result);
// TODO review the generated test code and remove the call to fail.
// fail("The test case is a prototype.");
}
/**
* Verify that languages are returned if provided in the DBURI.
*/
@Test
void testExplicitSourceCodeNamesList() throws URISyntaxException, Exception {
System.out.println("testExplicitSourceCodeNamesList");
List<String> defaultSourceCodeNamesList = Arrays.asList(C_EXPLICIT_SOURCE_CODE_NAMES.split(","));
DBURI instance = new DBURI(C_TEST_EXPLICIT);
List<String> result = instance.getSourceCodeNamesList();
assertEquals(defaultSourceCodeNamesList, result);
// TODO review the generated test code and remove the call to fail.
// fail("The test case is a prototype.");
}
}
| 26,277 | 38.220896 | 277 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/FileDataSourceTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class FileDataSourceTest {
@TempDir
private Path tempFolder;
private static final String SOMEFILE_DIR = "path/";
private static final String SOMEFILE_TXT = "somefile.txt";
private static final String SOMEFILE_TXT_FULL_PATH = SOMEFILE_DIR + SOMEFILE_TXT;
private FileDataSource ds;
private File someFile;
private File someFolder;
@BeforeEach
void setup() throws IOException {
someFolder = tempFolder.resolve(SOMEFILE_DIR).toFile();
assertTrue(someFolder.mkdir());
someFile = tempFolder.resolve(SOMEFILE_TXT_FULL_PATH).toFile();
ds = new FileDataSource(someFile);
}
@Test
void testShortNamesSingleFile() {
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, someFile.getAbsolutePath()));
}
@Test
void testShortNamesSingleDir() {
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, someFolder.getAbsolutePath()));
}
@Test
void testShortNamesNullBase() {
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, null));
}
@Test
void testShortNamesCommaSeparatedDirs() {
// use 2 dirs, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, SOMEFILE_DIR + "," + someFolder.getAbsolutePath()));
}
@Test
void testShortNamesCommaSeparatedFiles() {
// use 2 files, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, SOMEFILE_TXT_FULL_PATH + "," + someFile.getAbsolutePath()));
}
@Test
void testShortNamesCommaSeparatedMixed() {
// use a file and a dir, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(SOMEFILE_TXT, ds.getNiceFileName(true, SOMEFILE_TXT_FULL_PATH + "," + someFolder.getAbsolutePath()));
}
@Test
void testLongNamesSingleFile() throws IOException {
assertEquals(someFile.getCanonicalFile().getAbsolutePath(), ds.getNiceFileName(false, someFile.getAbsolutePath()));
}
@Test
void testLongNamesSingleDir() throws IOException {
assertEquals(someFile.getCanonicalFile().getAbsolutePath(), ds.getNiceFileName(false, someFolder.getAbsolutePath()));
}
@Test
void testLongNamesNullBase() throws IOException {
assertEquals(someFile.getCanonicalFile().getAbsolutePath(), ds.getNiceFileName(false, null));
}
@Test
void testLongNamesCommaSeparatedDirs() throws IOException {
// use 2 dirs, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(someFile.getCanonicalFile().getAbsolutePath(),
ds.getNiceFileName(false, SOMEFILE_DIR + "," + someFolder.getAbsolutePath()));
}
@Test
void testLongNamesCommaSeparatedFiles() throws IOException {
// use 2 files, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(someFile.getCanonicalFile().getAbsolutePath(),
ds.getNiceFileName(false, SOMEFILE_TXT_FULL_PATH + "," + someFile.getAbsolutePath()));
}
@Test
void testLongNamesCommaSeparatedMixed() throws IOException {
// use a file and a dir, one relative (similar, but not resolving to the same location) and one absolute
assertEquals(someFile.getCanonicalFile().getAbsolutePath(),
ds.getNiceFileName(false, SOMEFILE_TXT_FULL_PATH + "," + someFolder.getAbsolutePath()));
}
}
| 4,017 | 36.203704 | 125 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/internal/PathDataSourceTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.internal.util.IOUtil;
class PathDataSourceTest {
@TempDir
private Path tempDir;
@Test
void testZipFileNiceName() throws Exception {
Path zipArchive = tempDir.resolve("sources.zip");
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipArchive.toFile()))) {
ZipEntry zipEntry = new ZipEntry("path/inside/someSource.dummy");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write("dummy text".getBytes(StandardCharsets.UTF_8));
zipOutputStream.closeEntry();
}
try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:" + zipArchive.toUri()), Collections.<String, Object>emptyMap())) {
Path path = fileSystem.getPath("path/inside/someSource.dummy");
PathDataSource ds = new PathDataSource(path);
assertEquals(zipArchive.toAbsolutePath() + "!" + IOUtil.normalizePath("/path/inside/someSource.dummy"),
ds.getNiceFileName(false, null));
assertEquals("sources.zip!someSource.dummy", ds.getNiceFileName(true, null));
assertEquals("sources.zip!" + IOUtil.normalizePath("/path/inside/someSource.dummy"),
ds.getNiceFileName(true, zipArchive.toAbsolutePath().getParent().toString()));
}
}
}
| 1,939 | 39.416667 | 146 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.util.Iterator;
import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test for {@link CPD}
*/
class CPDTest {
private static final String BASE_TEST_RESOURCE_PATH = "src/test/resources/net/sourceforge/pmd/cpd/files/";
private static final String TARGET_TEST_RESOURCE_PATH = "target/classes/net/sourceforge/pmd/cpd/files/";
private CPD cpd;
// Symlinks are not well supported under Windows - so the tests are
// simply executed only on linux.
private boolean canTestSymLinks = SystemUtils.IS_OS_UNIX;
@BeforeEach
void setup() throws Exception {
CPDConfiguration theConfiguration = new CPDConfiguration();
theConfiguration.setLanguage(new AnyLanguage("any"));
theConfiguration.setMinimumTileSize(10);
theConfiguration.postContruct();
cpd = new CPD(theConfiguration);
}
/**
* As java doesn't support symlinks in zip files, maven does not, too. So,
* we are creating the symlinks manually here before the test.
*
* @throws Exception
* any error
*/
private void prepareSymLinks() throws Exception {
assumeTrue(canTestSymLinks, "Skipping unit tests with symlinks.");
Runtime runtime = Runtime.getRuntime();
if (!new File(TARGET_TEST_RESOURCE_PATH, "symlink-for-real-file.txt").exists()) {
runtime.exec(new String[] { "ln", "-s", BASE_TEST_RESOURCE_PATH + "real-file.txt",
TARGET_TEST_RESOURCE_PATH + "symlink-for-real-file.txt", }).waitFor();
}
if (!new File(BASE_TEST_RESOURCE_PATH, "this-is-a-broken-sym-link-for-test").exists()) {
runtime.exec(new String[] { "ln", "-s", "broken-sym-link",
TARGET_TEST_RESOURCE_PATH + "this-is-a-broken-sym-link-for-test", }).waitFor();
}
}
/**
* A broken symlink (which is basically a not existing file), should be
* skipped.
*
* @throws Exception
* any error
*/
@Test
void testFileSectionWithBrokenSymlinks() throws Exception {
prepareSymLinks();
NoFileAssertListener listener = new NoFileAssertListener(0);
cpd.setCpdListener(listener);
cpd.add(new File(BASE_TEST_RESOURCE_PATH, "this-is-a-broken-sym-link-for-test"));
listener.verify();
}
/**
* A file should be added only once - even if it was found twice, because of
* a sym link.
*
* @throws Exception
* any error
*/
@Test
void testFileAddedAsSymlinkAndReal() throws Exception {
prepareSymLinks();
NoFileAssertListener listener = new NoFileAssertListener(1);
cpd.setCpdListener(listener);
cpd.add(new File(BASE_TEST_RESOURCE_PATH, "real-file.txt"));
cpd.add(new File(BASE_TEST_RESOURCE_PATH, "symlink-for-real-file.txt"));
listener.verify();
}
/**
* Add a file with a relative path - should still be added and not be
* detected as a sym link.
*
* @throws Exception
* any error
*/
@Test
void testFileAddedWithRelativePath() throws Exception {
NoFileAssertListener listener = new NoFileAssertListener(1);
cpd.setCpdListener(listener);
cpd.add(new File("./" + BASE_TEST_RESOURCE_PATH, "real-file.txt"));
listener.verify();
}
/**
* The order of the duplicates is dependent on the order the files are added to CPD.
* See also https://github.com/pmd/pmd/issues/1196
* @throws Exception
*/
@Test
void testFileOrderRelevance() throws Exception {
cpd.add(new File("./" + BASE_TEST_RESOURCE_PATH, "dup2.java"));
cpd.add(new File("./" + BASE_TEST_RESOURCE_PATH, "dup1.java"));
cpd.go();
Iterator<Match> matches = cpd.getMatches();
while (matches.hasNext()) {
Match match = matches.next();
// the file added first was dup2.
assertTrue(match.getFirstMark().getFilename().endsWith("dup2.java"));
assertTrue(match.getSecondMark().getFilename().endsWith("dup1.java"));
}
}
/**
* Simple listener that fails, if too many files were added and not skipped.
*/
private static class NoFileAssertListener implements CPDListener {
private int expectedFilesCount;
private int files;
NoFileAssertListener(int expectedFilesCount) {
this.expectedFilesCount = expectedFilesCount;
this.files = 0;
}
@Override
public void addedFile(int fileCount, File file) {
files++;
if (files > expectedFilesCount) {
fail("File was added! - " + file);
}
}
@Override
public void phaseUpdate(int phase) {
// not needed for this test
}
public void verify() {
assertEquals(expectedFilesCount, files,
"Expected " + expectedFilesCount + " files, but " + files + " have been added.");
}
}
}
| 5,515 | 32.02994 | 110 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/MatchTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
class MatchTest {
@Test
void testSimple() {
int lineCount1 = 10;
String codeFragment1 = "code fragment";
Mark mark1 = createMark("public", "/var/Foo.java", 1, lineCount1, codeFragment1);
int lineCount2 = 20;
String codeFragment2 = "code fragment 2";
Mark mark2 = createMark("class", "/var/Foo.java", 1, lineCount2, codeFragment2);
Match match = new Match(1, mark1, mark2);
assertEquals(1, match.getTokenCount());
// Returns the line count of the first mark
assertEquals(lineCount1, match.getLineCount());
// Returns the source code of the first mark
assertEquals(codeFragment1, match.getSourceCodeSlice());
Iterator<Mark> i = match.iterator();
Mark occurrence1 = i.next();
Mark occurrence2 = i.next();
assertFalse(i.hasNext());
assertEquals(mark1, occurrence1);
assertEquals(lineCount1, occurrence1.getLineCount());
assertEquals(codeFragment1, occurrence1.getSourceCodeSlice());
assertEquals(mark2, occurrence2);
assertEquals(lineCount2, occurrence2.getLineCount());
assertEquals(codeFragment2, occurrence2.getSourceCodeSlice());
}
@Test
void testCompareTo() {
Match m1 = new Match(1, new TokenEntry("public", "/var/Foo.java", 1),
new TokenEntry("class", "/var/Foo.java", 1));
Match m2 = new Match(2, new TokenEntry("Foo", "/var/Foo.java", 1), new TokenEntry("{", "/var/Foo.java", 1));
assertTrue(m2.compareTo(m1) < 0);
}
private Mark createMark(String image, String tokenSrcID, int beginLine, int lineCount, String code) {
Mark result = new Mark(new TokenEntry(image, tokenSrcID, beginLine));
result.setLineCount(lineCount);
result.setSourceCode(new SourceCode(new SourceCode.StringCodeLoader(code)));
return result;
}
}
| 2,279 | 34.625 | 116 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDReportTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.util.Predicate;
class CPDReportTest {
@Test
void testFilterMatches() {
List<Match> originalMatches = Arrays.asList(
createMatch("file1.java", "file2.java", 1),
createMatch("file1.java", "file3.java", 2),
createMatch("file2.java", "file3.java", 3));
Map<String, Integer> numberOfTokensPerFile = new HashMap<>();
numberOfTokensPerFile.put("file1.java", 10);
numberOfTokensPerFile.put("file2.java", 15);
numberOfTokensPerFile.put("file3.java", 20);
CPDReport original = new CPDReport(originalMatches, numberOfTokensPerFile);
assertEquals(3, original.getMatches().size());
CPDReport filtered = original.filterMatches(
new Predicate<Match>() {
@Override
public boolean test(Match match) {
// only keep file1.java
for (Mark mark : match.getMarkSet()) {
if (mark.getFilename().equals("file1.java")) {
return true;
}
}
return false;
}
});
assertEquals(2, filtered.getMatches().size());
for (Match match : filtered.getMatches()) {
Set<String> filenames = new HashSet<>();
for (Mark mark : match.getMarkSet()) {
filenames.add(mark.getFilename());
}
assertTrue(filenames.contains("file1.java"));
}
// note: number of tokens per file is not changed
assertEquals(original.getNumberOfTokensPerFile(), filtered.getNumberOfTokensPerFile());
}
private Match createMatch(String file1, String file2, int line) {
return new Match(5,
new TokenEntry("firstToken", file1, 1, 1, 1),
new TokenEntry("secondToken", file2, 1, 2, 2));
}
}
| 2,438 | 34.347826 | 95 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDFilelistTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
class CPDFilelistTest {
@Test
void testFilelist() {
CPDConfiguration arguments = new CPDConfiguration();
arguments.setLanguage(new CpddummyLanguage());
arguments.setFileListPath("src/test/resources/net/sourceforge/pmd/cpd/cli/filelist.txt");
CPD cpd = new CPD(arguments);
List<String> paths = cpd.getSourcePaths();
assertEquals(2, paths.size());
Set<String> simpleNames = new HashSet<>();
for (String path : paths) {
simpleNames.add(Paths.get(path).getFileName().toString());
}
assertTrue(simpleNames.contains("anotherfile.dummy"));
assertTrue(simpleNames.contains("somefile.dummy"));
}
@Test
void testFilelistMultipleLines() {
CPDConfiguration arguments = new CPDConfiguration();
arguments.setLanguage(new CpddummyLanguage());
arguments.setFileListPath("src/test/resources/net/sourceforge/pmd/cpd/cli/filelist2.txt");
CPD cpd = new CPD(arguments);
List<String> paths = cpd.getSourcePaths();
assertEquals(2, paths.size());
Set<String> simpleNames = new HashSet<>();
for (String path : paths) {
simpleNames.add(Paths.get(path).getFileName().toString());
}
assertTrue(simpleNames.contains("anotherfile.dummy"));
assertTrue(simpleNames.contains("somefile.dummy"));
}
}
| 1,774 | 32.490566 | 98 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/MarkTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.SourceCode.StringCodeLoader;
class MarkTest {
@Test
void testSimple() {
String filename = "/var/Foo.java";
int beginLine = 1;
TokenEntry token = new TokenEntry("public", "/var/Foo.java", 1);
Mark mark = new Mark(token);
int lineCount = 10;
mark.setLineCount(lineCount);
String codeFragment = "code fragment";
mark.setSourceCode(new SourceCode(new StringCodeLoader(codeFragment)));
assertEquals(token, mark.getToken());
assertEquals(filename, mark.getFilename());
assertEquals(beginLine, mark.getBeginLine());
assertEquals(lineCount, mark.getLineCount());
assertEquals(beginLine + lineCount - 1, mark.getEndLine());
assertEquals(-1, mark.getBeginColumn());
assertEquals(-1, mark.getEndColumn());
assertEquals(codeFragment, mark.getSourceCodeSlice());
}
@Test
void testColumns() {
final String filename = "/var/Foo.java";
final int beginLine = 1;
final int beginColumn = 2;
final int endColumn = 3;
final TokenEntry token = new TokenEntry("public", "/var/Foo.java", 1, beginColumn, beginColumn + "public".length());
final TokenEntry endToken = new TokenEntry("}", "/var/Foo.java", 5, endColumn - 1, endColumn);
final Mark mark = new Mark(token);
final int lineCount = 10;
mark.setLineCount(lineCount);
mark.setEndToken(endToken);
final String codeFragment = "code fragment";
mark.setSourceCode(new SourceCode(new StringCodeLoader(codeFragment)));
assertEquals(token, mark.getToken());
assertEquals(filename, mark.getFilename());
assertEquals(beginLine, mark.getBeginLine());
assertEquals(lineCount, mark.getLineCount());
assertEquals(beginLine + lineCount - 1, mark.getEndLine());
assertEquals(beginColumn, mark.getBeginColumn());
assertEquals(endColumn, mark.getEndColumn());
assertEquals(codeFragment, mark.getSourceCodeSlice());
}
}
| 2,305 | 35.603175 | 124 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/LanguageFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class LanguageFactoryTest {
@Test
void testSimple() {
assertTrue(LanguageFactory.createLanguage("Cpddummy") instanceof CpddummyLanguage);
assertTrue(LanguageFactory.createLanguage("not_existing_language") instanceof AnyLanguage);
}
}
| 482 | 24.421053 | 99 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CpdXsltTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.util.IOUtil;
class CpdXsltTest {
/* Sample ant build.xml file. Run with "ant cpdxsl".
<project>
<target name="cpdxslt">
<xslt in="src/test/resources/net/sourceforge/pmd/cpd/SampleCpdReport.xml" style="etc/xslt/cpdhtml.xslt" out="cpd.html" />
</target>
</project>
*/
@Test
void cpdhtml() throws Exception {
String result = runXslt("cpdhtml.xslt");
String expected = IOUtil.readToString(CpdXsltTest.class.getResourceAsStream("ExpectedCpdHtmlReport.html"), StandardCharsets.UTF_8);
assertEquals(expected, result);
}
@Test
void cpdhtmlv2() throws Exception {
String result = runXslt("cpdhtml-v2.xslt");
String expected = IOUtil.readToString(CpdXsltTest.class.getResourceAsStream("ExpectedCpdHtmlReport-v2.html"), StandardCharsets.UTF_8);
assertEquals(expected, result);
}
private String runXslt(String stylesheet) throws Exception {
XSLTErrorListener errorListener = new XSLTErrorListener();
// note: using the default JDK factory, otherwise we would use Saxon from PMD's classpath
// which supports more xslt features.
TransformerFactory factory = TransformerFactory
.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null);
factory.setErrorListener(errorListener);
StreamSource xslt = new StreamSource(new File("etc/xslt/" + stylesheet));
Templates template = factory.newTemplates(xslt);
StreamSource cpdReport = new StreamSource(CpdXsltTest.class.getResourceAsStream("SampleCpdReport.xml"));
StreamResult result = new StreamResult(new StringWriter());
Transformer transformer = template.newTransformer();
transformer.setErrorListener(errorListener);
transformer.transform(cpdReport, result);
assertTrue(errorListener.hasNoErrors(), "XSLT errors occured: " + errorListener);
return result.getWriter().toString();
}
private static class XSLTErrorListener implements ErrorListener {
final List<TransformerException> errors = new ArrayList<>();
@Override
public void warning(TransformerException exception) throws TransformerException {
errors.add(exception);
}
@Override
public void fatalError(TransformerException exception) throws TransformerException {
errors.add(exception);
}
@Override
public void error(TransformerException exception) throws TransformerException {
errors.add(exception);
}
public boolean hasNoErrors() {
return errors.isEmpty();
}
@Override
public String toString() {
return errors.toString();
}
}
}
| 3,550 | 34.51 | 142 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/XMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
/**
* @author Philippe T'Seyen
* @author Romain Pelisse <belaran@gmail.com>
*
*/
class XMLRendererTest {
private static final String ENCODING = (String) System.getProperties().get("file.encoding");
private static final String FORM_FEED = "\u000C"; // this character is invalid in XML 1.0 documents
private static final String FORM_FEED_ENTITY = ""; // this is also not allowed in XML 1.0 documents
@Test
void testWithNoDuplication() throws IOException, ParserConfigurationException, SAXException {
CPDReportRenderer renderer = new XMLRenderer();
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(Collections.emptyList(), Collections.emptyMap()), sw);
String report = sw.toString();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(report.getBytes(ENCODING)));
NodeList nodes = doc.getChildNodes();
Node n = nodes.item(0);
assertEquals("pmd-cpd", n.getNodeName());
assertEquals(0, doc.getElementsByTagName("duplication").getLength());
}
@Test
void testWithOneDuplication() throws Exception {
CPDReportRenderer renderer = new XMLRenderer();
List<Match> list = new ArrayList<>();
int lineCount = 6;
String codeFragment = "code\nfragment";
Mark mark1 = createMark("public", "/var/Foo.java", 1, lineCount, codeFragment);
Mark mark2 = createMark("stuff", "/var/Foo.java", 73, lineCount, codeFragment);
Match match = new Match(75, mark1, mark2);
list.add(match);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(report.getBytes(ENCODING)));
NodeList dupes = doc.getElementsByTagName("duplication");
assertEquals(1, dupes.getLength());
Node file = dupes.item(0).getFirstChild();
while (file != null && file.getNodeType() != Node.ELEMENT_NODE) {
file = file.getNextSibling();
}
if (file != null) {
assertEquals("1", file.getAttributes().getNamedItem("line").getNodeValue());
assertEquals("/var/Foo.java", file.getAttributes().getNamedItem("path").getNodeValue());
assertEquals("6", file.getAttributes().getNamedItem("endline").getNodeValue());
assertEquals(null, file.getAttributes().getNamedItem("column"));
assertEquals(null, file.getAttributes().getNamedItem("endcolumn"));
file = file.getNextSibling();
while (file != null && file.getNodeType() != Node.ELEMENT_NODE) {
file = file.getNextSibling();
}
}
if (file != null) {
assertEquals("73", file.getAttributes().getNamedItem("line").getNodeValue());
assertEquals("78", file.getAttributes().getNamedItem("endline").getNodeValue());
assertEquals(null, file.getAttributes().getNamedItem("column"));
assertEquals(null, file.getAttributes().getNamedItem("endcolumn"));
}
assertEquals(1, doc.getElementsByTagName("codefragment").getLength());
assertEquals(codeFragment, doc.getElementsByTagName("codefragment").item(0).getTextContent());
}
@Test
void testRenderWithMultipleMatch() throws Exception {
CPDReportRenderer renderer = new XMLRenderer();
List<Match> list = new ArrayList<>();
int lineCount1 = 6;
String codeFragment1 = "code fragment";
Mark mark1 = createMark("public", "/var/Foo.java", 48, lineCount1, codeFragment1);
Mark mark2 = createMark("void", "/var/Foo.java", 73, lineCount1, codeFragment1);
Match match1 = new Match(75, mark1, mark2);
int lineCount2 = 7;
String codeFragment2 = "code fragment 2";
Mark mark3 = createMark("void", "/var/Foo2.java", 49, lineCount2, codeFragment2);
Mark mark4 = createMark("stuff", "/var/Foo2.java", 74, lineCount2, codeFragment2);
Match match2 = new Match(76, mark3, mark4);
list.add(match1);
list.add(match2);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(report.getBytes(ENCODING)));
assertEquals(2, doc.getElementsByTagName("duplication").getLength());
assertEquals(4, doc.getElementsByTagName("file").getLength());
}
@Test
void testWithOneDuplicationWithColumns() throws Exception {
CPDReportRenderer renderer = new XMLRenderer();
List<Match> list = new ArrayList<>();
int lineCount = 6;
String codeFragment = "code\nfragment";
Mark mark1 = createMark("public", "/var/Foo.java", 1, lineCount, codeFragment, 2, 3);
Mark mark2 = createMark("stuff", "/var/Foo.java", 73, lineCount, codeFragment, 4, 5);
Match match = new Match(75, mark1, mark2);
list.add(match);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(report.getBytes(ENCODING)));
NodeList dupes = doc.getElementsByTagName("duplication");
assertEquals(1, dupes.getLength());
Node file = dupes.item(0).getFirstChild();
while (file != null && file.getNodeType() != Node.ELEMENT_NODE) {
file = file.getNextSibling();
}
if (file != null) {
assertEquals("1", file.getAttributes().getNamedItem("line").getNodeValue());
assertEquals("/var/Foo.java", file.getAttributes().getNamedItem("path").getNodeValue());
assertEquals("6", file.getAttributes().getNamedItem("endline").getNodeValue());
assertEquals("2", file.getAttributes().getNamedItem("column").getNodeValue());
assertEquals("3", file.getAttributes().getNamedItem("endcolumn").getNodeValue());
file = file.getNextSibling();
while (file != null && file.getNodeType() != Node.ELEMENT_NODE) {
file = file.getNextSibling();
}
}
if (file != null) {
assertEquals("73", file.getAttributes().getNamedItem("line").getNodeValue());
assertEquals("78", file.getAttributes().getNamedItem("endline").getNodeValue());
assertEquals("4", file.getAttributes().getNamedItem("column").getNodeValue());
assertEquals("5", file.getAttributes().getNamedItem("endcolumn").getNodeValue());
}
assertEquals(1, doc.getElementsByTagName("codefragment").getLength());
assertEquals(codeFragment, doc.getElementsByTagName("codefragment").item(0).getTextContent());
}
@Test
void testRendererEncodedPath() throws IOException {
CPDReportRenderer renderer = new XMLRenderer();
List<Match> list = new ArrayList<>();
final String espaceChar = "<";
Mark mark1 = createMark("public", "/var/A<oo.java" + FORM_FEED, 48, 6, "code fragment");
Mark mark2 = createMark("void", "/var/B<oo.java", 73, 6, "code fragment");
Match match1 = new Match(75, mark1, mark2);
list.add(match1);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
assertTrue(report.contains(espaceChar));
assertFalse(report.contains(FORM_FEED));
assertFalse(report.contains(FORM_FEED_ENTITY));
}
@Test
void testFilesWithNumberOfTokens() throws IOException, ParserConfigurationException, SAXException {
final CPDReportRenderer renderer = new XMLRenderer();
final List<Match> matches = new ArrayList<>();
final String filename = "/var/Foo.java";
final int lineCount = 6;
final String codeFragment = "code\nfragment";
final Mark mark1 = createMark("public", filename, 1, lineCount, codeFragment, 2, 3);
final Mark mark2 = createMark("stuff", filename, 73, lineCount, codeFragment, 4, 5);
final Match match = new Match(75, mark1, mark2);
matches.add(match);
final Map<String, Integer> numberOfTokensPerFile = new HashMap<>();
numberOfTokensPerFile.put(filename, 888);
final CPDReport report = new CPDReport(matches, numberOfTokensPerFile);
final StringWriter writer = new StringWriter();
renderer.render(report, writer);
final String xmlOutput = writer.toString();
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xmlOutput.getBytes(ENCODING)));
final NodeList files = doc.getElementsByTagName("file");
final Node file = files.item(0);
final NamedNodeMap attributes = file.getAttributes();
assertEquals("/var/Foo.java", attributes.getNamedItem("path").getNodeValue());
assertEquals("888", attributes.getNamedItem("totalNumberOfTokens").getNodeValue());
}
@Test
void testGetDuplicationStartEnd() throws IOException, ParserConfigurationException, SAXException {
TokenEntry.clearImages();
final CPDReportRenderer renderer = new XMLRenderer();
final List<Match> matches = new ArrayList<>();
final String filename = "/var/Foo.java";
final int lineCount = 6;
final String codeFragment = "code\nfragment";
final Mark mark1 = createMark("public", filename, 1, lineCount, codeFragment, 2, 3);
final Mark mark2 = createMark("stuff", filename, 73, lineCount, codeFragment, 4, 5);
final Match match = new Match(75, mark1, mark2);
matches.add(match);
final Map<String, Integer> numberOfTokensPerFile = new HashMap<>();
numberOfTokensPerFile.put(filename, 888);
final CPDReport report = new CPDReport(matches, numberOfTokensPerFile);
final StringWriter writer = new StringWriter();
renderer.render(report, writer);
final String xmlOutput = writer.toString();
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xmlOutput.getBytes(ENCODING)));
final NodeList files = doc.getElementsByTagName("file");
final Node dup_1 = files.item(1);
final NamedNodeMap attrs_1 = dup_1.getAttributes();
assertEquals("0", attrs_1.getNamedItem("begintoken").getNodeValue());
assertEquals("1", attrs_1.getNamedItem("endtoken").getNodeValue());
final Node dup_2 = files.item(2);
final NamedNodeMap attrs_2 = dup_2.getAttributes();
assertEquals("2", attrs_2.getNamedItem("begintoken").getNodeValue());
assertEquals("3", attrs_2.getNamedItem("endtoken").getNodeValue());
}
@Test
void testRendererXMLEscaping() throws IOException {
String codefragment = "code fragment" + FORM_FEED + "\nline2\nline3\nno & escaping necessary in CDATA\nx=\"]]>\";";
CPDReportRenderer renderer = new XMLRenderer();
List<Match> list = new ArrayList<>();
Mark mark1 = createMark("public", "file1", 1, 5, codefragment);
Mark mark2 = createMark("public", "file2", 5, 5, codefragment);
Match match1 = new Match(75, mark1, mark2);
list.add(match1);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
assertFalse(report.contains(FORM_FEED));
assertFalse(report.contains(FORM_FEED_ENTITY));
assertTrue(report.contains("no & escaping necessary in CDATA"));
assertFalse(report.contains("x=\"]]>\";")); // must be escaped
assertTrue(report.contains("x=\"]]]]><![CDATA[>\";"));
}
private Mark createMark(String image, String tokenSrcID, int beginLine, int lineCount, String code) {
Mark result = new Mark(new TokenEntry(image, tokenSrcID, beginLine));
result.setLineCount(lineCount);
result.setSourceCode(new SourceCode(new SourceCode.StringCodeLoader(code)));
return result;
}
private Mark createMark(String image, String tokenSrcID, int beginLine, int lineCount, String code, int beginColumn, int endColumn) {
final TokenEntry beginToken = new TokenEntry(image, tokenSrcID, beginLine, beginColumn, beginColumn + 1);
final TokenEntry endToken = new TokenEntry(image, tokenSrcID, beginLine + lineCount, endColumn - 1, endColumn);
final Mark result = new Mark(beginToken);
result.setLineCount(lineCount);
result.setEndToken(endToken);
result.setSourceCode(new SourceCode(new SourceCode.StringCodeLoader(code)));
return result;
}
}
| 14,090 | 47.757785 | 137 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CpddummyLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* Sample language for testing LanguageFactory.
*
*/
public class CpddummyLanguage extends AbstractLanguage {
public CpddummyLanguage() {
super("CPD Dummy Language used in tests", "Cpddummy", new AnyTokenizer(), "dummy");
}
}
| 372 | 20.941176 | 91 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDConfigurationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
class CPDConfigurationTest {
@Test
void testRenderers() {
Map<String, Class<? extends CPDReportRenderer>> renderersToTest = new HashMap<>();
renderersToTest.put("csv", CSVRenderer.class);
renderersToTest.put("xml", XMLRenderer.class);
renderersToTest.put("csv_with_linecount_per_file", CSVWithLinecountPerFileRenderer.class);
renderersToTest.put("vs", VSRenderer.class);
renderersToTest.put("text", SimpleRenderer.class);
for (Map.Entry<String, Class<? extends CPDReportRenderer>> entry : renderersToTest.entrySet()) {
CPDReportRenderer r = CPDConfiguration.createRendererByName(entry.getKey(), "UTF-8");
assertNotNull(r);
assertSame(entry.getValue(), r.getClass());
}
}
}
| 1,178 | 31.75 | 104 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/AnyTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class AnyTokenizerTest {
@Test
void testMultiLineMacros() {
AnyTokenizer tokenizer = new AnyTokenizer("//");
compareResult(tokenizer, TEST1, EXPECTED);
}
@Test
void testStringEscape() {
AnyTokenizer tokenizer = new AnyTokenizer("//");
compareResult(tokenizer, "a = \"oo\\n\"", listOf("a", "=", "\"oo\\n\"", "EOF"));
}
@Test
void testMultilineString() {
AnyTokenizer tokenizer = new AnyTokenizer("//");
Tokens tokens = compareResult(tokenizer, "a = \"oo\n\";", listOf("a", "=", "\"oo\n\"", ";", "EOF"));
TokenEntry string = tokens.getTokens().get(2);
assertEquals("\"oo\n\"", getTokenImage(string));
assertEquals(1, string.getBeginLine());
assertEquals(5, string.getBeginColumn());
assertEquals(2, string.getEndColumn()); // ends on line 2
TokenEntry semi = tokens.getTokens().get(3);
assertEquals(";", getTokenImage(semi));
assertEquals(2, semi.getBeginLine());
assertEquals(2, semi.getBeginColumn());
assertEquals(3, semi.getEndColumn());
}
/**
* Tests that [core][cpd] AnyTokenizer doesn't count columns correctly #2760 is actually fixed.
*/
@Test
void testTokenPosition() {
AnyTokenizer tokenizer = new AnyTokenizer();
SourceCode code = new SourceCode(new SourceCode.StringCodeLoader("a;\nbbbb\n;"));
Tokens tokens = new Tokens();
tokenizer.tokenize(code, tokens);
TokenEntry bbbbToken = tokens.getTokens().get(2);
assertEquals(2, bbbbToken.getBeginLine());
assertEquals(1, bbbbToken.getBeginColumn());
assertEquals(5, bbbbToken.getEndColumn());
}
private Tokens compareResult(AnyTokenizer tokenizer, String source, List<String> expectedImages) {
SourceCode code = new SourceCode(new SourceCode.StringCodeLoader(source));
Tokens tokens = new Tokens();
tokenizer.tokenize(code, tokens);
List<String> tokenStrings = new ArrayList<>();
for (TokenEntry token : tokens.getTokens()) {
tokenStrings.add(getTokenImage(token));
}
assertEquals(expectedImages, tokenStrings);
return tokens;
}
private String getTokenImage(TokenEntry t) {
return t.toString();
}
private static final List<String> EXPECTED = listOf(
"using", "System", ";",
"namespace", "HelloNameSpace", "{",
"public", "class", "HelloWorld", "{", // note: comment is excluded
"static", "void", "Main", "(", "string", "[", "]", "args", ")", "{",
"Console", ".", "WriteLine", "(", "\"Hello World!\"", ")", ";",
"}", "}", "}", "EOF"
);
private static final String TEST1 =
"using System;\n"
+ "namespace HelloNameSpace {\n"
+ "\n"
+ " public class HelloWorld { // A comment\n"
+ " static void Main(string[] args) {\n"
+ "\n"
+ " Console.WriteLine(\"Hello World!\");\n"
+ " }\n"
+ " }\n"
+ "\n"
+ "}\n";
}
| 3,479 | 32.786408 | 108 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CSVRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
class CSVRendererTest {
@Test
void testLineCountPerFile() throws IOException {
CPDReportRenderer renderer = new CSVRenderer(true);
List<Match> list = new ArrayList<>();
String codeFragment = "code\nfragment";
Mark mark1 = createMark("public", "/var/Foo.java", 48, 10, codeFragment);
Mark mark2 = createMark("stuff", "/var/Bar.java", 73, 20, codeFragment);
Match match = new Match(75, mark1, mark2);
list.add(match);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
String expectedReport = "tokens,occurrences" + System.lineSeparator()
+ "75,2,48,10,/var/Foo.java,73,20,/var/Bar.java" + System.lineSeparator();
assertEquals(expectedReport, report);
}
@Test
void testFilenameEscapes() throws IOException {
CPDReportRenderer renderer = new CSVRenderer();
List<Match> list = new ArrayList<>();
String codeFragment = "code\nfragment";
Mark mark1 = createMark("public", "/var,with,commas/Foo.java", 48, 10, codeFragment);
Mark mark2 = createMark("stuff", "/var,with,commas/Bar.java", 73, 20, codeFragment);
Match match = new Match(75, mark1, mark2);
list.add(match);
StringWriter sw = new StringWriter();
renderer.render(new CPDReport(list, Collections.emptyMap()), sw);
String report = sw.toString();
String expectedReport = "lines,tokens,occurrences" + System.lineSeparator()
+ "10,75,2,48,\"/var,with,commas/Foo.java\",73,\"/var,with,commas/Bar.java\"" + System.lineSeparator();
assertEquals(expectedReport, report);
}
private Mark createMark(String image, String tokenSrcID, int beginLine, int lineCount, String code) {
Mark result = new Mark(new TokenEntry(image, tokenSrcID, beginLine));
result.setLineCount(lineCount);
result.setSourceCode(new SourceCode(new SourceCode.StringCodeLoader(code)));
return result;
}
}
| 2,512 | 37.661538 | 119 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/SourceCodeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.SourceCode.FileCodeLoader;
class SourceCodeTest {
private static final String BASE_RESOURCE_PATH = "src/test/resources/net/sourceforge/pmd/cpd/files/";
private static final String SAMPLE_CODE = "Line 1\n" + "Line 2\n" + "Line 3\n" + "Line 4\n";
@Test
void testSlice() {
SourceCode sourceCode = new SourceCode(new SourceCode.StringCodeLoader(SAMPLE_CODE, "Foo.java"));
assertEquals("Foo.java", sourceCode.getFileName());
assertEquals("Line 1", sourceCode.getSlice(1, 1));
assertEquals("Line 2", sourceCode.getSlice(2, 2));
assertEquals("Line 1\nLine 2", sourceCode.getSlice(1, 2));
sourceCode.getCodeBuffer(); // load into soft reference, must not change behavior
assertEquals("Line 1\nLine 2", sourceCode.getSlice(1, 2));
}
@Test
void testEncodingDetectionFromBOM() throws Exception {
FileCodeLoader loader = new SourceCode.FileCodeLoader(new File(BASE_RESOURCE_PATH + "file_with_utf8_bom.java"),
"ISO-8859-1");
// The encoding detection is done when the reader is created
loader.getReader();
assertEquals("UTF-8", loader.getEncoding());
}
@Test
void testEncodingIsNotChangedWhenThereIsNoBOM() throws Exception {
FileCodeLoader loader = new SourceCode.FileCodeLoader(
new File(BASE_RESOURCE_PATH + "file_with_ISO-8859-1_encoding.java"), "ISO-8859-1");
// The encoding detection is done when the reader is created
loader.getReader();
assertEquals("ISO-8859-1", loader.getEncoding());
}
}
| 1,866 | 34.226415 | 119 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/TokenEntryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class TokenEntryTest {
@Test
void testSimple() {
TokenEntry.clearImages();
TokenEntry mark = new TokenEntry("public", "/var/Foo.java", 1);
assertEquals(1, mark.getBeginLine());
assertEquals("/var/Foo.java", mark.getTokenSrcID());
assertEquals(0, mark.getIndex());
assertEquals(-1, mark.getBeginColumn());
assertEquals(-1, mark.getEndColumn());
}
@Test
void testColumns() {
TokenEntry.clearImages();
TokenEntry mark = new TokenEntry("public", "/var/Foo.java", 1, 2, 3);
assertEquals(1, mark.getBeginLine());
assertEquals("/var/Foo.java", mark.getTokenSrcID());
assertEquals(0, mark.getIndex());
assertEquals(2, mark.getBeginColumn());
assertEquals(3, mark.getEndColumn());
}
}
| 1,035 | 28.6 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.token.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.GenericToken;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.document.TextRegion;
class BaseTokenFilterTest {
static class StringToken implements GenericToken<StringToken> {
private final String text;
StringToken(final String text) {
this.text = text;
}
@Override
public StringToken getNext() {
return null;
}
@Override
public StringToken getPreviousComment() {
return null;
}
@Override
public TextRegion getRegion() {
return TextRegion.fromBothOffsets(0, text.length());
}
@Override
public boolean isEof() {
return text == null;
}
@Override
public String getImageCs() {
return text;
}
@Override
public FileLocation getReportLocation() {
return FileLocation.range(FileId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 1));
}
@Override
public int compareTo(StringToken o) {
return text.compareTo(o.text);
}
@Override
public int getKind() {
return 0;
}
}
static class StringTokenManager implements TokenManager<StringToken> {
Iterator<String> iterator = Collections.unmodifiableList(Arrays.asList("a", "b", "c")).iterator();
@Override
public StringToken getNextToken() {
if (iterator.hasNext()) {
return new StringToken(iterator.next());
} else {
return null;
}
}
}
static class DummyTokenFilter<T extends GenericToken<T>> extends BaseTokenFilter<T> {
Iterable<T> remainingTokens;
DummyTokenFilter(final TokenManager<T> tokenManager) {
super(tokenManager);
}
@Override
protected boolean shouldStopProcessing(final T currentToken) {
return currentToken == null;
}
@Override
protected void analyzeTokens(final T currentToken, final Iterable<T> remainingTokens) {
this.remainingTokens = remainingTokens;
}
public Iterable<T> getRemainingTokens() {
return remainingTokens;
}
}
@Test
void testRemainingTokensFunctionality1() {
final TokenManager<StringToken> tokenManager = new StringTokenManager();
final DummyTokenFilter<StringToken> tokenFilter = new DummyTokenFilter<>(tokenManager);
final StringToken firstToken = tokenFilter.getNextToken();
assertEquals("a", firstToken.getImage());
final Iterable<StringToken> iterable = tokenFilter.getRemainingTokens();
final Iterator<StringToken> it1 = iterable.iterator();
final Iterator<StringToken> it2 = iterable.iterator();
assertTrue(it1.hasNext());
assertTrue(it2.hasNext());
final StringToken firstValFirstIt = it1.next();
final StringToken firstValSecondIt = it2.next();
assertTrue(it1.hasNext());
assertTrue(it2.hasNext());
final StringToken secondValFirstIt = it1.next();
assertFalse(it1.hasNext());
assertTrue(it2.hasNext());
final StringToken secondValSecondIt = it2.next();
assertFalse(it2.hasNext());
assertEquals("b", firstValFirstIt.getImage());
assertEquals("b", firstValSecondIt.getImage());
assertEquals("c", secondValFirstIt.getImage());
assertEquals("c", secondValSecondIt.getImage());
}
@Test
void testRemainingTokensFunctionality2() {
final TokenManager<StringToken> tokenManager = new StringTokenManager();
final DummyTokenFilter<StringToken> tokenFilter = new DummyTokenFilter<>(tokenManager);
final StringToken firstToken = tokenFilter.getNextToken();
assertEquals("a", firstToken.getImage());
final Iterable<StringToken> iterable = tokenFilter.getRemainingTokens();
final Iterator<StringToken> it1 = iterable.iterator();
final Iterator<StringToken> it2 = iterable.iterator();
assertTrue(it1.hasNext());
assertTrue(it2.hasNext());
final StringToken firstValFirstIt = it1.next();
assertTrue(it1.hasNext());
final StringToken secondValFirstIt = it1.next();
assertFalse(it1.hasNext());
assertTrue(it2.hasNext());
final StringToken firstValSecondIt = it2.next();
assertTrue(it2.hasNext());
final StringToken secondValSecondIt = it2.next();
assertFalse(it2.hasNext());
assertEquals("b", firstValFirstIt.getImage());
assertEquals("b", firstValSecondIt.getImage());
assertEquals("c", secondValFirstIt.getImage());
assertEquals("c", secondValSecondIt.getImage());
}
@Test
void testRemainingTokensFunctionality3() {
final TokenManager<StringToken> tokenManager = new StringTokenManager();
final DummyTokenFilter<StringToken> tokenFilter = new DummyTokenFilter<>(tokenManager);
final StringToken firstToken = tokenFilter.getNextToken();
assertEquals("a", firstToken.getImage());
final Iterable<StringToken> iterable = tokenFilter.getRemainingTokens();
final Iterator<StringToken> it1 = iterable.iterator();
final Iterator<StringToken> it2 = iterable.iterator();
it1.next();
it1.next();
it2.next();
it2.next();
assertThrows(NoSuchElementException.class, () -> it1.next());
}
@Test
void testRemainingTokensFunctionality4() {
final TokenManager<StringToken> tokenManager = new StringTokenManager();
final DummyTokenFilter<StringToken> tokenFilter = new DummyTokenFilter<>(tokenManager);
final StringToken firstToken = tokenFilter.getNextToken();
assertEquals("a", firstToken.getImage());
final Iterable<StringToken> iterable = tokenFilter.getRemainingTokens();
final Iterator<StringToken> it1 = iterable.iterator();
final StringToken secondToken = tokenFilter.getNextToken();
assertEquals("b", secondToken.getImage());
assertThrows(ConcurrentModificationException.class, () -> it1.next());
}
}
| 7,029 | 34.505051 | 106 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/AbstractPackagedPropertyDescriptorTester.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Map;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
abstract class AbstractPackagedPropertyDescriptorTester<T> extends AbstractPropertyDescriptorTester<T> {
/* default */ AbstractPackagedPropertyDescriptorTester(String typeName) {
super(typeName);
}
@Test
void testMissingPackageNames() {
Map<PropertyDescriptorField, String> attributes = getPropertyDescriptorValues();
attributes.remove(PropertyDescriptorField.LEGAL_PACKAGES);
getMultiFactory().build(attributes); // no exception, null is ok
getSingleFactory().build(attributes);
}
@Override
protected Map<PropertyDescriptorField, String> getPropertyDescriptorValues() {
Map<PropertyDescriptorField, String> attributes = super.getPropertyDescriptorValues();
attributes.put(PropertyDescriptorField.LEGAL_PACKAGES, "java.lang");
return attributes;
}
}
| 1,076 | 28.108108 | 104 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/AbstractPropertyDescriptorTester.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorExternalBuilder;
/**
* Base functionality for all concrete subclasses that evaluate type-specific property descriptors. Checks for error
* conditions during construction, error value detection, serialization, etc.
*
* @author Brian Remedios
*/
abstract class AbstractPropertyDescriptorTester<T> {
public static final String PUNCTUATION_CHARS = "!@#$%^&*()_-+=[]{}\\|;:'\",.<>/?`~";
public static final String WHITESPACE_CHARS = " \t\n";
public static final String DIGIT_CHARS = "0123456789";
public static final String ALPHA_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmniopqrstuvwxyz";
public static final String ALPHA_NUMERIC_CHARS = DIGIT_CHARS + ALPHA_CHARS;
public static final String ALL_CHARS = PUNCTUATION_CHARS + WHITESPACE_CHARS + ALPHA_NUMERIC_CHARS;
private static final int MULTI_VALUE_COUNT = 10;
private static final Random RANDOM = new Random();
protected final String typeName;
AbstractPropertyDescriptorTester(String typeName) {
this.typeName = typeName;
}
protected abstract PropertyDescriptor<List<T>> createBadMultiProperty();
@Test
void testFactorySingleValue() {
PropertyDescriptor<T> prop = getSingleFactory().build(getPropertyDescriptorValues());
T originalValue = createValue();
T value = prop.valueFrom(originalValue instanceof Class ? ((Class) originalValue).getName() : String.valueOf(originalValue));
T value2 = prop.valueFrom(prop.asDelimitedString(value));
if (Pattern.class.equals(prop.type())) {
// Pattern.equals uses object identity...
// we're forced to do that to make it compare the string values of the pattern
assertEquals(String.valueOf(value), String.valueOf(value2));
} else {
assertEquals(value, value2);
}
}
@SuppressWarnings("unchecked")
protected final PropertyDescriptorExternalBuilder<T> getSingleFactory() {
return (PropertyDescriptorExternalBuilder<T>) PropertyTypeId.factoryFor(typeName);
}
protected Map<PropertyDescriptorField, String> getPropertyDescriptorValues() {
Map<PropertyDescriptorField, String> valuesById = new HashMap<>();
valuesById.put(PropertyDescriptorField.NAME, "test");
valuesById.put(PropertyDescriptorField.DESCRIPTION, "desc");
valuesById.put(PropertyDescriptorField.DEFAULT_VALUE, createProperty().asDelimitedString(createValue()));
return valuesById;
}
/**
* Return a legal value(s) per the general scope of the descriptor.
*
* @return Object
*/
protected abstract T createValue();
@Test
void testFactoryMultiValueDefaultDelimiter() {
PropertyDescriptorExternalBuilder<List<T>> multiFactory = getMultiFactory();
PropertyDescriptor<List<T>> prop = multiFactory.build(getPropertyDescriptorValues());
List<T> originalValue = createMultipleValues(MULTI_VALUE_COUNT);
String asDelimitedString = prop.asDelimitedString(originalValue);
List<T> value2 = prop.valueFrom(asDelimitedString);
assertEquals(originalValue, value2);
}
@SuppressWarnings("unchecked")
protected final PropertyDescriptorExternalBuilder<List<T>> getMultiFactory() {
return (PropertyDescriptorExternalBuilder<List<T>>) PropertyTypeId.factoryFor("List[" + typeName + "]");
}
private List<T> createMultipleValues(int count) {
List<T> res = new ArrayList<>();
while (count > 0) {
res.add(createValue());
count--;
}
return res;
}
@Test
void testFactoryMultiValueCustomDelimiter() {
PropertyDescriptorExternalBuilder<List<T>> multiFactory = getMultiFactory();
Map<PropertyDescriptorField, String> valuesById = getPropertyDescriptorValues();
String customDelimiter = "ä";
assertFalse(ALL_CHARS.contains(customDelimiter));
valuesById.put(PropertyDescriptorField.DELIMITER, customDelimiter);
PropertyDescriptor<List<T>> prop = multiFactory.build(valuesById);
List<T> originalValue = createMultipleValues(MULTI_VALUE_COUNT);
String asDelimitedString = prop.asDelimitedString(originalValue);
List<T> value2 = prop.valueFrom(asDelimitedString);
assertEquals(originalValue.toString(), value2.toString());
assertEquals(originalValue, value2);
}
@Test
void testConstructors() {
PropertyDescriptor<T> desc = createProperty();
assertNotNull(desc);
assertThrows(Exception.class, () -> createBadProperty());
}
/**
* Creates and returns a properly configured property descriptor.
*
* @return PropertyDescriptor
*/
protected abstract PropertyDescriptor<T> createProperty();
/**
* Attempt to create a property with faulty configuration values. This method should throw an
* IllegalArgumentException if done correctly.
*
* @return PropertyDescriptor
*/
protected abstract PropertyDescriptor<T> createBadProperty();
@Test
void testAsDelimitedString() {
List<T> testValue = createMultipleValues(MULTI_VALUE_COUNT);
PropertyDescriptor<List<T>> pmdProp = createMultiProperty();
String storeValue = pmdProp.asDelimitedString(testValue);
List<T> returnedValue = pmdProp.valueFrom(storeValue);
assertEquals(returnedValue, testValue);
}
protected abstract PropertyDescriptor<List<T>> createMultiProperty();
@Test
void testValueFrom() {
T testValue = createValue();
PropertyDescriptor<T> pmdProp = createProperty();
String storeValue = pmdProp.asDelimitedString(testValue);
T returnedValue = pmdProp.valueFrom(storeValue);
if (Pattern.class.equals(pmdProp.type())) {
// Pattern.equals uses object identity...
// we're forced to do that to make it compare the string values of the pattern
assertEquals(String.valueOf(returnedValue), String.valueOf(testValue));
} else {
assertEquals(returnedValue, testValue);
}
}
@Test
void testErrorForCorrectSingle() {
T testValue = createValue();
PropertyDescriptor<T> pmdProp = createProperty(); // plain vanilla
// property & valid test value
String errorMsg = pmdProp.errorFor(testValue);
assertNull(errorMsg, errorMsg);
}
@Test
void testErrorForCorrectMulti() {
List<T> testMultiValues = createMultipleValues(MULTI_VALUE_COUNT); // multi-value property, all
// valid test values
PropertyDescriptor<List<T>> multiProperty = createMultiProperty();
String errorMsg = multiProperty.errorFor(testMultiValues);
assertNull(errorMsg, errorMsg);
}
@Test
void testErrorForBadSingle() {
T testValue = createBadValue();
PropertyDescriptor<T> pmdProp = createProperty(); // plain vanilla
// property & valid test value
String errorMsg = pmdProp.errorFor(testValue);
assertNotNull("uncaught bad value: " + testValue, errorMsg);
}
/**
* Return a value(s) that is known to be faulty per the general scope of the descriptor.
*
* @return Object
*/
protected abstract T createBadValue();
@Test
void testErrorForBadMulti() {
List<T> testMultiValues = createMultipleBadValues(MULTI_VALUE_COUNT); // multi-value property, all
// valid test values
PropertyDescriptor<List<T>> multiProperty = createMultiProperty();
String errorMsg = multiProperty.errorFor(testMultiValues);
assertNotNull(errorMsg, "uncaught bad value in: " + testMultiValues);
}
private List<T> createMultipleBadValues(int count) {
List<T> res = new ArrayList<>();
while (count > 0) {
res.add(createBadValue());
count--;
}
return res;
}
@Test
void testIsMultiValue() {
assertFalse(createProperty().isMultiValue());
}
@Test
void testIsMultiValueMulti() {
assertTrue(createMultiProperty().isMultiValue());
}
@Test
void testAddAttributes() {
Map<PropertyDescriptorField, String> atts = createProperty().attributeValuesById();
assertTrue(atts.containsKey(PropertyDescriptorField.NAME));
assertTrue(atts.containsKey(PropertyDescriptorField.DESCRIPTION));
assertTrue(atts.containsKey(PropertyDescriptorField.DEFAULT_VALUE));
}
@Test
void testAddAttributesMulti() {
Map<PropertyDescriptorField, String> multiAtts = createMultiProperty().attributeValuesById();
assertTrue(multiAtts.containsKey(PropertyDescriptorField.DELIMITER));
assertTrue(multiAtts.containsKey(PropertyDescriptorField.NAME));
assertTrue(multiAtts.containsKey(PropertyDescriptorField.DESCRIPTION));
assertTrue(multiAtts.containsKey(PropertyDescriptorField.DEFAULT_VALUE));
}
@Test
void testType() {
assertNotNull(createProperty().type());
}
@Test
void testTypeMulti() {
assertNotNull(createMultiProperty().type());
}
static boolean randomBool() {
return RANDOM.nextBoolean();
}
static char randomChar(char[] characters) {
return characters[randomInt(0, characters.length)];
}
static int randomInt(int min, int max) {
return (int) randomLong(min, max);
}
static float randomFloat(float min, float max) {
return (float) randomDouble(min, max);
}
static double randomDouble(double min, double max) {
return min + RANDOM.nextDouble() * Math.abs(max - min);
}
static long randomLong(long min, long max) {
return min + RANDOM.nextInt((int) Math.abs(max - min));
}
static <T> T randomChoice(T[] items) {
return items[randomInt(0, items.length)];
}
/**
* Method filter.
*
* @param chars char[]
* @param removeChar char
* @return char[]
*/
protected static char[] filter(char[] chars, char removeChar) {
int count = 0;
for (char c : chars) {
if (c == removeChar) {
count++;
}
}
char[] results = new char[chars.length - count];
int index = 0;
for (char c : chars) {
if (c != removeChar) {
results[index++] = c;
}
}
return results;
}
}
| 11,284 | 30.522346 | 133 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/DoublePropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* Evaluates the functionality of the DoubleProperty descriptor by testing its
* ability to catch creation errors (illegal args), flag out-of-range test
* values, and serialize/deserialize groups of double values onto/from a string
* buffer.
*
* @author Brian Remedios
*/
@Deprecated
class DoublePropertyTest extends AbstractNumericPropertyDescriptorTester<Double> {
private static final double MIN = -10.0;
private static final double MAX = 100.0;
private static final double SHIFT = 5.0;
DoublePropertyTest() {
super("Double");
}
@Override
protected Double createValue() {
return randomDouble(MIN, MAX);
}
@Override
protected Double createBadValue() {
return randomBool() ? randomDouble(MIN - SHIFT, MIN - 0.01) : randomDouble(MAX + 0.01, MAX + SHIFT);
}
protected DoubleProperty.DoublePBuilder singleBuilder() {
return DoubleProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValue(createValue()).uiOrder(1.0f);
}
protected DoubleMultiProperty.DoubleMultiPBuilder multiBuilder() {
return DoubleMultiProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValues(createValue(), createValue()).uiOrder(1.0f);
}
@Override
protected PropertyDescriptor<Double> createProperty() {
return new DoubleProperty("testDouble", "Test double property", MIN, MAX, 9.0, 1.0f);
}
@Override
protected PropertyDescriptor<List<Double>> createMultiProperty() {
return new DoubleMultiProperty("testDouble", "Test double property", MIN, MAX,
new Double[] {-1d, 0d, 1d, 2d}, 1.0f);
}
@Override
protected PropertyDescriptor<Double> createBadProperty() {
return new DoubleProperty("testDouble", "Test double property", MAX, MIN, 9.0, 1.0f);
}
@Override
protected PropertyDescriptor<List<Double>> createBadMultiProperty() {
return new DoubleMultiProperty("testDouble", "Test double property", MIN, MAX,
new Double[] {MIN - SHIFT, MIN, MIN + SHIFT, MAX + SHIFT}, 1.0f);
}
@Override
protected Double min() {
return MIN;
}
@Override
protected Double max() {
return MAX;
}
}
| 2,507 | 26.26087 | 109 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/BooleanPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Brian Remedios
*/
class BooleanPropertyTest extends AbstractPropertyDescriptorTester<Boolean> {
BooleanPropertyTest() {
super("Boolean");
}
@Override
protected Boolean createValue() {
return randomBool();
}
@Override
@Test
void testErrorForBadSingle() {
// override, cannot create a 'bad' boolean per se
}
@Override
@Test
void testErrorForBadMulti() {
// override, cannot create a 'bad' boolean per se
}
@Override
protected Boolean createBadValue() {
return null;
}
@Override
protected PropertyDescriptor<Boolean> createProperty() {
return new BooleanProperty("testBoolean", "Test boolean property", false, 1.0f);
}
@Override
protected PropertyDescriptor<List<Boolean>> createMultiProperty() {
return new BooleanMultiProperty("testBoolean", "Test boolean property",
new Boolean[] {false, true, true}, 1.0f);
}
@Override
protected PropertyDescriptor<List<Boolean>> createBadMultiProperty() {
return new BooleanMultiProperty("", "Test boolean property", new Boolean[] {false, true, true}, 1.0f);
}
@Override
protected PropertyDescriptor<Boolean> createBadProperty() {
return new BooleanProperty("testBoolean", "", false, 1.0f);
}
}
| 1,578 | 20.930556 | 110 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/LongPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* @author Clément Fournier
*/
@Deprecated
class LongPropertyTest extends AbstractNumericPropertyDescriptorTester<Long> {
private static final long MIN = 10L;
private static final long MAX = 11000L;
private static final long SHIFT = 300L;
LongPropertyTest() {
super("Long");
}
@Override
protected Long createValue() {
return randomLong(MIN, MAX);
}
@Override
protected Long createBadValue() {
return randomBool() ? randomLong(MIN - SHIFT, MIN) : randomLong(MAX + 1, MAX + SHIFT);
}
@Override
protected LongProperty.LongPBuilder singleBuilder() {
return LongProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValue(createValue()).uiOrder(1.0f);
}
@Override
protected LongMultiProperty.LongMultiPBuilder multiBuilder() {
return LongMultiProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValues(createValue(), createValue()).uiOrder(1.0f);
}
@Override
protected PropertyDescriptor<Long> createProperty() {
return new LongProperty("testFloat", "Test float property", MIN, MAX, 90L, 1.0f);
}
@Override
protected PropertyDescriptor<List<Long>> createMultiProperty() {
return new LongMultiProperty("testFloat", "Test float property", MIN, MAX,
new Long[]{1000L, 10L, 100L, 20L}, 1.0f);
}
@Override
protected PropertyDescriptor<Long> createBadProperty() {
return new LongProperty("testFloat", "Test float property", 200L, -400L, 900L, 1.0f);
}
@Override
protected PropertyDescriptor<List<Long>> createBadMultiProperty() {
return new LongMultiProperty("testFloat", "Test float property", 0L, 5L,
new Long[]{-1000L, 0L, 100L, 20L}, 1.0f);
}
@Override
protected Long min() {
return MIN;
}
@Override
protected Long max() {
return MAX;
}
}
| 2,138 | 23.033708 | 107 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/CharacterPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Evaluates the functionality of the CharacterProperty descriptor by testing
* its ability to catch creation errors (illegal args), flag invalid characters,
* and serialize/deserialize any default values.
*
* @author Brian Remedios
*/
@Deprecated
class CharacterPropertyTest extends AbstractPropertyDescriptorTester<Character> {
private static final char DELIMITER = '|';
private static final char[] CHARSET = filter(ALL_CHARS.toCharArray(), DELIMITER);
CharacterPropertyTest() {
super("Character");
}
@Override
@Test
void testErrorForBadSingle() {
} // not until char properties use illegal chars
@Override
@Test
void testErrorForBadMulti() {
} // not until char properties use illegal chars
@Override
protected Character createValue() {
return randomChar(CHARSET);
}
@Override
protected Character createBadValue() {
return null;
}
@Override
protected PropertyDescriptor<Character> createProperty() {
return new CharacterProperty("testCharacter", "Test character property", 'a', 1.0f);
}
@Override
protected PropertyDescriptor<List<Character>> createMultiProperty() {
return new CharacterMultiProperty("testCharacter", "Test character property",
new Character[] {'a', 'b', 'c'}, 1.0f, DELIMITER);
}
@Override
protected PropertyDescriptor<Character> createBadProperty() {
return new CharacterProperty("", "Test character property", 'a', 1.0f);
}
@Override
protected PropertyDescriptor<List<Character>> createBadMultiProperty() {
return new CharacterMultiProperty("testCharacter", "Test character property",
new Character[] {'a', 'b', 'c'}, 1.0f, DELIMITER);
}
}
| 2,041 | 24.848101 | 92 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/RegexPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
import java.util.regex.Pattern;
/**
* Since there's no RegexMultiProperty the base class is only partially implemented,
* and some tests are overridden with no-op ones.
*
* @author Clément Fournier
* @since 6.2.0
*/
@Deprecated
class RegexPropertyTest extends AbstractPropertyDescriptorTester<Pattern> {
RegexPropertyTest() {
super("Regex");
}
@Override
protected Pattern createValue() {
return Pattern.compile("abc++");
}
@Override
protected Pattern createBadValue() {
return null;
}
@Override
protected PropertyDescriptor<Pattern> createProperty() {
return RegexProperty.named("foo").defaultValue("(ec|sa)+").desc("the description").build();
}
@Override
protected PropertyDescriptor<Pattern> createBadProperty() {
return RegexProperty.named("foo").defaultValue("(ec|sa").desc("the description").build();
}
// The following are deliberately unimplemented, since they are only relevant to the tests of the multiproperty
@Override
protected PropertyDescriptor<List<Pattern>> createMultiProperty() {
throw new UnsupportedOperationException();
}
@Override
protected PropertyDescriptor<List<Pattern>> createBadMultiProperty() {
throw new UnsupportedOperationException();
}
@Override
void testAddAttributesMulti() {
}
@Override
void testAsDelimitedString() {
}
@Override
void testErrorForBadMulti() {
}
@Override
void testErrorForCorrectMulti() {
}
@Override
void testFactoryMultiValueDefaultDelimiter() {
}
@Override
void testFactoryMultiValueCustomDelimiter() {
}
@Override
void testTypeMulti() {
}
@Override
void testIsMultiValueMulti() {
}
}
| 1,968 | 18.116505 | 115 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/PropertyDescriptorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static java.util.Collections.emptyList;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.core.SubstringMatcher;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.properties.constraints.PropertyConstraint;
/**
* Mostly TODO, I'd rather implement tests on the final version of the framework.
*
* @author Clément Fournier
* @since 7.0.0
*/
class PropertyDescriptorTest {
@Test
void testConstraintViolationCausesDysfunctionalRule() {
PropertyDescriptor<Integer> intProperty = PropertyFactory.intProperty("fooProp")
.desc("hello")
.defaultValue(4)
.require(inRange(1, 10))
.build();
FooRule rule = new FooRule();
rule.definePropertyDescriptor(intProperty);
rule.setProperty(intProperty, 1000);
RuleSet ruleSet = RuleSet.forSingleRule(rule);
List<Rule> dysfunctional = new ArrayList<>();
ruleSet.removeDysfunctionalRules(dysfunctional);
assertEquals(1, dysfunctional.size());
assertThat(dysfunctional, hasItem(rule));
}
@Test
void testConstraintViolationCausesDysfunctionalRuleMulti() {
PropertyDescriptor<List<Double>> descriptor = PropertyFactory.doubleListProperty("fooProp")
.desc("hello")
.defaultValues(2., 11.) // 11. is in range
.requireEach(inRange(1d, 20d))
.build();
FooRule rule = new FooRule();
rule.definePropertyDescriptor(descriptor);
rule.setProperty(descriptor, Collections.singletonList(1000d)); // not in range
RuleSet ruleSet = RuleSet.forSingleRule(rule);
List<Rule> dysfunctional = new ArrayList<>();
ruleSet.removeDysfunctionalRules(dysfunctional);
assertEquals(1, dysfunctional.size());
assertThat(dysfunctional, hasItem(rule));
}
@Test
void testDefaultValueConstraintViolationCausesFailure() {
PropertyConstraint<Integer> constraint = inRange(1, 10);
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
PropertyFactory.intProperty("fooProp")
.desc("hello")
.defaultValue(1000)
.require(constraint)
.build());
assertThat(thrown.getMessage(), allOf(containsIgnoreCase("Constraint violat"/*-ed or -ion*/),
containsIgnoreCase(constraint.getConstraintDescription())));
}
@Test
void testDefaultValueConstraintViolationCausesFailureMulti() {
PropertyConstraint<Double> constraint = inRange(1d, 10d);
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
PropertyFactory.doubleListProperty("fooProp")
.desc("hello")
.defaultValues(2., 11.) // 11. is out of range
.requireEach(constraint)
.build());
assertThat(thrown.getMessage(), allOf(containsIgnoreCase("Constraint violat"/*-ed or -ion*/),
containsIgnoreCase(constraint.getConstraintDescription())));
}
@Test
void testNoConstraintViolationCausesIsOkMulti() {
PropertyDescriptor<List<Double>> descriptor = PropertyFactory.doubleListProperty("fooProp")
.desc("hello")
.defaultValues(2., 11.) // 11. is in range
.requireEach(inRange(1d, 20d))
.build();
assertEquals("fooProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertThat(descriptor.defaultValue(), Matchers.contains(2., 11.));
}
@Test
void testNoConstraintViolationCausesIsOk() {
PropertyDescriptor<String> descriptor = PropertyFactory.stringProperty("fooProp")
.desc("hello")
.defaultValue("bazooli")
.build();
assertEquals("fooProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals("bazooli", descriptor.defaultValue());
}
@Test
void testIntProperty() {
PropertyDescriptor<Integer> descriptor = PropertyFactory.intProperty("intProp")
.desc("hello")
.defaultValue(1)
.build();
assertEquals("intProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals(Integer.valueOf(1), descriptor.defaultValue());
assertEquals(Integer.valueOf(5), descriptor.valueFrom("5"));
assertEquals(Integer.valueOf(5), descriptor.valueFrom(" 5 "));
PropertyDescriptor<List<Integer>> listDescriptor = PropertyFactory.intListProperty("intListProp")
.desc("hello")
.defaultValues(1, 2)
.build();
assertEquals("intListProp", listDescriptor.name());
assertEquals("hello", listDescriptor.description());
assertEquals(Arrays.asList(1, 2), listDescriptor.defaultValue());
assertEquals(Arrays.asList(5, 7), listDescriptor.valueFrom("5,7"));
assertEquals(Arrays.asList(5, 7), listDescriptor.valueFrom(" 5 , 7 "));
}
@Test
void testIntPropertyInvalidValue() {
PropertyDescriptor<Integer> descriptor = PropertyFactory.intProperty("intProp")
.desc("hello")
.defaultValue(1)
.build();
NumberFormatException thrown = assertThrows(NumberFormatException.class, () ->
descriptor.valueFrom("not a number"));
assertThat(thrown.getMessage(), containsString("not a number"));
}
@Test
void testDoubleProperty() {
PropertyDescriptor<Double> descriptor = PropertyFactory.doubleProperty("doubleProp")
.desc("hello")
.defaultValue(1.0)
.build();
assertEquals("doubleProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals(Double.valueOf(1.0), descriptor.defaultValue());
assertEquals(Double.valueOf(2.0), descriptor.valueFrom("2.0"));
assertEquals(Double.valueOf(2.0), descriptor.valueFrom(" 2.0 "));
PropertyDescriptor<List<Double>> listDescriptor = PropertyFactory.doubleListProperty("doubleListProp")
.desc("hello")
.defaultValues(1.0, 2.0)
.build();
assertEquals("doubleListProp", listDescriptor.name());
assertEquals("hello", listDescriptor.description());
assertEquals(Arrays.asList(1.0, 2.0), listDescriptor.defaultValue());
assertEquals(Arrays.asList(2.0, 3.0), listDescriptor.valueFrom("2.0,3.0"));
assertEquals(Arrays.asList(2.0, 3.0), listDescriptor.valueFrom(" 2.0 , 3.0 "));
}
@Test
void testDoublePropertyInvalidValue() {
PropertyDescriptor<Double> descriptor = PropertyFactory.doubleProperty("doubleProp")
.desc("hello")
.defaultValue(1.0)
.build();
NumberFormatException thrown = assertThrows(NumberFormatException.class, () ->
descriptor.valueFrom("this is not a number"));
assertThat(thrown.getMessage(), containsString("this is not a number"));
}
@Test
void testStringProperty() {
PropertyDescriptor<String> descriptor = PropertyFactory.stringProperty("stringProp")
.desc("hello")
.defaultValue("default value")
.build();
assertEquals("stringProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals("default value", descriptor.defaultValue());
assertEquals("foo", descriptor.valueFrom("foo"));
assertEquals("foo", descriptor.valueFrom(" foo "));
PropertyDescriptor<List<String>> listDescriptor = PropertyFactory.stringListProperty("stringListProp")
.desc("hello")
.defaultValues("v1", "v2")
.build();
assertEquals("stringListProp", listDescriptor.name());
assertEquals("hello", listDescriptor.description());
assertEquals(Arrays.asList("v1", "v2"), listDescriptor.defaultValue());
assertEquals(Arrays.asList("foo", "bar"), listDescriptor.valueFrom("foo|bar"));
assertEquals(Arrays.asList("foo", "bar"), listDescriptor.valueFrom(" foo | bar "));
}
private enum SampleEnum { A, B, C }
private static Map<String, SampleEnum> nameMap = new LinkedHashMap<>();
static {
nameMap.put("TEST_A", SampleEnum.A);
nameMap.put("TEST_B", SampleEnum.B);
nameMap.put("TEST_C", SampleEnum.C);
}
@Test
void testEnumProperty() {
PropertyDescriptor<SampleEnum> descriptor = PropertyFactory.enumProperty("enumProp", nameMap)
.desc("hello")
.defaultValue(SampleEnum.B)
.build();
assertEquals("enumProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals(SampleEnum.B, descriptor.defaultValue());
assertEquals(SampleEnum.C, descriptor.valueFrom("TEST_C"));
PropertyDescriptor<List<SampleEnum>> listDescriptor = PropertyFactory.enumListProperty("enumListProp", nameMap)
.desc("hello")
.defaultValues(SampleEnum.A, SampleEnum.B)
.build();
assertEquals("enumListProp", listDescriptor.name());
assertEquals("hello", listDescriptor.description());
assertEquals(Arrays.asList(SampleEnum.A, SampleEnum.B), listDescriptor.defaultValue());
assertEquals(Arrays.asList(SampleEnum.B, SampleEnum.C), listDescriptor.valueFrom("TEST_B|TEST_C"));
}
@Test
void testEnumPropertyNullValueFailsBuild() {
Map<String, SampleEnum> map = new HashMap<>(nameMap);
map.put("TEST_NULL", null);
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
PropertyFactory.enumProperty("enumProp", map));
assertThat(thrown.getMessage(), containsIgnoreCase("null value"));
}
@Test
void testEnumListPropertyNullValueFailsBuild() {
Map<String, SampleEnum> map = new HashMap<>(nameMap);
map.put("TEST_NULL", null);
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
PropertyFactory.enumListProperty("enumProp", map));
assertThat(thrown.getMessage(), containsIgnoreCase("null value"));
}
@Test
void testEnumPropertyInvalidValue() {
PropertyDescriptor<SampleEnum> descriptor = PropertyFactory.enumProperty("enumProp", nameMap)
.desc("hello")
.defaultValue(SampleEnum.B)
.build();
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () ->
descriptor.valueFrom("InvalidEnumValue"));
assertThat(thrown.getMessage(), containsString("Value was not in the set [TEST_A, TEST_B, TEST_C]"));
}
@Test
void testRegexProperty() {
PropertyDescriptor<Pattern> descriptor = PropertyFactory.regexProperty("regexProp")
.desc("hello")
.defaultValue("^[A-Z].*$")
.build();
assertEquals("regexProp", descriptor.name());
assertEquals("hello", descriptor.description());
assertEquals("^[A-Z].*$", descriptor.defaultValue().toString());
assertEquals("[0-9]+", descriptor.valueFrom("[0-9]+").toString());
}
@Test
void testRegexPropertyInvalidValue() {
PropertyDescriptor<Pattern> descriptor = PropertyFactory.regexProperty("regexProp")
.desc("hello")
.defaultValue("^[A-Z].*$")
.build();
PatternSyntaxException thrown = assertThrows(PatternSyntaxException.class, () ->
descriptor.valueFrom("[open class"));
assertThat(thrown.getMessage(), containsString("Unclosed character class"));
}
@Test
void testRegexPropertyInvalidDefaultValue() {
PatternSyntaxException thrown = assertThrows(PatternSyntaxException.class, () ->
PropertyFactory.regexProperty("regexProp")
.desc("hello")
.defaultValue("[open class")
.build());
assertThat(thrown.getMessage(), containsString("Unclosed character class"));
}
private static List<String> parseEscaped(String s, char d) {
return ValueParserConstants.parseListWithEscapes(s, d, ValueParserConstants.STRING_PARSER);
}
@Test
void testStringParserEmptyString() {
assertEquals(emptyList(), parseEscaped("", ','));
}
@Test
void testStringParserSimple() {
assertEquals(listOf("a", "b", "c"),
parseEscaped("a,b,c", ','));
}
@Test
void testStringParserEscapedChar() {
assertEquals(listOf("a", "b,c"),
parseEscaped("a,b\\,c", ','));
}
@Test
void testStringParserEscapedEscapedChar() {
assertEquals(listOf("a", "b\\", "c"),
parseEscaped("a,b\\\\,c", ','));
}
@Test
void testStringParserDelimIsBackslash() {
assertEquals(listOf("a,b", "", ",c"),
parseEscaped("a,b\\\\,c", '\\'));
}
@Test
void testStringParserTrailingBackslash() {
assertEquals(listOf("a", "b\\"),
parseEscaped("a,b\\", ','));
}
private static Matcher<String> containsIgnoreCase(final String substring) {
return new SubstringMatcher("containing (ignoring case)", true, substring) {
@Override
protected boolean evalSubstringOf(String string) {
return StringUtils.indexOfIgnoreCase(string, substring) != -1;
}
};
}
}
| 15,755 | 39.296675 | 119 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/AbstractNumericPropertyDescriptorTester.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.properties.builders.MultiNumericPropertyBuilder;
import net.sourceforge.pmd.properties.builders.SingleNumericPropertyBuilder;
/**
* @author Clément Fournier
*/
abstract class AbstractNumericPropertyDescriptorTester<T> extends AbstractPropertyDescriptorTester<T> {
AbstractNumericPropertyDescriptorTester(String typeName) {
super(typeName);
}
@Test
void testLowerUpperLimit() {
assertNotNull(((NumericPropertyDescriptor<T>) createProperty()).lowerLimit());
assertNotNull(((NumericPropertyDescriptor<T>) createProperty()).upperLimit());
assertNotNull(((NumericPropertyDescriptor<T>) createMultiProperty()).lowerLimit());
assertNotNull(((NumericPropertyDescriptor<T>) createMultiProperty()).upperLimit());
}
@Test
void testMissingMinThreshold() {
Map<PropertyDescriptorField, String> attributes = getPropertyDescriptorValues();
attributes.remove(PropertyDescriptorField.MIN);
assertThrows(RuntimeException.class, () -> getSingleFactory().build(attributes));
}
@Override
protected Map<PropertyDescriptorField, String> getPropertyDescriptorValues() {
Map<PropertyDescriptorField, String> attributes = super.getPropertyDescriptorValues();
attributes.put(PropertyDescriptorField.MIN, min().toString());
attributes.put(PropertyDescriptorField.MAX, max().toString());
return attributes;
}
@Test
void testMissingMaxThreshold() {
Map<PropertyDescriptorField, String> attributes = getPropertyDescriptorValues();
attributes.remove(PropertyDescriptorField.MAX);
assertThrows(RuntimeException.class, () -> getSingleFactory().build(attributes));
}
@Test
void testBadDefaultValue() {
assertThrows(IllegalArgumentException.class, () -> singleBuilder().defaultValue(createBadValue()).build());
}
@Test
@SuppressWarnings("unchecked")
void testMultiBadDefaultValue() {
assertThrows(IllegalArgumentException.class, () -> multiBuilder().defaultValues(createValue(), createBadValue()).build());
}
protected abstract SingleNumericPropertyBuilder<T, ?> singleBuilder();
protected abstract MultiNumericPropertyBuilder<T, ?> multiBuilder();
protected abstract T min();
protected abstract T max();
}
| 2,670 | 30.797619 | 130 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/FloatPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* Evaluates the functionality of the FloatProperty descriptor by testing its
* ability to catch creation errors (illegal args), flag out-of-range test
* values, and serialize/deserialize groups of float values onto/from a string
* buffer.
*
* @author Brian Remedios
*/
class FloatPropertyTest extends AbstractNumericPropertyDescriptorTester<Float> {
private static final float MIN = 1.0f;
private static final float MAX = 11.0f;
private static final float SHIFT = 3.0f;
FloatPropertyTest() {
super("Float");
}
@Override
protected Float createValue() {
return randomFloat(MIN, MAX);
}
@Override
protected Float createBadValue() {
return randomBool() ? randomFloat(MIN - SHIFT, MIN) : randomFloat(MAX + 1, MAX + SHIFT);
}
@Override
protected FloatProperty.FloatPBuilder singleBuilder() {
return FloatProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValue(createValue()).uiOrder(1.0f);
}
@Override
protected FloatMultiProperty.FloatMultiPBuilder multiBuilder() {
return FloatMultiProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValues(createValue(), createValue()).uiOrder(1.0f);
}
@Override
protected PropertyDescriptor<Float> createProperty() {
return new FloatProperty("testFloat", "Test float property", MIN, MAX, 9.0f, 1.0f);
}
@Override
protected PropertyDescriptor<List<Float>> createMultiProperty() {
return new FloatMultiProperty("testFloat", "Test float property", MIN, MAX,
new Float[]{6f, 9f, 1f, 2f}, 1.0f);
}
@Override
protected PropertyDescriptor<Float> createBadProperty() {
return new FloatProperty("testFloat", "Test float property", 5f, 4f, 9.0f, 1.0f);
}
@Override
protected PropertyDescriptor<List<Float>> createBadMultiProperty() {
return new FloatMultiProperty("testFloat", "Test float property", 0f, 5f,
new Float[]{-1f, 0f, 1f, 2f}, 1.0f);
}
@Override
protected Float min() {
return MIN;
}
@Override
protected Float max() {
return MAX;
}
}
| 2,387 | 24.136842 | 108 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/SimpleEnumeratedPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.properties.SimpleEnumeratedPropertyTest.Foo;
/**
* Evaluates the functionality of the EnumeratedProperty descriptor by testing
* its ability to catch creation errors (illegal args), flag invalid selections,
* and serialize/deserialize selection options.
*
* @author Brian Remedios
*/
@Deprecated
class SimpleEnumeratedPropertyTest extends AbstractPropertyDescriptorTester<Foo> {
private static final String[] KEYS = {"bar", "na", "bee", "coo"};
private static final Foo[] VALUES = {Foo.BAR, Foo.NA, Foo.BEE, Foo.COO};
private static final Map<String, Foo> MAPPINGS;
static {
Map<String, Foo> map = new HashMap<>();
map.put("bar", Foo.BAR);
map.put("na", Foo.NA);
map.put("bee", Foo.BEE);
map.put("coo", Foo.COO);
MAPPINGS = Collections.unmodifiableMap(map);
}
SimpleEnumeratedPropertyTest() {
super("Enum");
}
@Test
void testMappings() {
EnumeratedPropertyDescriptor<Foo, Foo> prop
= (EnumeratedPropertyDescriptor<Foo, Foo>) createProperty();
EnumeratedPropertyDescriptor<Foo, List<Foo>> multi
= (EnumeratedPropertyDescriptor<Foo, List<Foo>>) createMultiProperty();
assertEquals(MAPPINGS, prop.mappings());
assertEquals(MAPPINGS, multi.mappings());
}
@Override
protected PropertyDescriptor<Foo> createProperty() {
return new EnumeratedProperty<>("testEnumerations",
"Test enumerations with complex types",
KEYS,
VALUES, 0, Foo.class,
1.0f);
}
@Override
protected PropertyDescriptor<List<Foo>> createMultiProperty() {
return new EnumeratedMultiProperty<>("testEnumerations",
"Test enumerations with complex types",
KEYS,
VALUES,
new int[] {0, 1}, Foo.class, 1.0f);
}
@Test
void testDefaultIndexOutOfBounds() {
assertThrows(IllegalArgumentException.class, () ->
new EnumeratedMultiProperty<>("testEnumerations", "Test enumerations with simple type",
KEYS, VALUES, new int[] {99}, Foo.class, 1.0f));
}
@Test
void testNoMappingForDefault() {
assertThrows(IllegalArgumentException.class, () ->
new EnumeratedMultiProperty<>("testEnumerations", "Test enumerations with simple type",
MAPPINGS, Collections.singletonList(Foo.IGNORED), Foo.class, 1.0f));
}
@Test
void creationTest() {
PropertyDescriptor<Foo> prop = createProperty();
PropertyDescriptor<List<Foo>> multi = createMultiProperty();
for (Map.Entry<String, Foo> e : MAPPINGS.entrySet()) {
assertEquals(e.getValue(), prop.valueFrom(e.getKey()));
assertTrue(multi.valueFrom(e.getKey()).contains(e.getValue()));
}
}
@Override
protected Foo createValue() {
return randomChoice(VALUES);
}
@Override
protected Foo createBadValue() {
return Foo.IGNORED; // not in the set of values
}
@Override
protected PropertyDescriptor<Foo> createBadProperty() {
return new EnumeratedProperty<>("testEnumerations", "Test enumerations with simple type",
new String[0], VALUES, -1, Foo.class, 1.0f);
}
@Override
protected PropertyDescriptor<List<Foo>> createBadMultiProperty() {
return new EnumeratedMultiProperty<>("testEnumerations", "Test enumerations with simple type",
KEYS, VALUES, new int[] {99}, Foo.class, 1.0f);
}
@Override
@Test
@Disabled("The EnumeratedProperty factory is not implemented yet")
void testFactorySingleValue() {
}
@Override
@Test
@Disabled("The EnumeratedProperty factory is not implemented yet")
void testFactoryMultiValueCustomDelimiter() {
}
@Override
@Test
@Disabled("The EnumeratedProperty factory is not implemented yet")
void testFactoryMultiValueDefaultDelimiter() {
}
enum Foo {
BAR, NA, BEE, COO, IGNORED
}
}
| 4,933 | 29.45679 | 110 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/IntegerPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* Evaluates the functionality of the IntegerProperty descriptor by testing its
* ability to catch creation errors (illegal args), flag out-of-range test
* values, and serialize/deserialize groups of integers onto/from a string
* buffer.
*
* @author Brian Remedios
*/
@Deprecated
class IntegerPropertyTest extends AbstractNumericPropertyDescriptorTester<Integer> {
private static final int MIN = 1;
private static final int MAX = 12;
private static final int SHIFT = 4;
IntegerPropertyTest() {
super("Integer");
}
@Override
protected Integer createValue() {
return randomInt(MIN, MAX);
}
@Override
protected Integer createBadValue() {
return randomBool() ? randomInt(MIN - SHIFT, MIN - 1) : randomInt(MAX + 1, MAX + SHIFT);
}
protected IntegerProperty.IntegerPBuilder singleBuilder() {
return IntegerProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValue(createValue()).uiOrder(1.0f);
}
protected IntegerMultiProperty.IntegerMultiPBuilder multiBuilder() {
return IntegerMultiProperty.named("test").desc("foo")
.range(MIN, MAX).defaultValues(createValue(), createValue()).uiOrder(1.0f);
}
@Override
protected PropertyDescriptor<Integer> createProperty() {
return new IntegerProperty("testInteger", "Test integer property", MIN, MAX, MAX - 1, 1.0f);
}
@Override
protected PropertyDescriptor<List<Integer>> createMultiProperty() {
return new IntegerMultiProperty("testInteger", "Test integer property", MIN, MAX,
new Integer[] {MIN, MIN + 1, MAX - 1, MAX}, 1.0f);
}
@Override
protected PropertyDescriptor<Integer> createBadProperty() {
return new IntegerProperty("", "Test integer property", MIN, MAX, MAX + 1, 1.0f);
}
@Override
protected PropertyDescriptor<List<Integer>> createBadMultiProperty() {
return new IntegerMultiProperty("testInteger", "", MIN, MAX, new Integer[] {MIN - 1, MAX}, 1.0f);
}
@Override
protected Integer min() {
return MIN;
}
@Override
protected Integer max() {
return MAX;
}
}
| 2,424 | 25.358696 | 110 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/StringPropertyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* Evaluates the functionality of the StringProperty descriptor by testing its
* ability to catch creation errors (illegal args), flag invalid strings per any
* specified expressions, and serialize/deserialize groups of strings onto/from
* a string buffer.
*
* @author Brian Remedios
*/
class StringPropertyTest extends AbstractPropertyDescriptorTester<String> {
private static final int MAX_STRING_LENGTH = 52;
private static final char DELIMITER = '|';
private static final char[] CHARSET = filter(ALL_CHARS.toCharArray(), DELIMITER);
StringPropertyTest() {
super("String");
}
@Override
protected String createValue() {
return newString();
}
/**
* Method newString.
*
* @return String
*/
private String newString() {
int strLength = randomInt(1, MAX_STRING_LENGTH);
char[] chars = new char[strLength];
for (int i = 0; i < chars.length; i++) {
chars[i] = randomCharIn(CHARSET);
}
return new String(chars);
}
/**
* Method randomCharIn.
*
* @param chars char[]
*
* @return char
*/
private char randomCharIn(char[] chars) {
return randomChar(chars);
}
@Override
protected String createBadValue() {
return null;
}
@Override
protected PropertyDescriptor<String> createProperty() {
return new StringProperty("testString", "Test string property", "brian", 1.0f);
}
@Override
protected PropertyDescriptor<List<String>> createMultiProperty() {
return new StringMultiProperty("testString", "Test string property",
new String[] {"hello", "world"}, 1.0f, DELIMITER);
}
@Override
protected PropertyDescriptor<String> createBadProperty() {
return new StringProperty("", "Test string property", "brian", 1.0f);
}
@Override
protected PropertyDescriptor<List<String>> createBadMultiProperty() {
return new StringMultiProperty("testString", "Test string property",
new String[] {"hello", "world", "a" + DELIMITER + "b"}, 1.0f, DELIMITER);
}
}
| 2,371 | 23.968421 | 112 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/properties/constraints/NumericConstraintsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.constraints;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class NumericConstraintsTest {
@Test
void testInRangeInteger() {
PropertyConstraint<Integer> constraint = NumericConstraints.inRange(1, 10);
assertTrue(constraint.test(1));
assertTrue(constraint.test(5));
assertTrue(constraint.test(10));
assertFalse(constraint.test(0));
assertFalse(constraint.test(-1));
assertFalse(constraint.test(11));
assertFalse(constraint.test(100));
}
@Test
void testInRangeDouble() {
PropertyConstraint<Double> constraint = NumericConstraints.inRange(1.0, 10.0);
assertTrue(constraint.test(1.0));
assertTrue(constraint.test(5.5));
assertTrue(constraint.test(10.0));
assertFalse(constraint.test(0.0));
assertFalse(constraint.test(-1.0));
assertFalse(constraint.test(11.1));
assertFalse(constraint.test(100.0));
}
@Test
void testPositive() {
PropertyConstraint<Number> constraint = NumericConstraints.positive();
assertTrue(constraint.test(1));
assertTrue(constraint.test(1.5f));
assertTrue(constraint.test(1.5d));
assertTrue(constraint.test(100));
assertFalse(constraint.test(0));
assertFalse(constraint.test(0.1f));
assertFalse(constraint.test(0.9d));
assertFalse(constraint.test(-1));
assertFalse(constraint.test(-100));
assertFalse(constraint.test(-0.1f));
assertFalse(constraint.test(-0.1d));
}
}
| 1,786 | 32.092593 | 86 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.reporting;
import static net.sourceforge.pmd.reporting.ConfigurableFileNameRenderer.getDisplayName;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.FileId;
class ConfigurableFileNameRendererTest {
@Test
void testRelativize() {
FileId file = FileId.fromPath(Paths.get("a", "b", "c"));
String displayName = getDisplayName(file, listOf(Paths.get("a")));
assertEquals(displayName, Paths.get("b", "c").toString());
}
@Test
void testRelativizeOutOfDir() {
FileId file = FileId.fromPath(Paths.get("a", "b", "c"));
String displayName = getDisplayName(file, listOf(Paths.get("d")));
assertEquals(displayName, Paths.get("..", "a", "b", "c").toString());
}
@Test
void testRelativizeWithRoot() {
Path path = Paths.get("a", "b", "c");
FileId file = FileId.fromPath(path);
String displayName = getDisplayName(file, listOf(Paths.get("/")));
assertEquals(path.toAbsolutePath().toString(),
displayName);
}
}
| 1,360 | 29.244444 | 88 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/reporting/GlobalAnalysisListenerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.reporting;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.cache.AnalysisCache;
import net.sourceforge.pmd.cache.NoopAnalysisCache;
import net.sourceforge.pmd.lang.ast.FileAnalysisException;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileId;
class GlobalAnalysisListenerTest {
static final int NUM_DATA_SOURCES = 3;
@Test
void testViolationCounter() {
PMDConfiguration config = newConfig();
GlobalAnalysisListener.ViolationCounterListener listener = new GlobalAnalysisListener.ViolationCounterListener();
MyFooRule mockrule = Mockito.spy(MyFooRule.class);
runPmd(config, listener, mockrule);
Mockito.verify(mockrule, times(NUM_DATA_SOURCES)).apply(any(), any());
assertEquals(2, (int) listener.getResult());
}
@Test
void testViolationCounterOnMulti() {
PMDConfiguration config = newConfig();
config.setThreads(2);
GlobalAnalysisListener.ViolationCounterListener listener = new GlobalAnalysisListener.ViolationCounterListener();
MyFooRule mockrule = Mockito.spy(MyFooRule.class);
when(mockrule.deepCopy()).thenReturn(mockrule); // the spy cannot track the deep copies
runPmd(config, listener, mockrule);
Mockito.verify(mockrule, times(NUM_DATA_SOURCES)).apply(any(), any());
assertEquals(2, (int) listener.getResult());
}
@Test
void testAnalysisCache() throws Exception {
PMDConfiguration config = newConfig();
AnalysisCache mockCache = spy(NoopAnalysisCache.class);
config.setAnalysisCache(mockCache);
MyFooRule rule = new MyFooRule();
runPmd(config, GlobalAnalysisListener.noop(), rule);
verify(mockCache).checkValidity(any(), any(), any());
verify(mockCache, times(1)).persist();
verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any());
}
@Test
void testCacheWithFailure() throws Exception {
PMDConfiguration config = newConfig();
AnalysisCache mockCache = spy(NoopAnalysisCache.class);
config.setAnalysisCache(mockCache);
BrokenRule rule = new BrokenRule(); // the broken rule throws
runPmd(config, GlobalAnalysisListener.noop(), rule);
// cache methods are called regardless
verify(mockCache).checkValidity(any(), any(), any());
verify(mockCache, times(1)).persist();
verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any());
}
@Test
void testCacheWithPropagatedException() throws Exception {
PMDConfiguration config = newConfig();
AnalysisCache mockCache = spy(NoopAnalysisCache.class);
config.setAnalysisCache(mockCache);
BrokenRule rule = new BrokenRule(); // the broken rule throws
// now the exception should be propagated
GlobalAnalysisListener listener = GlobalAnalysisListener.exceptionThrower();
FileAnalysisException exception = assertThrows(FileAnalysisException.class, () -> {
runPmd(config, listener, rule);
});
assertEquals("fname1.dummy", exception.getFileId().getOriginalPath());
// cache methods are called regardless
verify(mockCache).checkValidity(any(), any(), any());
verify(mockCache, times(1)).persist();
verify(mockCache, times(1)).isUpToDate(any());
}
@NonNull
private PMDConfiguration newConfig() {
PMDConfiguration config = new PMDConfiguration();
config.setAnalysisCache(new NoopAnalysisCache());
config.setIgnoreIncrementalAnalysis(true);
config.setThreads(0); // no multithreading for this test
return config;
}
private void runPmd(PMDConfiguration config, GlobalAnalysisListener listener, Rule rule) {
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRuleSet(RuleSet.forSingleRule(rule));
pmd.files().addSourceFile(FileId.fromPathLikeString("fname1.dummy"), "abc");
pmd.files().addSourceFile(FileId.fromPathLikeString("fname2.dummy"), "abcd");
pmd.files().addSourceFile(FileId.fromPathLikeString("fname21.dummy"), "abcd");
pmd.addListener(listener);
pmd.performAnalysis();
}
}
public static class MyFooRule extends FooRule {
@Override
public void apply(Node node, RuleContext ctx) {
if (node.getTextDocument().getFileId().getFileName().contains("1")) {
ctx.addViolation(node);
}
}
}
public static class BrokenRule extends FooRule {
@Override
public void apply(Node node, RuleContext ctx) {
throw new IllegalArgumentException("Something happened");
}
}
@Test
void teeShouldForwardAllEventsSingleListeners() throws Exception {
GlobalAnalysisListener mockListener1 = createMockListener();
GlobalAnalysisListener teed = GlobalAnalysisListener.tee(Arrays.asList(mockListener1));
teed.initializer();
teed.startFileAnalysis(null);
teed.onConfigError(null);
teed.close();
verifyMethods(mockListener1);
Mockito.verifyNoMoreInteractions(mockListener1);
}
@Test
void teeShouldForwardAllEventsMultipleListeners() throws Exception {
GlobalAnalysisListener mockListener1 = createMockListener();
GlobalAnalysisListener mockListener2 = createMockListener();
GlobalAnalysisListener teed = GlobalAnalysisListener.tee(Arrays.asList(mockListener1, mockListener2));
teed.initializer();
teed.startFileAnalysis(null);
teed.onConfigError(null);
teed.close();
verifyMethods(mockListener1);
verifyMethods(mockListener2);
Mockito.verifyNoMoreInteractions(mockListener1, mockListener2);
}
private GlobalAnalysisListener createMockListener() {
GlobalAnalysisListener mockListener = Mockito.mock(GlobalAnalysisListener.class);
Mockito.when(mockListener.initializer()).thenReturn(ListenerInitializer.noop());
Mockito.when(mockListener.startFileAnalysis(Mockito.any())).thenReturn(FileAnalysisListener.noop());
return mockListener;
}
private void verifyMethods(GlobalAnalysisListener listener) throws Exception {
Mockito.verify(listener, Mockito.times(1)).initializer();
Mockito.verify(listener, Mockito.times(1)).startFileAnalysis(null);
Mockito.verify(listener, Mockito.times(1)).onConfigError(null);
Mockito.verify(listener, Mockito.times(1)).close();
}
}
| 7,415 | 35 | 121 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/CodeClimateRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
class CodeClimateRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new CodeClimateRenderer();
}
@Override
String getExpected() {
return "{\"type\":\"issue\",\"check_name\":\"Foo\",\"description\":\"blah\","
+ "\"content\":{\"body\":\"## Foo\\n\\nSince: PMD null\\n\\nPriority: Low\\n\\n"
+ "[Categories](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#categories): Style\\n\\n"
+ "[Remediation Points](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#remediation-points): 50000\\n\\n"
+ "Description with Unicode Character U+2013: – .\\n\\n"
+ "### [PMD properties](https://docs.pmd-code.org/latest/pmd_userdocs_configuring_rules.html#rule-properties)\\n\\n"
+ "Name | Value | Description\\n" + "--- | --- | ---\\n"
+ "violationSuppressRegex | | Suppress violations with messages matching a regular expression\\n"
+ "violationSuppressXPath | | Suppress violations on nodes which match a given relative XPath expression.\\n"
+ "\"},\"categories\":[\"Style\"],\"location\":{\"path\":\"" + getSourceCodeFilename() + "\",\"lines\":{\"begin\":1,\"end\":1}},\"severity\":\"info\",\"remediation_points\":50000}"
+ "\u0000" + EOL;
}
@Override
String getExpectedWithProperties() {
return "{\"type\":\"issue\",\"check_name\":\"Foo\",\"description\":\"blah\","
+ "\"content\":{\"body\":\"## Foo\\n\\nSince: PMD null\\n\\nPriority: Low\\n\\n"
+ "[Categories](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#categories): Style\\n\\n"
+ "[Remediation Points](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#remediation-points): 50000\\n\\n"
+ "Description with Unicode Character U+2013: – .\\n\\n"
+ "### [PMD properties](https://docs.pmd-code.org/latest/pmd_userdocs_configuring_rules.html#rule-properties)\\n\\n"
+ "Name | Value | Description\\n" + "--- | --- | ---\\n"
+ "violationSuppressRegex | | Suppress violations with messages matching a regular expression\\n"
+ "violationSuppressXPath | | Suppress violations on nodes which match a given relative XPath expression.\\n"
+ "stringProperty | the string value\\nsecond line with 'quotes' | simple string property\\n"
+ "multiString | default1,default2 | multi string property\\n"
+ "\"},\"categories\":[\"Style\"],\"location\":{\"path\":\"" + getSourceCodeFilename() + "\",\"lines\":{\"begin\":1,\"end\":1}},\"severity\":\"info\",\"remediation_points\":50000}"
+ "\u0000" + EOL;
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return "{\"type\":\"issue\",\"check_name\":\"Foo\",\"description\":\"blah\","
+ "\"content\":{\"body\":\"## Foo\\n\\nSince: PMD null\\n\\nPriority: Low\\n\\n"
+ "[Categories](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#categories): Style\\n\\n"
+ "[Remediation Points](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#remediation-points): 50000\\n\\n"
+ "Description with Unicode Character U+2013: – .\\n\\n"
+ "### [PMD properties](https://docs.pmd-code.org/latest/pmd_userdocs_configuring_rules.html#rule-properties)\\n\\n"
+ "Name | Value | Description\\n" + "--- | --- | ---\\n"
+ "violationSuppressRegex | | Suppress violations with messages matching a regular expression\\n"
+ "violationSuppressXPath | | Suppress violations on nodes which match a given relative XPath expression.\\n"
+ "\"},\"categories\":[\"Style\"],\"location\":{\"path\":\"" + getSourceCodeFilename() + "\",\"lines\":{\"begin\":1,\"end\":1}},\"severity\":\"info\",\"remediation_points\":50000}"
+ "\u0000" + EOL + "{\"type\":\"issue\",\"check_name\":\"Boo\",\"description\":\"blah\","
+ "\"content\":{\"body\":\"## Boo\\n\\nSince: PMD null\\n\\nPriority: High\\n\\n"
+ "[Categories](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#categories): Style\\n\\n"
+ "[Remediation Points](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#remediation-points): 50000\\n\\n"
+ "desc\\n\\n"
+ "### [PMD properties](https://docs.pmd-code.org/latest/pmd_userdocs_configuring_rules.html#rule-properties)\\n\\n"
+ "Name | Value | Description\\n" + "--- | --- | ---\\n"
+ "violationSuppressRegex | | Suppress violations with messages matching a regular expression\\n"
+ "violationSuppressXPath | | Suppress violations on nodes which match a given relative XPath expression.\\n"
+ "\"},\"categories\":[\"Style\"],\"location\":{\"path\":\"" + getSourceCodeFilename() + "\",\"lines\":{\"begin\":1,\"end\":1}},\"severity\":\"blocker\",\"remediation_points\":50000}"
+ "\u0000" + EOL;
}
@Test
void testXPathRule() throws Exception {
FileLocation node = createLocation(1, 1, 1, 1);
XPathRule theRule = new XPathRule(XPathVersion.XPATH_3_1, "//dummyNode");
// Setup as FooRule
theRule.setDescription("Description with Unicode Character U+2013: – .");
theRule.setName("Foo");
String rendered = renderReport(getRenderer(), it -> it.onRuleViolation(new ParametricRuleViolation(theRule, node, "blah")));
// Output should be the exact same as for non xpath rules
assertEquals(filter(getExpected()), filter(rendered));
}
}
| 6,446 | 63.47 | 199 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SarifRendererTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import com.github.stefanbirkner.systemlambda.SystemLambda;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
class SarifRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new SarifRenderer();
}
@Test
void testRendererWithASCII() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.setProperty("file.encoding", StandardCharsets.US_ASCII.name());
testRenderer(StandardCharsets.UTF_8);
});
}
@Override
String getExpected() {
return readFile("expected.sarif.json");
}
@Override
String getExpectedEmpty() {
return readFile("empty.sarif.json");
}
@Override
String getExpectedMultiple() {
return readFile("expected-multiple.sarif.json");
}
@Override
String getExpectedError(Report.ProcessingError error) {
String expected = readFile("expected-error.sarif.json");
expected = expected.replace("###REPLACE_ME###", error.getDetail()
.replaceAll("\r", "\\\\r")
.replaceAll("\n", "\\\\n")
.replaceAll("\t", "\\\\t"));
return expected;
}
@Override
String getExpectedError(Report.ConfigurationError error) {
return readFile("expected-configerror.sarif.json");
}
@Override
String getExpectedErrorWithoutMessage(Report.ProcessingError error) {
String expected = readFile("expected-error-nomessage.sarif.json");
expected = expected.replace("###REPLACE_ME###", error.getDetail()
.replaceAll("\r", "\\\\r")
.replaceAll("\n", "\\\\n")
.replaceAll("\t", "\\\\t"));
return expected;
}
@Override
String filter(String expected) {
return expected.replaceAll("\r\n", "\n") // make the test run on Windows, too
.replaceAll("\"version\": \".+\",", "\"version\": \"unknown\",");
}
/**
* Multiple occurrences of the same rule should be reported as individual results.
*
* @see <a href="https://github.com/pmd/pmd/issues/3768"> [core] SARIF formatter reports multiple locations
* when it should report multiple results #3768</a>
*/
@Test
void testRendererMultipleLocations() throws Exception {
String actual = renderReport(getRenderer(), reportThreeViolationsTwoRules());
Gson gson = new Gson();
JsonObject json = gson.fromJson(actual, JsonObject.class);
JsonArray results = json.getAsJsonArray("runs").get(0).getAsJsonObject().getAsJsonArray("results");
assertEquals(3, results.size());
assertEquals(filter(readFile("expected-multiple-locations.sarif.json")), filter(actual));
}
private Consumer<FileAnalysisListener> reportThreeViolationsTwoRules() {
Rule fooRule = createFooRule();
Rule booRule = createBooRule();
return reportBuilder -> {
reportBuilder.onRuleViolation(newRuleViolation(1, 1, 1, 10, fooRule));
reportBuilder.onRuleViolation(newRuleViolation(5, 1, 5, 11, fooRule));
reportBuilder.onRuleViolation(newRuleViolation(2, 2, 3, 1, booRule));
};
}
protected String readFile(String relativePath) {
return super.readFile("sarif/" + relativePath);
}
}
| 3,822 | 31.956897 | 111 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/HTMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
class HTMLRendererTest extends AbstractRendererTest {
@Override
protected String getSourceCodeFilename() {
// note: the file name should still be a valid file name on both win and nix.
// This precludes using chars like <> to test escaping (https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names)
return "someFilename\u00A0thatNeedsEscaping.ext";
}
private String getEscapedFilename() {
return "someFilename thatNeedsEscaping.ext";
}
@Override
Renderer getRenderer() {
return new HTMLRenderer();
}
@Override
String getExpected() {
return getExpected(null, null);
}
private String getExpected(String linkPrefix, String lineAnchor) {
String filename = getEscapedFilename();
if (linkPrefix != null) {
filename = "<a href=\"" + linkPrefix + filename + "#" + lineAnchor + "\">"
+ filename + "</a>";
}
return getHeader()
+ "<tr bgcolor=\"lightgrey\"> " + EOL + "<td align=\"center\">1</td>" + EOL
+ "<td width=\"*%\">" + filename + "</td>" + EOL + "<td align=\"center\" width=\"5%\">1</td>" + EOL
+ "<td width=\"*\">blah</td>" + EOL + "</tr>" + EOL + "</table></body></html>" + EOL;
}
@Override
String getExpectedEmpty() {
return getHeader()
+ "</table></body></html>" + EOL;
}
@Override
String getExpectedMultiple() {
return getHeader()
+ "<tr bgcolor=\"lightgrey\"> " + EOL + "<td align=\"center\">1</td>" + EOL
+ "<td width=\"*%\">" + getEscapedFilename() + "</td>" + EOL + "<td align=\"center\" width=\"5%\">1</td>" + EOL
+ "<td width=\"*\">blah</td>" + EOL + "</tr>" + EOL + "<tr> " + EOL
+ "<td align=\"center\">2</td>" + EOL + "<td width=\"*%\">" + getEscapedFilename() + "</td>" + EOL
+ "<td align=\"center\" width=\"5%\">1</td>" + EOL + "<td width=\"*\">blah</td>" + EOL + "</tr>"
+ EOL + "</table></body></html>" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return getHeader()
+ "</table><hr/><center><h3>Processing errors</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>File</th><th>Problem</th></tr>" + EOL + "<tr bgcolor=\"lightgrey\"> " + EOL
+ "<td>file</td>" + EOL + "<td><pre>" + error.getDetail() + "</pre></td>" + EOL + "</tr>" + EOL + "</table></body></html>"
+ EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return getHeader()
+ "</table><hr/><center><h3>Configuration errors</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>Rule</th><th>Problem</th></tr>" + EOL + "<tr bgcolor=\"lightgrey\"> " + EOL
+ "<td>Foo</td>" + EOL + "<td>a configuration error</td>" + EOL + "</tr>" + EOL + "</table></body></html>"
+ EOL;
}
private String getHeader() {
return "<html><head><title>PMD</title></head><body>" + EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL;
}
@Test
void testLinkPrefix() throws IOException {
final HTMLRenderer renderer = new HTMLRenderer();
final String linkPrefix = "https://github.com/pmd/pmd/blob/master/";
final String linePrefix = "L";
renderer.setProperty(HTMLRenderer.LINK_PREFIX, linkPrefix);
renderer.setProperty(HTMLRenderer.LINE_PREFIX, linePrefix);
renderer.setProperty(HTMLRenderer.HTML_EXTENSION, false);
String actual = renderReport(renderer, reportOneViolation());
assertEquals(filter(getExpected(linkPrefix, "L1")), filter(actual));
}
@Test
void testLinePrefixNotSet() throws IOException {
final HTMLRenderer renderer = new HTMLRenderer();
final String linkPrefix = "https://github.com/pmd/pmd/blob/master/";
renderer.setProperty(HTMLRenderer.LINK_PREFIX, linkPrefix);
// dont set line prefix renderer.setProperty(HTMLRenderer.LINE_PREFIX, linePrefix);
renderer.setProperty(HTMLRenderer.HTML_EXTENSION, false);
String actual = renderReport(renderer, reportOneViolation());
assertEquals(filter(getExpected(linkPrefix, "")), filter(actual));
}
@Test
void testEmptyLinePrefix() throws IOException {
final HTMLRenderer renderer = new HTMLRenderer();
final String linkPrefix = "https://github.com/pmd/pmd/blob/master/";
renderer.setProperty(HTMLRenderer.LINK_PREFIX, linkPrefix);
renderer.setProperty(HTMLRenderer.LINE_PREFIX, "");
renderer.setProperty(HTMLRenderer.HTML_EXTENSION, false);
String actual = renderReport(renderer, reportOneViolation());
assertEquals(filter(getExpected(linkPrefix, "1")), filter(actual));
}
}
| 5,599 | 42.410853 | 175 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
class XSLTRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new XSLTRenderer();
}
@Override
String getExpected() {
return readFile("expected.html");
}
@Override
String getExpectedEmpty() {
return readFile("empty.html");
}
@Override
String getExpectedMultiple() {
return readFile("expected-multiple.html");
}
@Override
String getExpectedError(Report.ProcessingError error) {
return readFile("expected-error.html");
}
@Override
String getExpectedError(Report.ConfigurationError error) {
return readFile("expected-error.html");
}
@Override
String filter(String expected) {
return expected.replaceAll("<h2>PMD unknown Report\\. Generated on .+</h2>",
"<h2>PMD unknown Report. Generated on ...</h2>")
.replaceAll("\r\n", "\n"); // make the test run on Windows, too
}
@Test
void testDefaultStylesheet() throws Exception {
XSLTRenderer renderer = new XSLTRenderer();
FileLocation loc = FileLocation.range(FileId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 2));
RuleViolation rv = new ParametricRuleViolation(new FooRule(), loc, "violation message");
String result = renderReport(renderer, it -> it.onRuleViolation(rv));
assertTrue(result.contains("violation message"));
}
protected String readFile(String relativePath) {
return super.readFile("xslt/" + relativePath);
}
}
| 2,129 | 29 | 96 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/TextRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
class TextRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new TextRenderer();
}
@Override
String getExpected() {
return getSourceCodeFilename() + ":1:\tFoo:\tblah" + EOL;
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return getSourceCodeFilename() + ":1:\tFoo:\tblah" + EOL
+ getSourceCodeFilename() + ":1:\tBoo:\tblah" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return "file\t-\tRuntimeException: Error" + EOL;
}
@Override
String getExpectedErrorWithoutMessage(ProcessingError error) {
return "file\t-\tNullPointerException: null" + EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return "Foo\t-\ta configuration error" + EOL;
}
}
| 1,162 | 23.229167 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SummaryHTMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
class SummaryHTMLRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
Renderer result = new SummaryHTMLRenderer();
result.setProperty(HTMLRenderer.LINK_PREFIX, "link_prefix");
result.setProperty(HTMLRenderer.LINE_PREFIX, "line_prefix");
result.setProperty(HTMLRenderer.HTML_EXTENSION, true);
return result;
}
@Override
protected String getSourceCodeFilename() {
return "notAvailable";
}
@Override
String getExpected() {
return "<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>" + EOL
+ "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL
+ "<tr><td>Foo</td><td align=center>1</td></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "<tr bgcolor=\"lightgrey\"> " + EOL + "<td align=\"center\">1</td>" + EOL
+ "<td width=\"*%\"><a href=\"link_prefix" + getSourceCodeFilename() + ".html#line_prefix1\">" + getSourceCodeFilename() + "</a></td>" + EOL
+ "<td align=\"center\" width=\"5%\">1</td>" + EOL + "<td width=\"*\">blah</td>" + EOL + "</tr>"
+ EOL + "</table></tr></table></body></html>" + EOL;
}
@Override
String getExpectedEmpty() {
return "<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>" + EOL
+ "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "</table></tr></table></body></html>" + EOL;
}
@Override
String getExpectedMultiple() {
return "<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>" + EOL
+ "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL
+ "<tr><td>Boo</td><td align=center>1</td></tr>" + EOL
+ "<tr><td>Foo</td><td align=center>1</td></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "<tr bgcolor=\"lightgrey\"> " + EOL + "<td align=\"center\">1</td>" + EOL
+ "<td width=\"*%\"><a href=\"link_prefix" + getSourceCodeFilename() + ".html#line_prefix1\">" + getSourceCodeFilename() + "</a></td>" + EOL
+ "<td align=\"center\" width=\"5%\">1</td>" + EOL + "<td width=\"*\">blah</td>" + EOL + "</tr>"
+ EOL + "<tr> " + EOL + "<td align=\"center\">2</td>" + EOL
+ "<td width=\"*%\"><a href=\"link_prefix" + getSourceCodeFilename() + ".html#line_prefix1\">" + getSourceCodeFilename() + "</a></td>" + EOL
+ "<td align=\"center\" width=\"5%\">1</td>" + EOL + "<td width=\"*\">blah</td>" + EOL + "</tr>"
+ EOL + "</table></tr></table></body></html>" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return "<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>" + EOL
+ "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "</table><hr/><center><h3>Processing errors</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>File</th><th>Problem</th></tr>" + EOL + "<tr bgcolor=\"lightgrey\"> " + EOL
+ "<td><a href=\"link_prefixfile.html#\">file</a></td>" + EOL + "<td><pre>" + error.getDetail() + "</pre></td>" + EOL + "</tr>" + EOL
+ "</table></tr></table></body></html>" + EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return "<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>" + EOL
+ "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "</table><hr/><center><h3>Configuration errors</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>Rule</th><th>Problem</th></tr>" + EOL + "<tr bgcolor=\"lightgrey\"> " + EOL
+ "<td>Foo</td>" + EOL + "<td>a configuration error</td>" + EOL + "</tr>" + EOL
+ "</table></tr></table></body></html>" + EOL;
}
@Test
void testShowSuppressions() throws Exception {
Renderer renderer = getRenderer();
renderer.setShowSuppressedViolations(true);
String actual = renderReport(renderer, createEmptyReportWithSuppression());
assertEquals("<html><head><title>PMD</title></head><body>" + EOL + "<center><h2>Summary</h2></center>"
+ EOL + "<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">" + EOL
+ "<tr><th>Rule name</th><th>Number of violations</th></tr>" + EOL + "</table>" + EOL
+ "<center><h2>Detail</h2></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL
+ "<center><h3>PMD report</h3></center><center><h3>Problems found</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>" + EOL
+ "</table><hr/><center><h3>Suppressed warnings</h3></center><table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"
+ EOL + "<th>File</th><th>Line</th><th>Rule</th><th>NOPMD or Annotation</th><th>Reason</th></tr>"
+ EOL + "<tr bgcolor=\"lightgrey\"> " + EOL + "<td align=\"left\"><a href=\"link_prefix" + getSourceCodeFilename() + ".html#line_prefix1\">" + getSourceCodeFilename() + "</a></td>" + EOL
+ "<td align=\"center\">1</td>" + EOL + "<td align=\"center\">Foo</td>" + EOL
+ "<td align=\"center\">//NOPMD</td>" + EOL + "<td align=\"center\">test</td>" + EOL
+ "</tr>"
+ EOL + "</table></tr></table></body></html>" + EOL, actual);
}
@Test
void testHideSuppressions() throws Exception {
Renderer renderer = getRenderer();
renderer.setShowSuppressedViolations(false);
String actual = renderReport(renderer, createEmptyReportWithSuppression());
assertEquals(getExpectedEmpty(), actual);
}
private Consumer<FileAnalysisListener> createEmptyReportWithSuppression() {
return listener -> {
DummyRootNode root = helper.parse("dummy code", getSourceCodeFilename())
.withNoPmdComments(Collections.singletonMap(1, "test"));
RuleContext ruleContext = RuleContext.create(listener, new FooRule());
ruleContext.addViolationWithPosition(root, 1, 1, "suppress test");
};
}
}
| 9,693 | 61.541935 | 211 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/TextPadRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
class TextPadRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new TextPadRenderer();
}
@Override
String getExpected() {
return getSourceCodeFilename() + "(1, Foo): blah" + EOL;
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return getSourceCodeFilename() + "(1, Foo): blah" + EOL + getSourceCodeFilename() + "(1, Boo): blah" + EOL;
}
}
| 639 | 21.068966 | 119 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/EmacsRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
class EmacsRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new EmacsRenderer();
}
@Override
String getExpected() {
return getSourceCodeFilename() + ":1: blah" + EOL;
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return getSourceCodeFilename() + ":1: blah" + EOL + getSourceCodeFilename() + ":1: blah" + EOL;
}
}
| 611 | 20.103448 | 103 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/IDEAJRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
class IDEAJRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
Renderer result = new IDEAJRenderer();
result.setProperty(IDEAJRenderer.SOURCE_PATH, "");
result.setProperty(IDEAJRenderer.CLASS_AND_METHOD_NAME, "Foo <init>");
result.setProperty(IDEAJRenderer.FILE_NAME, "Foo.java");
return result;
}
@Override
String getExpected() {
return "blah" + EOL + " at Foo <init>(Foo.java:1)" + EOL;
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return "blah" + EOL + " at Foo <init>(Foo.java:1)" + EOL + "blah" + EOL
+ " at Foo <init>(Foo.java:1)" + EOL;
}
}
| 885 | 25.058824 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/YAHTMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.util.CollectionUtil;
class YAHTMLRendererTest extends AbstractRendererTest {
private File outputDir;
@TempDir
private Path folder;
@BeforeEach
void setUp() {
outputDir = folder.resolve("pmdtest").toFile();
assertTrue(outputDir.mkdir());
}
private RuleViolation newRuleViolation(int beginLine, int beginColumn, int endLine, int endColumn, final String packageNameArg, final String classNameArg) {
FileLocation loc = createLocation(beginLine, beginColumn, endLine, endColumn);
Map<String, String> additionalInfo = CollectionUtil.mapOf(RuleViolation.PACKAGE_NAME, packageNameArg,
RuleViolation.CLASS_NAME, classNameArg);
return new ParametricRuleViolation(new FooRule(), loc, "blah", additionalInfo);
}
@Override
protected RuleViolation newRuleViolation(int beginLine, int beginColumn, int endLine, int endColumn, Rule rule) {
return newRuleViolation(beginLine, beginColumn, endLine, endColumn, "net.sf.pmd.test", "YAHTMLSampleClass");
}
@Test
void testReportMultipleViolations() throws Exception {
String actual = renderReport(getRenderer(), it -> {
it.onRuleViolation(newRuleViolation(1, 1, 1, 1, "net.sf.pmd.test", "YAHTMLSampleClass1"));
it.onRuleViolation(newRuleViolation(1, 1, 1, 2, "net.sf.pmd.test", "YAHTMLSampleClass1"));
it.onRuleViolation(newRuleViolation(1, 1, 1, 1, "net.sf.pmd.other", "YAHTMLSampleClass2"));
});
assertEquals(filter(getExpected()), filter(actual));
String[] htmlFiles = outputDir.list();
assertEquals(3, htmlFiles.length);
Arrays.sort(htmlFiles);
assertEquals("YAHTMLSampleClass1.html", htmlFiles[0]);
assertEquals("YAHTMLSampleClass2.html", htmlFiles[1]);
assertEquals("index.html", htmlFiles[2]);
for (String file : htmlFiles) {
try (FileInputStream in = new FileInputStream(new File(outputDir, file));
InputStream expectedIn = YAHTMLRendererTest.class.getResourceAsStream("yahtml/" + file)) {
String data = IOUtil.readToString(in, StandardCharsets.UTF_8);
String expected = normalizeLineSeparators(IOUtil.readToString(expectedIn, StandardCharsets.UTF_8));
assertEquals(expected, data, "File " + file + " is different");
}
}
}
private static String normalizeLineSeparators(String s) {
return s.replaceAll("\\R", System.lineSeparator());
}
@Override
Renderer getRenderer() {
Renderer result = new YAHTMLRenderer();
result.setProperty(YAHTMLRenderer.OUTPUT_DIR, outputDir.getAbsolutePath());
return result;
}
@Override
String getExpected() {
return "<h3 align=\"center\">The HTML files are located in '" + outputDir + "'.</h3>" + System.lineSeparator();
}
@Override
String getExpectedEmpty() {
return getExpected();
}
@Override
String getExpectedMultiple() {
return getExpected();
}
@Override
String getExpectedError(ProcessingError error) {
return getExpected();
}
@Override
String getExpectedError(ConfigurationError error) {
return getExpected();
}
}
| 4,314 | 34.958333 | 160 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/VBHTMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
class VBHTMLRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new VBHTMLRenderer();
}
@Override
String getExpected() {
return "<html><head><title>PMD</title></head><style type=\"text/css\"><!--" + EOL
+ "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }"
+ EOL
+ ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }"
+ EOL
+ ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }"
+ EOL + "#TableHeader { background-color: #003366; }" + EOL
+ "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }"
+ EOL
+ "--></style><body><center><table border=\"0\" width=\"80%\"><tr id=TableHeader><td colspan=\"2\"><font class=title> " + getSourceCodeFilename() + "</font></tr>"
+ EOL
+ "<tr id=RowColor2><td width=\"50\" align=\"right\"><font class=body>1 </font></td><td><font class=body>blah</font></td></tr>"
+ EOL + "</table><br></center></body></html>" + EOL;
}
@Override
String getExpectedEmpty() {
return "<html><head><title>PMD</title></head><style type=\"text/css\"><!--" + EOL
+ "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }"
+ EOL
+ ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }"
+ EOL
+ ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }"
+ EOL + "#TableHeader { background-color: #003366; }" + EOL
+ "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }"
+ EOL + "--></style><body><center><br></center></body></html>" + EOL;
}
@Override
String getExpectedMultiple() {
return "<html><head><title>PMD</title></head><style type=\"text/css\"><!--" + EOL
+ "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }"
+ EOL
+ ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }"
+ EOL
+ ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }"
+ EOL + "#TableHeader { background-color: #003366; }" + EOL
+ "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }"
+ EOL
+ "--></style><body><center><table border=\"0\" width=\"80%\"><tr id=TableHeader><td colspan=\"2\"><font class=title> " + getSourceCodeFilename() + "</font></tr>"
+ EOL
+ "<tr id=RowColor2><td width=\"50\" align=\"right\"><font class=body>1 </font></td><td><font class=body>blah</font></td></tr>"
+ EOL
+ "<tr id=RowColor1><td width=\"50\" align=\"right\"><font class=body>1 </font></td><td><font class=body>blah</font></td></tr>"
+ EOL + "</table><br></center></body></html>" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return "<html><head><title>PMD</title></head><style type=\"text/css\"><!--" + EOL
+ "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }"
+ EOL
+ ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }"
+ EOL
+ ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }"
+ EOL + "#TableHeader { background-color: #003366; }" + EOL
+ "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }"
+ EOL
+ "--></style><body><center><br><table border=\"0\" width=\"80%\"><tr id=TableHeader><td colspan=\"2\"><font class=title> Problems found</font></td></tr><tr id=RowColor2><td><font class=body>"
+ error.getFileId().getOriginalPath() + "</font></td><td><font class=body><pre>" + error.getDetail() + "</pre></font></td></tr></table></center></body></html>" + EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return "<html><head><title>PMD</title></head><style type=\"text/css\"><!--" + EOL
+ "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }"
+ EOL
+ ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }"
+ EOL
+ ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }"
+ EOL + "#TableHeader { background-color: #003366; }" + EOL
+ "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }"
+ EOL
+ "--></style><body><center><br><table border=\"0\" width=\"80%\"><tr id=TableHeader><td colspan=\"2\"><font class=title> Configuration problems found</font></td></tr><tr id=RowColor2><td><font class=body>"
+ error.rule().getName() + "</font></td><td><font class=body>" + error.issue() + "</font></td></tr></table></center></body></html>" + EOL;
}
}
| 6,342 | 65.072917 | 227 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/PapariTextRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.io.StringReader;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
class PapariTextRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
TextColorRenderer result = new TextColorRenderer() {
@Override
protected Reader getReader(String sourceFile) throws FileNotFoundException {
return new StringReader("public class Foo {}");
}
};
result.setProperty(TextColorRenderer.COLOR, "false");
return result;
}
@Override
String getExpected() {
return "* file: " + getSourceCodeFilename() + EOL + " src: " + getSourceCodeFilename() + ":1:1" + EOL + " rule: Foo" + EOL
+ " msg: blah" + EOL + " code: public class Foo {}" + EOL + EOL + EOL + EOL
+ "Summary:" + EOL + EOL + "* warnings: 1" + EOL;
}
@Override
String getExpectedEmpty() {
return EOL + EOL + "Summary:" + EOL + EOL + "* warnings: 0" + EOL;
}
@Override
String getExpectedMultiple() {
return "* file: " + getSourceCodeFilename() + EOL + " src: " + getSourceCodeFilename() + ":1:1" + EOL + " rule: Foo" + EOL
+ " msg: blah" + EOL + " code: public class Foo {}" + EOL + EOL + " src: "
+ getSourceCodeFilename() + ":1:1" + EOL + " rule: Boo" + EOL + " msg: blah" + EOL
+ " code: public class Foo {}" + EOL + EOL + EOL + EOL + "Summary:" + EOL
+ EOL + "* warnings: 2" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return EOL + EOL + "Summary:" + EOL + EOL + "* file: file" + EOL + " err: RuntimeException: Error" + EOL
+ error.getDetail() + EOL + EOL
+ "* errors: 1" + EOL + "* warnings: 0" + EOL;
}
@Override
String getExpectedErrorWithoutMessage(ProcessingError error) {
return EOL + EOL + "Summary:" + EOL + EOL + "* file: file" + EOL + " err: NullPointerException: null" + EOL
+ error.getDetail() + EOL + EOL
+ "* errors: 1" + EOL + "* warnings: 0" + EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return EOL + EOL + "Summary:" + EOL + EOL + "* rule: Foo" + EOL
+ " err: a configuration error" + EOL + EOL
+ "* errors: 1" + EOL + "* warnings: 0" + EOL;
}
}
| 2,708 | 37.7 | 137 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class XMLRendererTest extends AbstractRendererTest {
@TempDir
private Path folder;
@Override
Renderer getRenderer() {
return new XMLRenderer();
}
@Override
String getExpected() {
return getHeader() + "<file name=\"" + getSourceCodeFilename() + "\">" + EOL
+ "<violation beginline=\"1\" endline=\"1\" begincolumn=\"1\" endcolumn=\"1\" rule=\"Foo\" ruleset=\"RuleSet\" priority=\"5\">"
+ EOL + "blah" + EOL + "</violation>" + EOL + "</file>" + EOL + "</pmd>" + EOL;
}
@Override
String getExpectedEmpty() {
return getHeader() + "</pmd>" + EOL;
}
@Override
String getExpectedMultiple() {
return getHeader() + "<file name=\"" + getSourceCodeFilename() + "\">" + EOL
+ "<violation beginline=\"1\" endline=\"1\" begincolumn=\"1\" endcolumn=\"1\" rule=\"Foo\" ruleset=\"RuleSet\" priority=\"5\">"
+ EOL + "blah" + EOL + "</violation>" + EOL
+ "<violation beginline=\"1\" endline=\"1\" begincolumn=\"1\" endcolumn=\"2\" rule=\"Boo\" ruleset=\"RuleSet\" priority=\"1\">"
+ EOL + "blah" + EOL + "</violation>" + EOL + "</file>" + EOL + "</pmd>" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return getHeader() + "<error filename=\"file\" msg=\"RuntimeException: Error\">"
+ EOL + "<![CDATA[" + error.getDetail() + "]]>" + EOL + "</error>" + EOL + "</pmd>" + EOL;
}
@Override
String getExpectedErrorWithoutMessage(ProcessingError error) {
return getHeader() + "<error filename=\"file\" msg=\"NullPointerException: null\">"
+ EOL + "<![CDATA[" + error.getDetail() + "]]>" + EOL + "</error>" + EOL + "</pmd>" + EOL;
}
@Override
String getExpectedError(ConfigurationError error) {
return getHeader() + "<configerror rule=\"Foo\" msg=\"a configuration error\"/>"
+ EOL + "</pmd>" + EOL;
}
@Override
String filter(String expected) {
return expected.replaceAll(" timestamp=\"[^\"]+\">", " timestamp=\"\">");
}
private RuleViolation createRuleViolation(String description) {
FileLocation loc = FileLocation.range(FileId.fromPathLikeString(getSourceCodeFilename()),
TextRange2d.range2d(1, 1, 1, 1));
return new ParametricRuleViolation(new FooRule(), loc, description);
}
private void verifyXmlEscaping(Renderer renderer, String shouldContain, Charset charset) throws Exception {
renderer.setProperty(XMLRenderer.ENCODING, charset.name());
String surrogatePair = "\ud801\udc1c";
String msg = "The String 'literal' \"TokénizĀr " + surrogatePair + "\" appears...";
Report report = Report.buildReport(it -> it.onRuleViolation(createRuleViolation(msg)));
String actual = renderTempFile(renderer, report, charset);
assertTrue(actual.contains(shouldContain));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(actual)));
NodeList violations = doc.getElementsByTagName("violation");
assertEquals(1, violations.getLength());
assertEquals(msg, violations.item(0).getTextContent().trim());
}
@Test
void testXMLEscapingWithUTF8() throws Exception {
Renderer renderer = getRenderer();
verifyXmlEscaping(renderer, "\ud801\udc1c", StandardCharsets.UTF_8);
}
@Test
void testXMLEscapingWithUTF16() throws Exception {
Renderer renderer = getRenderer();
verifyXmlEscaping(renderer, "𐐜", StandardCharsets.UTF_16);
}
@Test
void testXMLEscapingWithoutUTF8() throws Exception {
Renderer renderer = getRenderer();
verifyXmlEscaping(renderer, "𐐜", StandardCharsets.ISO_8859_1);
}
String getHeader() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + EOL
+ "<pmd xmlns=\"http://pmd.sourceforge.net/report/2.0.0\""
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/report/2.0.0 http://pmd.sourceforge.net/report_2_0_0.xsd\""
+ " version=\"" + PMDVersion.VERSION + "\" timestamp=\"2014-10-06T19:30:51.262\">" + EOL;
}
@Test
void testCorrectCharset() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
System.setProperty("file.encoding", StandardCharsets.ISO_8859_1.name());
Renderer renderer = getRenderer();
String formFeed = "\u000C";
// é = U+00E9 : can be represented in ISO-8859-1 as is
// Ā = U+0100 : cannot be represented in ISO-8859-1 -> would be a unmappable character, needs to be escaped
String specialChars = "éĀ";
String originalChars = formFeed + specialChars; // u000C should be removed, é should be encoded correctly as UTF-8
String msg = "The String literal \"" + originalChars + "\" appears...";
Report report = Report.buildReport(it -> it.onRuleViolation(createRuleViolation(msg)));
String actual = renderTempFile(renderer, report, StandardCharsets.UTF_8);
assertTrue(actual.contains(specialChars));
assertFalse(actual.contains(formFeed));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(actual)));
NodeList violations = doc.getElementsByTagName("violation");
assertEquals(1, violations.getLength());
assertEquals(msg.replaceAll(formFeed, ""), violations.item(0).getTextContent().trim());
});
}
private String renderTempFile(Renderer renderer, Report report, Charset expectedCharset) throws IOException {
File reportFile = folder.resolve("report.out").toFile();
renderer.setReportFile(reportFile.getAbsolutePath());
renderer.start();
renderer.renderFileReport(report);
renderer.end();
renderer.flush();
try (FileInputStream input = new FileInputStream(reportFile)) {
return IOUtil.readToString(input, expectedCharset);
}
}
}
| 7,665 | 41.826816 | 143 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collections;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.RuleWithProperties;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
abstract class AbstractRendererTest {
@RegisterExtension
protected final DummyParsingHelper helper = new DummyParsingHelper();
protected static final String EOL = System.lineSeparator();
@TempDir
private Path tempDir;
abstract Renderer getRenderer();
abstract String getExpected();
String getExpectedWithProperties() {
return getExpected();
}
abstract String getExpectedEmpty();
abstract String getExpectedMultiple();
String getExpectedError(ProcessingError error) {
return "";
}
String getExpectedErrorWithoutMessage(ProcessingError error) {
return getExpectedError(error);
}
String getExpectedError(ConfigurationError error) {
return "";
}
String filter(String expected) {
return expected;
}
String getSourceCodeFilename() {
return "notAvailable.ext";
}
@Test
void testNullPassedIn() throws Exception {
assertThrows(NullPointerException.class, () ->
getRenderer().renderFileReport(null));
}
protected Consumer<FileAnalysisListener> reportOneViolation() {
return it -> it.onRuleViolation(newRuleViolation(1, 1, 1, 1, createFooRule()));
}
private Consumer<FileAnalysisListener> reportTwoViolations() {
return it -> {
RuleViolation informationalRuleViolation = newRuleViolation(1, 1, 1, 1, createFooRule());
it.onRuleViolation(informationalRuleViolation);
RuleViolation severeRuleViolation = newRuleViolation(1, 1, 1, 2, createBooRule());
it.onRuleViolation(severeRuleViolation);
};
}
protected FileLocation createLocation(int beginLine, int beginColumn, int endLine, int endColumn) {
TextRange2d range2d = TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn);
return FileLocation.range(FileId.fromPathLikeString(getSourceCodeFilename()), range2d);
}
protected RuleViolation newRuleViolation(int beginLine, int beginColumn, int endLine, int endColumn, Rule rule) {
FileLocation loc = createLocation(beginLine, beginColumn, endLine, endColumn);
return new ParametricRuleViolation(rule, loc, "blah", Collections.emptyMap());
}
/**
* Creates a new rule instance with name "Boo" and priority {@link RulePriority#HIGH}.
*/
protected Rule createBooRule() {
Rule booRule = new FooRule();
booRule.setName("Boo");
booRule.setDescription("desc");
booRule.setPriority(RulePriority.HIGH);
return booRule;
}
/**
* Creates a new rule instance with name "Foo" and priority {@link RulePriority#LOW}.
*/
protected Rule createFooRule() {
Rule fooRule = new FooRule();
fooRule.setName("Foo");
fooRule.setPriority(RulePriority.LOW);
return fooRule;
}
/**
* Read a resource file relative to this class's location.
*/
protected String readFile(String relativePath) {
try (InputStream in = getClass().getResourceAsStream(relativePath)) {
return IOUtil.readToString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
void testRuleWithProperties() throws Exception {
RuleWithProperties theRule = new RuleWithProperties();
theRule.setProperty(RuleWithProperties.STRING_PROPERTY_DESCRIPTOR,
"the string value\nsecond line with \"quotes\"");
RuleViolation violation = newRuleViolation(1, 1, 1, 1, theRule);
String rendered = renderReport(getRenderer(), it -> it.onRuleViolation(violation));
assertEquals(filter(getExpectedWithProperties()), filter(rendered));
}
@Test
void testRenderer() throws Exception {
testRenderer(Charset.defaultCharset());
}
protected void testRenderer(Charset expectedCharset) throws Exception {
String actual = renderReport(getRenderer(), reportOneViolation(), expectedCharset);
assertEquals(filter(getExpected()), filter(actual));
}
@Test
void testRendererEmpty() throws Exception {
String actual = render(it -> {});
assertEquals(filter(getExpectedEmpty()), filter(actual));
}
@Test
void testRendererMultiple() throws Exception {
String actual = render(reportTwoViolations());
assertEquals(filter(getExpectedMultiple()), filter(actual));
}
@Test
void testError() throws Exception {
Report.ProcessingError err = new Report.ProcessingError(new RuntimeException("Error"), FileId.fromPathLikeString("file"));
String actual = render(it -> it.onError(err));
assertEquals(filter(getExpectedError(err)), filter(actual));
}
@Test
void testErrorWithoutMessage() throws Exception {
Report.ProcessingError err = new Report.ProcessingError(new NullPointerException(), FileId.fromPathLikeString("file"));
String actual = render(it -> it.onError(err));
assertEquals(filter(getExpectedErrorWithoutMessage(err)), filter(actual));
}
private String render(Consumer<FileAnalysisListener> listenerEffects) throws IOException {
return renderReport(getRenderer(), listenerEffects);
}
@Test
void testConfigError() throws Exception {
Report.ConfigurationError err = new Report.ConfigurationError(new FooRule(), "a configuration error");
String actual = renderGlobal(getRenderer(), it -> it.onConfigError(err));
assertEquals(filter(getExpectedError(err)), filter(actual));
}
protected String renderReport(Renderer renderer, Consumer<? super FileAnalysisListener> listenerEffects) throws IOException {
return renderReport(renderer, listenerEffects, Charset.defaultCharset());
}
protected String renderReport(Renderer renderer, Consumer<? super FileAnalysisListener> listenerEffects,
Charset expectedEncoding) throws IOException {
return renderGlobal(renderer, globalListener -> {
LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion();
TextFile dummyFile = TextFile.forCharSeq("dummyText", FileId.fromPathLikeString("fname1.dummy"), version);
try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) {
listenerEffects.accept(fal);
} catch (Exception e) {
throw new AssertionError(e);
}
}, expectedEncoding);
}
private String renderGlobal(Renderer renderer, Consumer<? super GlobalAnalysisListener> listenerEffects) throws IOException {
return renderGlobal(renderer, listenerEffects, Charset.defaultCharset());
}
private String renderGlobal(Renderer renderer, Consumer<? super GlobalAnalysisListener> listenerEffects,
Charset expectedEncoding) throws IOException {
File file = tempDir.resolve("report.out").toFile();
renderer.setReportFile(file.getAbsolutePath());
try (GlobalAnalysisListener listener = renderer.newListener()) {
listenerEffects.accept(listener);
} catch (Exception e) {
throw new AssertionError(e);
}
return IOUtil.readFileToString(file, expectedEncoding);
}
}
| 8,921 | 36.330544 | 130 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/RenderersTests.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
/**
* tests for the net.sourceforge.pmd.renderers package
*
* @author Boris Gruschko ( boris at gruschko.org )
*/
@Suite
@SelectClasses({
CodeClimateRendererTest.class,
CSVRendererTest.class,
EmacsRendererTest.class,
HTMLRendererTest.class,
IDEAJRendererTest.class,
JsonRendererTest.class,
PapariTextRendererTest.class,
SarifRendererTest.class,
SummaryHTMLRendererTest.class,
TextPadRendererTest.class,
TextRendererTest.class,
VBHTMLRendererTest.class,
XMLRendererTest.class,
XSLTRendererTest.class,
YAHTMLRendererTest.class
})
class RenderersTests {
}
| 841 | 23.057143 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/EmptyRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
class EmptyRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new EmptyRenderer();
}
@Override
void testNullPassedIn() throws Exception {
// Overriding test from the super class, this renderer doesn't care, so no NPE.
getRenderer().renderFileReport(null);
}
@Override
String getExpected() {
return "";
}
@Override
String getExpectedEmpty() {
return "";
}
@Override
String getExpectedMultiple() {
return "";
}
}
| 688 | 18.685714 | 87 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/CSVRendererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
class CSVRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new CSVRenderer();
}
@Override
String getExpected() {
return getHeader()
+ "\"1\",\"\",\"" + getSourceCodeFilename() + "\",\"5\",\"1\",\"blah\",\"RuleSet\",\"Foo\"" + EOL;
}
@Override
String getExpectedEmpty() {
return getHeader();
}
@Override
String getExpectedMultiple() {
return getHeader()
+ "\"1\",\"\",\"" + getSourceCodeFilename() + "\",\"5\",\"1\",\"blah\",\"RuleSet\",\"Foo\"" + EOL
+ "\"2\",\"\",\"" + getSourceCodeFilename() + "\",\"1\",\"1\",\"blah\",\"RuleSet\",\"Boo\"" + EOL;
}
@Override
String getExpectedError(ProcessingError error) {
return getHeader();
}
@Override
String getExpectedError(ConfigurationError error) {
return getHeader();
}
private String getHeader() {
return "\"Problem\",\"Package\",\"File\",\"Priority\",\"Line\",\"Description\",\"Rule set\",\"Rule\"" + EOL;
}
}
| 1,321 | 25.979592 | 116 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/renderers/JsonRendererTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.renderers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report.ConfigurationError;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.ViolationSuppressor;
class JsonRendererTest extends AbstractRendererTest {
@Override
Renderer getRenderer() {
return new JsonRenderer();
}
@Override
String getExpected() {
return readFile("expected.json");
}
@Override
String getExpectedEmpty() {
return readFile("empty.json");
}
@Override
String getExpectedMultiple() {
return readFile("expected-multiple.json");
}
@Override
String getExpectedError(ProcessingError error) {
String expected = readFile("expected-processingerror.json");
expected = expected.replace("###REPLACE_ME###", error.getDetail()
.replaceAll("\r", "\\\\r")
.replaceAll("\n", "\\\\n")
.replaceAll("\t", "\\\\t"));
return expected;
}
@Override
String getExpectedError(ConfigurationError error) {
return readFile("expected-configurationerror.json");
}
@Override
String getExpectedErrorWithoutMessage(ProcessingError error) {
String expected = readFile("expected-processingerror-no-message.json");
expected = expected.replace("###REPLACE_ME###", error.getDetail()
.replaceAll("\r", "\\\\r")
.replaceAll("\n", "\\\\n")
.replaceAll("\t", "\\\\t"));
return expected;
}
@Override
protected String readFile(String relativePath) {
return super.readFile("json/" + relativePath);
}
@Override
String filter(String expected) {
return expected
.replaceAll("\"timestamp\":\\s*\"[^\"]+\"", "\"timestamp\": \"--replaced--\"")
.replaceAll("\"pmdVersion\":\\s*\"[^\"]+\"", "\"pmdVersion\": \"unknown\"")
.replaceAll("\\R", "\n"); // make the test run on Windows, too
}
@Test
void suppressedViolations() throws IOException {
SuppressedViolation suppressed = new SuppressedViolation(
newRuleViolation(1, 1, 1, 1, new FooRule()),
ViolationSuppressor.NOPMD_COMMENT_SUPPRESSOR,
"test"
);
String actual = renderReport(getRenderer(), it -> it.onSuppressedRuleViolation(suppressed));
String expected = readFile("expected-suppressed.json");
assertEquals(filter(expected), filter(actual));
}
}
| 2,819 | 29.652174 | 100 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/encodingTest/File2.java | public class File2 {
public void dup() {
for (int j = 0; j < 10; j++) {
System.out.println(j + "ä");
}
}
} | 142 | 19.428571 | 40 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/encodingTest/File1.java | public class File1 {
public void dup() {
for (int i = 0; i < 10; i++) {
System.out.println(i + "ä");
}
}
} | 142 | 19.428571 | 40 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/files/dup1.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
public class dup1 {
public static void main(String[] args) {
System.out.println("Test1");
System.out.println("Test2");
System.out.println("Test3");
System.out.println("Test4");
System.out.println("Test5");
System.out.println("Test6");
System.out.println("Test7");
System.out.println("Test8");
System.out.println("Test9");
}
} | 495 | 26.555556 | 79 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/files/file_with_ISO-8859-1_encoding.java | /**
* This file is using ISO-8859-1 (Latin-1) encoding.
*
*
*/
public class FileWith_ISO8859-1_Encoding {
}
| 114 | 11.777778 | 52 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/files/file_with_utf8_bom.java | /**
* This file is using UTF-8 with BOM encoding.
*
* ä
*/
public class FileWith_UTF-8-BOM_Encoding {
}
| 110 | 11.333333 | 46 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cli/cpd/files/dup2.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
public class dup2 {
public static void main(String[] args) {
System.out.println("Test1");
System.out.println("Test2");
System.out.println("Test3");
System.out.println("Test4");
System.out.println("Test5");
System.out.println("Test6");
System.out.println("Test7");
System.out.println("Test8");
System.out.println("Test9");
}
} | 495 | 26.555556 | 79 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cpd/files/file_with_ISO-8859-1_encoding.java | /**
* This file is using ISO-8859-1 (Latin-1) encoding.
*
* (this is an a-umlaut U+00E4)
*/
public class FileWith_ISO8859-1_Encoding {
}
| 143 | 15 | 52 | java |
pmd | pmd-master/pmd-core/src/test/resources/net/sourceforge/pmd/cpd/files/file_with_utf8_bom.java | /**
* This file is using UTF-8 with BOM encoding.
*
* ä (this is an a-umlaut U+00E4)
*/
public class FileWith_UTF-8-BOM_Encoding {
}
| 139 | 14.555556 | 46 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetReferenceId.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* This class is used to parse a RuleSet reference value. Most commonly used for
* specifying a RuleSet to process, or in a Rule 'ref' attribute value in the
* RuleSet XML. The RuleSet reference can refer to either an external RuleSet or
* the current RuleSet when used as a Rule 'ref' attribute value. An individual
* Rule in the RuleSet can be indicated.
*
* For an external RuleSet, referring to the entire RuleSet, the format is
* <i>ruleSetName</i>, where the RuleSet name is either a resource file path to
* a RuleSet that ends with <code>'.xml'</code>, or a simple RuleSet name.
*
* A simple RuleSet name, is one which contains no path separators, and either
* contains a '-' or is entirely numeric release number. A simple name of the
* form <code>[language]-[name]</code> is short for the full RuleSet name
* <code>rulesets/[language]/[name].xml</code>. A numeric release simple name of
* the form <code>[release]</code> is short for the full PMD Release RuleSet
* name <code>rulesets/releases/[release].xml</code>.
*
* For an external RuleSet, referring to a single Rule, the format is
* <i>ruleSetName/ruleName</i>, where the RuleSet name is as described above. A
* Rule with the <i>ruleName</i> should exist in this external RuleSet.
*
* For the current RuleSet, the format is <i>ruleName</i>, where the Rule name
* is not RuleSet name (i.e. contains no path separators, '-' or '.xml' in it,
* and is not all numeric). A Rule with the <i>ruleName</i> should exist in the
* current RuleSet.
*
* <table>
* <caption>Examples</caption> <thead>
* <tr>
* <th>String</th>
* <th>RuleSet file name</th>
* <th>Rule</th>
* </tr>
* </thead> <tbody>
* <tr>
* <td>rulesets/java/basic.xml</td>
* <td>rulesets/java/basic.xml</td>
* <td>all</td>
* </tr>
* <tr>
* <td>rulesets/java/basic.xml/EmptyCatchBlock</td>
* <td>rulesets/java/basic.xml</td>
* <td>EmptyCatchBlock</td>
* </tr>
* <tr>
* <td>EmptyCatchBlock</td>
* <td>null</td>
* <td>EmptyCatchBlock</td>
* </tr>
* </tbody>
* </table>
*
* @deprecated This is part of the internals of the {@link RuleSetLoader}.
*/
@Deprecated
@InternalApi
public class RuleSetReferenceId {
// todo this class has issues... What is even an "external" ruleset?
// terminology and API should be clarified.
private final boolean external;
private final String ruleSetFileName;
private final boolean allRules;
private final String ruleName;
private final RuleSetReferenceId externalRuleSetReferenceId;
private final String originalRef;
/**
* Construct a RuleSetReferenceId for the given single ID string.
*
* @param id
* The id string.
* @throws IllegalArgumentException
* If the ID contains a comma character.
*/
public RuleSetReferenceId(final String id) {
this(id, null, null);
}
private RuleSetReferenceId(final String ruleSetFileName, boolean external, String ruleName, RuleSetReferenceId externalRuleSetReferenceId) {
this.ruleSetFileName = Objects.requireNonNull(ruleSetFileName);
this.originalRef = ruleName == null ? ruleSetFileName : ruleSetFileName + "/" + ruleName;
this.allRules = ruleName == null;
this.external = external;
this.ruleName = ruleName;
this.externalRuleSetReferenceId = externalRuleSetReferenceId;
}
/**
* Construct a RuleSetReferenceId for the given single ID string. If an
* external RuleSetReferenceId is given, the ID must refer to a non-external
* Rule. The external RuleSetReferenceId will be responsible for producing
* the InputStream containing the Rule.
*
* @param id The id string.
* @param externalRuleSetReferenceId A RuleSetReferenceId to associate with this new instance.
*
* @throws IllegalArgumentException If the ID contains a comma character.
* @throws IllegalArgumentException If external RuleSetReferenceId is not external.
* @throws IllegalArgumentException If the ID is not Rule reference when there is an external
* RuleSetReferenceId.
*/
public RuleSetReferenceId(final String id, final RuleSetReferenceId externalRuleSetReferenceId) {
this(id, externalRuleSetReferenceId, null);
}
/**
* Construct a RuleSetReferenceId for the given single ID string. If an
* external RuleSetReferenceId is given, the ID must refer to a non-external
* Rule. The external RuleSetReferenceId will be responsible for producing
* the InputStream containing the Rule.
*
* @param id The id string.
* @param externalRuleSetReferenceId A RuleSetReferenceId to associate with this new instance.
*
* @throws IllegalArgumentException If the ID contains a comma character.
* @throws IllegalArgumentException If external RuleSetReferenceId is not external.
* @throws IllegalArgumentException If the ID is not Rule reference when there is an external
* RuleSetReferenceId.
*/
RuleSetReferenceId(final String id,
final RuleSetReferenceId externalRuleSetReferenceId,
final @Nullable MessageReporter err) {
this.originalRef = id;
if (externalRuleSetReferenceId != null && !externalRuleSetReferenceId.isExternal()) {
throw new IllegalArgumentException("Cannot pair with non-external <" + externalRuleSetReferenceId + ">.");
}
if (id != null && id.indexOf(',') >= 0) {
throw new IllegalArgumentException(
"A single RuleSetReferenceId cannot contain ',' (comma) characters: " + id);
}
// Damn this parsing sucks, but my brain is just not working to let me
// write a simpler scheme.
if (isValidUrl(id)) {
// A full RuleSet name
external = true;
ruleSetFileName = StringUtils.strip(id);
allRules = true;
ruleName = null;
} else if (isFullRuleSetName(id)) {
// A full RuleSet name
external = true;
ruleSetFileName = id;
allRules = true;
ruleName = null;
} else {
String tempRuleName = getRuleName(id);
String tempRuleSetFileName = tempRuleName != null && id != null
? id.substring(0, id.length() - tempRuleName.length() - 1) : id;
if (isValidUrl(tempRuleSetFileName)) {
// remaining part is a xml ruleset file, so the tempRuleName is
// probably a real rule name
external = true;
ruleSetFileName = StringUtils.strip(tempRuleSetFileName);
ruleName = StringUtils.strip(tempRuleName);
allRules = tempRuleName == null;
} else if (isHttpUrl(id)) {
// it's a url, we can't determine whether it's a full ruleset or
// a single rule - so falling back to
// a full RuleSet name
external = true;
ruleSetFileName = StringUtils.strip(id);
allRules = true;
ruleName = null;
} else if (isFullRuleSetName(tempRuleSetFileName)) {
// remaining part is a xml ruleset file, so the tempRuleName is
// probably a real rule name
external = true;
ruleSetFileName = tempRuleSetFileName;
ruleName = tempRuleName;
allRules = tempRuleName == null;
} else {
// resolve the ruleset name - it's maybe a built in ruleset
String expandedRuleset = resolveDeprecatedBuiltInRulesetShorthand(tempRuleSetFileName);
String builtinRuleSet = expandedRuleset == null ? tempRuleSetFileName : expandedRuleset;
if (checkRulesetExists(builtinRuleSet)) {
if (expandedRuleset != null && err != null) {
err.warn(
"Ruleset reference ''{0}'' uses a deprecated form, use ''{1}'' instead",
tempRuleSetFileName, builtinRuleSet
);
}
external = true;
ruleSetFileName = builtinRuleSet;
ruleName = tempRuleName;
allRules = tempRuleName == null;
} else {
// well, we didn't find the ruleset, so it's probably not a
// internal ruleset.
// at this time, we don't know, whether the tempRuleName is
// a name of the rule
// or the file name of the ruleset file.
// It is assumed, that tempRuleName is actually the filename
// of the ruleset,
// if there are more separator characters in the remaining
// ruleset filename (tempRuleSetFileName).
// This means, the only reliable way to specify single rules
// within a custom rulesest file is
// only possible, if the ruleset file has a .xml file
// extension.
if (tempRuleSetFileName == null || tempRuleSetFileName.contains(File.separator)) {
external = true;
ruleSetFileName = id;
ruleName = null;
allRules = true;
} else {
external = externalRuleSetReferenceId != null && externalRuleSetReferenceId.isExternal();
ruleSetFileName = externalRuleSetReferenceId != null
? externalRuleSetReferenceId.getRuleSetFileName() : null;
ruleName = id;
allRules = false;
}
}
}
}
if (this.external && this.ruleName != null && !this.ruleName.equals(id) && externalRuleSetReferenceId != null) {
throw new IllegalArgumentException(
"Cannot pair external <" + this + "> with external <" + externalRuleSetReferenceId + ">.");
}
this.externalRuleSetReferenceId = externalRuleSetReferenceId;
}
@Nullable RuleSetReferenceId getParentRulesetIfThisIsARule() {
if (ruleName == null) {
return null;
}
return new RuleSetReferenceId(
ruleSetFileName,
external,
null,
null
);
}
/**
* Tries to load the given ruleset.
*
* @param name
* the ruleset name
* @return <code>true</code> if the ruleset could be loaded,
* <code>false</code> otherwise.
*/
private boolean checkRulesetExists(final String name) {
boolean resourceFound = false;
if (name != null) {
try (InputStream ignored = new ResourceLoader().loadClassPathResourceAsStreamOrThrow(name)) {
resourceFound = true;
} catch (Exception ignored) {
// ignored
}
}
return resourceFound;
}
/**
* Assumes that the ruleset name given is e.g. "java-basic". Then it will
* return the full classpath name for the ruleset, in this example it would
* return "rulesets/java/basic.xml".
*
* @param name
* the ruleset name
* @return the full classpath to the ruleset
*/
private String resolveDeprecatedBuiltInRulesetShorthand(final String name) {
if (name == null) {
return null;
}
// Likely a simple RuleSet name
int index = name.indexOf('-');
if (index > 0) {
// Standard short name
return "rulesets/" + name.substring(0, index) + '/' + name.substring(index + 1) + ".xml";
}
// A release RuleSet?
if (name.matches("[0-9]+.*")) {
return "rulesets/releases/" + name + ".xml";
}
// Appears to be a non-standard RuleSet name
return null;
}
/**
* Extracts the rule name out of a ruleset path. E.g. for
* "/my/ruleset.xml/MyRule" it would return "MyRule". If no single rule is
* specified, <code>null</code> is returned.
*
* @param rulesetName
* the full rule set path
* @return the rule name or <code>null</code>.
*/
private String getRuleName(final String rulesetName) {
String result = null;
if (rulesetName != null) {
// Find last path separator if it exists... this might be a rule
// name
final int separatorIndex = Math.max(rulesetName.lastIndexOf('/'), rulesetName.lastIndexOf('\\'));
if (separatorIndex >= 0 && separatorIndex != rulesetName.length() - 1) {
result = rulesetName.substring(separatorIndex + 1);
}
}
return result;
}
private static boolean isHttpUrl(String name) {
String stripped = StringUtils.strip(name);
return stripped != null && (stripped.startsWith("http://") || stripped.startsWith("https://"));
}
private static boolean isValidUrl(String name) {
if (isHttpUrl(name)) {
String url = StringUtils.strip(name);
try {
// FIXME : Do we really need to perform a request? if it's a url we should treat it as one even if the server is down
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
connection.setConnectTimeout(ResourceLoader.TIMEOUT);
connection.setReadTimeout(ResourceLoader.TIMEOUT);
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
return true;
}
} catch (IOException e) {
return false;
}
}
return false;
}
private static boolean isFullRuleSetName(String name) {
return name != null && name.endsWith(".xml");
}
/**
* Parse a String comma separated list of RuleSet reference IDs into a List
* of RuleReferenceId instances.
*
* @param referenceString A comma separated list of RuleSet reference IDs.
*
* @return The corresponding List of RuleSetReferenceId instances.
*/
// TODO deprecate and remove
public static List<RuleSetReferenceId> parse(String referenceString) {
return parse(referenceString, null);
}
static List<RuleSetReferenceId> parse(String referenceString,
MessageReporter err) {
List<RuleSetReferenceId> references = new ArrayList<>();
if (referenceString != null && referenceString.trim().length() > 0) {
if (referenceString.indexOf(',') == -1) {
references.add(new RuleSetReferenceId(referenceString, null, err));
} else {
for (String name : referenceString.split(",")) {
references.add(new RuleSetReferenceId(name.trim(), null, err));
}
}
}
return references;
}
/**
* Is this an external RuleSet reference?
*
* @return <code>true</code> if this is an external reference,
* <code>false</code> otherwise.
*/
public boolean isExternal() {
return external;
}
/**
* Is this a reference to all Rules in a RuleSet, or a single Rule?
*
* @return <code>true</code> if this is a reference to all Rules,
* <code>false</code> otherwise.
*/
public boolean isAllRules() {
return allRules;
}
/**
* Get the RuleSet file name.
*
* @return The RuleSet file name if this is an external reference,
* <code>null</code> otherwise.
*/
public String getRuleSetFileName() {
return ruleSetFileName;
}
/**
* Get the Rule name.
*
* @return The Rule name. The Rule name.
*/
public String getRuleName() {
return ruleName;
}
/**
* Try to load the RuleSet resource with the specified ResourceLoader. Multiple
* attempts to get independent InputStream instances may be made, so
* subclasses must ensure they support this behavior. Delegates to an
* external RuleSetReferenceId if there is one associated with this
* instance.
*
* @param rl The {@link ResourceLoader} to use.
* @return An InputStream to that resource.
*/
public InputStream getInputStream(final ResourceLoader rl) throws IOException {
if (externalRuleSetReferenceId == null) {
if (StringUtils.isBlank(ruleSetFileName)) {
throw notFoundException();
}
try {
return rl.loadResourceAsStream(ruleSetFileName);
} catch (FileNotFoundException ignored) {
throw notFoundException();
}
} else {
return externalRuleSetReferenceId.getInputStream(rl);
}
}
private FileNotFoundException notFoundException() {
return new FileNotFoundException("Cannot resolve rule/ruleset reference '" + originalRef
+ "'" + ". Make sure the resource is a valid file or URL and is on the CLASSPATH. "
+ "Use --debug (or a fine log level) to see the current classpath.");
}
/**
* Return the String form of this Rule reference.
*
* @return Return the String form of this Rule reference, which is
* <i>ruleSetFileName</i> for all Rule external references,
* <i>ruleSetFileName/ruleName</i>, for a single Rule external
* references, or <i>ruleName</i> otherwise.
*
* @deprecated Do not rely on the format of this method, it may be changed in PMD 7.
*/
@Override
@Deprecated
public String toString() {
if (ruleSetFileName != null) {
if (allRules) {
return ruleSetFileName;
} else {
return ruleSetFileName + '/' + ruleName;
}
} else {
if (allRules) {
return "anonymous all Rule";
} else {
return ruleName;
}
}
}
}
| 19,259 | 37.752515 | 144 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/Rule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.List;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
import net.sourceforge.pmd.properties.PropertySource;
import net.sourceforge.pmd.properties.StringProperty;
/**
* This is the basic Rule interface for PMD rules.
*
* <p>
* <strong>Thread safety:</strong> PMD will create one instance of a rule per
* thread. The instances are not shared across different threads. However, a
* single rule instance is reused for analyzing multiple files.
* </p>
*/
public interface Rule extends PropertySource {
/**
* The property descriptor to universally suppress violations with messages
* matching a regular expression.
*/
// TODO 7.0.0 use PropertyDescriptor<Optional<Pattern>>
StringProperty VIOLATION_SUPPRESS_REGEX_DESCRIPTOR = new StringProperty("violationSuppressRegex",
"Suppress violations with messages matching a regular expression", null, Integer.MAX_VALUE - 1);
/**
* Name of the property to universally suppress violations on nodes which
* match a given relative XPath expression.
*/
// TODO 7.0.0 use PropertyDescriptor<Optional<String>>
StringProperty VIOLATION_SUPPRESS_XPATH_DESCRIPTOR = new StringProperty("violationSuppressXPath",
"Suppress violations on nodes which match a given relative XPath expression.", null, Integer.MAX_VALUE - 2);
/**
* Get the Language of this Rule.
*
* @return the language
*/
Language getLanguage();
/**
* Set the Language of this Rule.
*
* @param language
* the language
*/
void setLanguage(Language language);
/**
* Get the minimum LanguageVersion to which this Rule applies. If this value
* is <code>null</code> it indicates there is no minimum bound.
*
* @return the minimum language version
*/
LanguageVersion getMinimumLanguageVersion();
/**
* Set the minimum LanguageVersion to which this Rule applies.
*
* @param minimumLanguageVersion
* the minimum language version
*/
void setMinimumLanguageVersion(LanguageVersion minimumLanguageVersion);
/**
* Get the maximum LanguageVersion to which this Rule applies. If this value
* is <code>null</code> it indicates there is no maximum bound.
*
* @return the maximum language version
*/
LanguageVersion getMaximumLanguageVersion();
/**
* Set the maximum LanguageVersion to which this Rule applies.
*
* @param maximumLanguageVersion
* the maximum language version
*/
void setMaximumLanguageVersion(LanguageVersion maximumLanguageVersion);
/**
* Gets whether this Rule is deprecated. A deprecated Rule is one which:
* <ul>
* <li>is scheduled for removal in a future version of PMD</li>
* <li>or, has been removed and replaced with a non-functioning place-holder
* and will be completely removed in a future version of PMD</li>
* <li>or, has been renamed/moved and the old name will be completely
* removed in a future version of PMD</li>
* </ul>
*
* @return <code>true</code> if this rule is deprecated
*/
boolean isDeprecated();
/**
* Sets whether this Rule is deprecated.
*
* @param deprecated
* whether this rule is deprecated
*/
void setDeprecated(boolean deprecated);
/**
* Get the name of this Rule.
*
* @return the name
*/
@Override
String getName();
/**
* Set the name of this Rule.
*
* @param name
* the name
*/
void setName(String name);
/**
* Get the version of PMD in which this Rule was added. Return
* <code>null</code> if not applicable.
*
* @return version of PMD since when this rule was added
*/
String getSince();
/**
* Set the version of PMD in which this Rule was added.
*
* @param since
* the version of PMD since when this rule was added
*/
void setSince(String since);
/**
* Get the implementation class of this Rule.
*
* @return the implementation class name of this rule.
*/
String getRuleClass();
/**
* Set the class of this Rule.
*
* @param ruleClass
* the class name of this rule.
*/
void setRuleClass(String ruleClass);
/**
* Get the name of the RuleSet containing this Rule.
*
* @return the name of th ruleset containing this rule.
* @see RuleSet
*/
String getRuleSetName();
/**
* Set the name of the RuleSet containing this Rule.
*
* @param name
* the name of the ruleset containing this rule.
* @see RuleSet
*/
void setRuleSetName(String name);
/**
* Get the message to show when this Rule identifies a violation.
*
* @return the message to show for a violation.
*/
String getMessage();
/**
* Set the message to show when this Rule identifies a violation.
*
* @param message
* the message to show for a violation.
*/
void setMessage(String message);
/**
* Get the description of this Rule.
*
* @return the description
*/
String getDescription();
/**
* Set the description of this Rule.
*
* @param description
* the description
*/
void setDescription(String description);
/**
* Get the list of examples for this Rule.
*
* @return the list of examples for this rule.
*/
List<String> getExamples();
/**
* Add a single example for this Rule.
*
* @param example
* a single example to add
*/
void addExample(String example);
/**
* Get a URL for external information about this Rule.
*
* @return the URL for external information about this rule.
*/
String getExternalInfoUrl();
/**
* Set a URL for external information about this Rule.
*
* @param externalInfoUrl
* the URL for external information about this rule.
*/
void setExternalInfoUrl(String externalInfoUrl);
/**
* Get the priority of this Rule.
*
* @return the priority
*/
RulePriority getPriority();
/**
* Set the priority of this Rule.
*
* @param priority
* the priority
*/
void setPriority(RulePriority priority);
/**
* Returns the object that selects the nodes to which this rule applies.
* The selected nodes will be handed to {@link #apply(Node, RuleContext)}.
*/
RuleTargetSelector getTargetSelector();
/**
* Initialize the rule using the language processor if needed.
*
* @param languageProcessor The processor for the rule's language
*/
default void initialize(LanguageProcessor languageProcessor) {
// by default do nothing
}
/**
* Start processing. Called once per file, before apply() is first called.
*
* @param ctx the rule context
*/
void start(RuleContext ctx);
/**
* Process the given node. The nodes that are fed to this method
* are the nodes selected by {@link #getTargetSelector()}.
*
* @param target Node on which to apply the rule
* @param ctx Rule context, handling violations
*/
void apply(Node target, RuleContext ctx);
/**
* End processing. Called once per file, after apply() is last called.
*
* @param ctx
* the rule context
*/
void end(RuleContext ctx);
/**
* Creates a new copy of this rule.
* @return A new exact copy of this rule
*/
Rule deepCopy();
}
| 8,110 | 25.946844 | 120 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/PMDVersion.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stores the current PMD version and provides utility methods around it.
*/
public final class PMDVersion {
private static final Logger LOG = LoggerFactory.getLogger(PMDVersion.class);
/**
* Constant that contains always the current version of PMD.
*/
public static final String VERSION;
private static final String UNKNOWN_VERSION = "unknown";
/**
* Determines the version from maven's generated pom.properties file.
*/
static {
String pmdVersion = UNKNOWN_VERSION;
try (InputStream stream = PMDVersion.class.getResourceAsStream("/META-INF/maven/net.sourceforge.pmd/pmd-core/pom.properties")) {
if (stream != null) {
final Properties properties = new Properties();
properties.load(stream);
pmdVersion = properties.getProperty("version");
}
} catch (final IOException e) {
LOG.debug("Couldn't determine version of PMD", e);
}
VERSION = pmdVersion;
}
private PMDVersion() {
throw new AssertionError("Can't instantiate utility classes");
}
/**
* Retrieves the next major release to be expected.
* Useful when logging deprecation messages to indicate when support will be removed.
*
* @return The next major release to be expected.
*/
public static String getNextMajorRelease() {
if (isUnknown()) {
return UNKNOWN_VERSION;
}
final int major = Integer.parseInt(VERSION.split("\\.")[0]);
return (major + 1) + ".0.0";
}
/**
* Checks if the current version is unknown.
* @return True if an unknown version, false otherwise
*/
@SuppressWarnings("PMD.LiteralsFirstInComparisons")
public static boolean isUnknown() {
return UNKNOWN_VERSION.equals(VERSION);
}
/**
* Checks if the current version is a snapshot.
* @return True if a snapshot release, false otherwise
*/
public static boolean isSnapshot() {
return VERSION.endsWith("-SNAPSHOT");
}
}
| 2,358 | 27.768293 | 136 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.internal.RuleApplicator;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Grouping of Rules per Language in a RuleSet.
*
* @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be
*
* @deprecated Internal API
*/
@Deprecated
@InternalApi
public class RuleSets {
private final List<RuleSet> ruleSets;
private RuleApplicator ruleApplicator;
/**
* Copy constructor. Deep copies RuleSets.
*
* @param ruleSets The RuleSets to copy.
*/
public RuleSets(final RuleSets ruleSets) {
List<RuleSet> rsets = new ArrayList<>();
for (final RuleSet rs : ruleSets.ruleSets) {
rsets.add(new RuleSet(rs));
}
this.ruleSets = Collections.unmodifiableList(rsets);
}
public RuleSets(Collection<? extends RuleSet> ruleSets) {
this.ruleSets = Collections.unmodifiableList(new ArrayList<>(ruleSets));
}
/**
* Public constructor. Add the given rule set.
*
* @param ruleSet the RuleSet
*/
public RuleSets(RuleSet ruleSet) {
this.ruleSets = Collections.singletonList(ruleSet);
}
public void initializeRules(LanguageProcessorRegistry lpReg, MessageReporter reporter) {
// this is abusing the mutability of RuleSet, will go away eventually.
for (RuleSet rset : ruleSets) {
for (Iterator<Rule> iterator = rset.getRules().iterator(); iterator.hasNext();) {
Rule rule = iterator.next();
try {
rule.initialize(lpReg.getProcessor(rule.getLanguage()));
} catch (Exception e) {
reporter.errorEx(
"Exception while initializing rule " + rule.getName() + ", the rule will not be run", e);
iterator.remove();
}
}
}
}
private RuleApplicator prepareApplicator() {
return RuleApplicator.build(ruleSets.stream().flatMap(it -> it.getRules().stream())::iterator);
}
/**
* Get all the RuleSets.
*
* @return RuleSet[]
*/
public RuleSet[] getAllRuleSets() {
return ruleSets.toArray(new RuleSet[0]);
}
// internal
List<RuleSet> getRuleSetsInternal() {
return ruleSets;
}
public Iterator<RuleSet> getRuleSetsIterator() {
return ruleSets.iterator();
}
/**
* Return all rules from all rulesets.
*
* @return Set
*/
public Set<Rule> getAllRules() {
Set<Rule> result = new HashSet<>();
for (RuleSet r : ruleSets) {
result.addAll(r.getRules());
}
return result;
}
/**
* Check if a given source file should be checked by rules in this RuleSets.
*
* @param file
* the source file to check
* @return <code>true</code> if the file should be checked,
* <code>false</code> otherwise
*/
public boolean applies(TextFile file) {
for (RuleSet ruleSet : ruleSets) {
if (ruleSet.applies(file)) {
return true;
}
}
return false;
}
/**
* Apply all applicable rules to the compilation units. Applicable means the
* language of the rules must match the language of the source (@see
* applies).
*
* @param root the List of compilation units; the type these must have,
* depends on the source language
* @param listener Listener that will handle events while analysing.
*/
public void apply(RootNode root, FileAnalysisListener listener) {
if (ruleApplicator == null) {
// initialize here instead of ctor, because some rules properties
// are set after creating the ruleset, and jaxen xpath queries
// initialize their XPath expressions when calling getRuleChainVisits()... fixme
this.ruleApplicator = prepareApplicator();
}
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.RULE_AST_INDEXATION)) {
ruleApplicator.index(root);
}
for (RuleSet ruleSet : ruleSets) {
if (ruleSet.applies(root.getTextDocument().getFileId())) {
ruleApplicator.apply(ruleSet.getRules(), listener);
}
}
}
/**
* Returns the first Rule found with the given name.
*
* Note: Since we support multiple languages, rule names are not expected to
* be unique within any specific ruleset.
*
* @param ruleName
* the exact name of the rule to find
* @return the rule or null if not found
*/
public Rule getRuleByName(String ruleName) {
Rule rule = null;
for (Iterator<RuleSet> i = ruleSets.iterator(); i.hasNext() && rule == null;) {
RuleSet ruleSet = i.next();
rule = ruleSet.getRuleByName(ruleName);
}
return rule;
}
/**
* Determines the total count of rules that are used in all rule sets.
*
* @return the count
*/
public int ruleCount() {
int count = 0;
for (RuleSet r : ruleSets) {
count += r.getRules().size();
}
return count;
}
/**
* Remove and collect any rules that report problems.
*
* @param collector
*/
public void removeDysfunctionalRules(Collection<Rule> collector) {
for (RuleSet ruleSet : ruleSets) {
ruleSet.removeDysfunctionalRules(collector);
}
}
/**
* Retrieves a checksum of the rulesets being used. Any change to any rule
* of any ruleset should trigger a checksum change.
*
* @return The checksum for this ruleset collection.
*/
public long getChecksum() {
long checksum = 1;
for (final RuleSet ruleSet : ruleSets) {
checksum = checksum * 31 + ruleSet.getChecksum();
}
return checksum;
}
}
| 6,755 | 29.570136 | 113 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/AbstractConfiguration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.nio.charset.Charset;
/**
* Base configuration class for both PMD and CPD.
*
* @author Brian Remedios
*/
public abstract class AbstractConfiguration {
private Charset sourceEncoding = Charset.forName(System.getProperty("file.encoding"));
/**
* Create a new abstract configuration.
*/
protected AbstractConfiguration() {
super();
}
/**
* Get the character encoding of source files.
*
* @return The character encoding.
*/
public Charset getSourceEncoding() {
return sourceEncoding;
}
/**
* Set the character encoding of source files.
*
* @param sourceEncoding
* The character encoding.
*/
public void setSourceEncoding(String sourceEncoding) {
this.sourceEncoding = Charset.forName(sourceEncoding);
}
}
| 971 | 20.6 | 90 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.DESCRIPTION;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.EXCLUDE;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.EXCLUDE_PATTERN;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.INCLUDE_PATTERN;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.NAME;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.PRIORITY;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.REF;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.RULE;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.RULESET;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import net.sourceforge.pmd.RuleSet.RuleSetBuilder;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.rules.RuleFactory;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.StringUtil;
import net.sourceforge.pmd.util.internal.xml.PmdXmlReporter;
import net.sourceforge.pmd.util.internal.xml.XmlErrorMessages;
import net.sourceforge.pmd.util.internal.xml.XmlUtil;
import net.sourceforge.pmd.util.log.MessageReporter;
import com.github.oowekyala.ooxml.DomUtils;
import com.github.oowekyala.ooxml.messages.NiceXmlMessageSpec;
import com.github.oowekyala.ooxml.messages.OoxmlFacade;
import com.github.oowekyala.ooxml.messages.PositionedXmlDoc;
import com.github.oowekyala.ooxml.messages.XmlException;
import com.github.oowekyala.ooxml.messages.XmlMessageHandler;
import com.github.oowekyala.ooxml.messages.XmlMessageReporterBase;
import com.github.oowekyala.ooxml.messages.XmlPosition;
import com.github.oowekyala.ooxml.messages.XmlPositioner;
import com.github.oowekyala.ooxml.messages.XmlSeverity;
/**
* RuleSetFactory is responsible for creating RuleSet instances from XML
* content. See {@link RuleSetLoader} for configuration options and
* their defaults.
*/
final class RuleSetFactory {
private static final Logger LOG = LoggerFactory.getLogger(RuleSetFactory.class);
private final ResourceLoader resourceLoader;
private final LanguageRegistry languageRegistry;
private final RulePriority minimumPriority;
private final boolean warnDeprecated;
private final RuleSetFactoryCompatibility compatibilityFilter;
private final MessageReporter reporter;
private final boolean includeDeprecatedRuleReferences;
private final Map<RuleSetReferenceId, RuleSet> parsedRulesets = new HashMap<>();
RuleSetFactory(ResourceLoader resourceLoader,
LanguageRegistry languageRegistry,
RulePriority minimumPriority,
boolean warnDeprecated,
RuleSetFactoryCompatibility compatFilter,
boolean includeDeprecatedRuleReferences,
MessageReporter reporter) {
this.resourceLoader = resourceLoader;
this.languageRegistry = Objects.requireNonNull(languageRegistry);
this.minimumPriority = minimumPriority;
this.warnDeprecated = warnDeprecated;
this.includeDeprecatedRuleReferences = includeDeprecatedRuleReferences;
this.compatibilityFilter = compatFilter;
this.reporter = reporter;
}
/**
* Create a RuleSet from a RuleSetReferenceId. Priority filtering is ignored
* when loading a single Rule. The currently configured ResourceLoader is used.
*
* @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet to create.
*
* @return A new RuleSet.
*/
@NonNull RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId) {
return createRuleSet(ruleSetReferenceId, includeDeprecatedRuleReferences);
}
private @NonNull RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences)
throws RuleSetLoadException {
return readDocument(ruleSetReferenceId, withDeprecatedRuleReferences);
}
/**
* Create a Rule from a RuleSet created from a file name resource. The
* currently configured ResourceLoader is used.
* <p>
* Any Rules in the RuleSet other than the one being created, are _not_
* created. Deprecated rules are _not_ ignored, so that they can be
* referenced.
*
* @param ruleSetReferenceId
* The RuleSetReferenceId of the RuleSet with the Rule to create.
* @param withDeprecatedRuleReferences
* Whether RuleReferences that are deprecated should be ignored
* or not
* @return A new Rule.
*/
private Rule createRule(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) {
RuleSetReferenceId parentRuleset = ruleSetReferenceId.getParentRulesetIfThisIsARule();
if (parentRuleset == null) {
throw new IllegalArgumentException(
"Cannot parse a single Rule from an all Rule RuleSet reference: <" + ruleSetReferenceId + ">.");
}
// can't use computeIfAbsent as creating a ruleset may add more entries to the map.
RuleSet ruleSet = parsedRulesets.get(parentRuleset);
if (ruleSet == null) {
ruleSet = createRuleSet(ruleSetReferenceId, withDeprecatedRuleReferences);
parsedRulesets.put(ruleSetReferenceId, ruleSet);
}
return ruleSet.getRuleByName(ruleSetReferenceId.getRuleName());
}
/**
* Parse a ruleset node to construct a RuleSet.
*
* @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed.
* @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored
* or not
*
* @return The new RuleSet.
*
* @throws RuleSetLoadException If the ruleset cannot be parsed (eg IO exception, malformed XML, validation errors)
*/
private @NonNull RuleSet readDocument(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) {
try (CheckedInputStream inputStream = new CheckedInputStream(ruleSetReferenceId.getInputStream(resourceLoader), new Adler32())) {
if (!ruleSetReferenceId.isExternal()) {
throw new IllegalArgumentException(
"Cannot parse a RuleSet from a non-external reference: <" + ruleSetReferenceId + ">.");
}
XmlMessageHandler printer = getXmlMessagePrinter();
DocumentBuilder builder = createDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
inputSource.setSystemId(ruleSetReferenceId.getRuleSetFileName());
OoxmlFacade ooxml = new OoxmlFacade()
.withPrinter(printer)
.withAnsiColors(false);
PositionedXmlDoc parsed = ooxml.parse(builder, inputSource);
@SuppressWarnings("PMD.CloseResource")
PmdXmlReporterImpl err = new PmdXmlReporterImpl(reporter, ooxml, parsed.getPositioner());
try {
RuleSetBuilder ruleSetBuilder = new RuleSetBuilder(inputStream.getChecksum().getValue()).withFileName(ruleSetReferenceId.getRuleSetFileName());
RuleSet ruleSet = parseRulesetNode(ruleSetReferenceId, withDeprecatedRuleReferences, parsed, ruleSetBuilder, err);
if (err.errCount > 0) {
// note this makes us jump to the catch branch
// these might have been non-fatal errors
String message;
if (err.errCount == 1) {
message = "An XML validation error occurred";
} else {
message = err.errCount + " XML validation errors occurred";
}
throw new RuleSetLoadException(ruleSetReferenceId, message);
}
return ruleSet;
} catch (Exception | Error e) {
throw e;
}
} catch (ParserConfigurationException | IOException ex) {
throw new RuleSetLoadException(ruleSetReferenceId, ex);
}
}
private RuleSet parseRulesetNode(RuleSetReferenceId ruleSetReferenceId,
boolean withDeprecatedRuleReferences,
PositionedXmlDoc parsed,
RuleSetBuilder builder,
PmdXmlReporter err) {
Element ruleSetElement = parsed.getDocument().getDocumentElement();
if (ruleSetElement.hasAttribute("name")) {
builder.withName(ruleSetElement.getAttribute("name"));
} else {
err.at(ruleSetElement).warn("RuleSet name is missing. Future versions of PMD will require it.");
builder.withName("Missing RuleSet Name");
}
Set<String> rulesetReferences = new HashSet<>();
for (Element node : DomUtils.children(ruleSetElement)) {
String text = XmlUtil.parseTextNode(node);
if (DESCRIPTION.matchesElt(node)) {
builder.withDescription(text);
} else if (INCLUDE_PATTERN.matchesElt(node)) {
final Pattern pattern = parseRegex(node, text, err);
if (pattern == null) {
continue;
}
builder.withFileInclusions(pattern);
} else if (EXCLUDE_PATTERN.matchesElt(node)) {
final Pattern pattern = parseRegex(node, text, err);
if (pattern == null) {
continue;
}
builder.withFileExclusions(pattern);
} else if (RULE.matchesElt(node)) {
try {
parseRuleNode(ruleSetReferenceId, builder, node, withDeprecatedRuleReferences, rulesetReferences, err);
} catch (XmlException ignored) {
// already reported (it's an XmlException), error count
// was incremented so parent method will throw RuleSetLoadException.
}
} else {
err.at(node).error(XmlErrorMessages.ERR__UNEXPECTED_ELEMENT_IN,
node.getTagName(),
RULESET);
}
}
if (!builder.hasDescription()) {
err.at(ruleSetElement).warn("RuleSet description is missing. Future versions of PMD will require it.");
builder.withDescription("Missing description");
}
builder.filterRulesByPriority(minimumPriority);
return builder.build();
}
private Pattern parseRegex(Element node, String text, PmdXmlReporter err) {
final Pattern pattern;
try {
pattern = Pattern.compile(text);
} catch (PatternSyntaxException pse) {
err.at(node).error(pse);
return null;
}
return pattern;
}
private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
/*
* parser hardening
* https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
*/
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
// Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
// JDK7+ - http://xml.org/sax/features/external-general-entities
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
// JDK7+ - http://xml.org/sax/features/external-parameter-entities
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Disable external DTDs as well
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
} catch (final ParserConfigurationException e) {
// an unsupported feature... too bad, but won't fail execution due to this
LOG.warn("Ignored unsupported XML Parser Feature for parsing rulesets", e);
}
return dbf.newDocumentBuilder();
}
/**
* Parse a rule node.
*
* @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed.
* @param ruleSetBuilder The RuleSet being constructed.
* @param ruleNode Must be a rule element node.
* @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored
* or not
* @param rulesetReferences keeps track of already processed complete ruleset references in order to log
* a warning
*/
private void parseRuleNode(RuleSetReferenceId ruleSetReferenceId,
RuleSetBuilder ruleSetBuilder,
Element ruleNode,
boolean withDeprecatedRuleReferences,
Set<String> rulesetReferences,
PmdXmlReporter err) {
if (REF.hasAttribute(ruleNode)) {
String ref = REF.getAttributeOrThrow(ruleNode, err);
RuleSetReferenceId refId = parseReferenceAndWarn(ref, REF.getAttributeNode(ruleNode), err);
if (refId != null) {
if (refId.isAllRules()) {
parseRuleSetReferenceNode(ruleSetBuilder, ruleNode, ref, refId, rulesetReferences, err);
} else {
parseRuleReferenceNode(ruleSetReferenceId, ruleSetBuilder, ruleNode, ref, refId, withDeprecatedRuleReferences, err);
}
return;
}
}
parseSingleRuleNode(ruleSetReferenceId, ruleSetBuilder, ruleNode, err);
}
/**
* Parse a rule node as an RuleSetReference for all Rules. Every Rule from
* the referred to RuleSet will be added as a RuleReference except for those
* explicitly excluded, below the minimum priority threshold for this
* RuleSetFactory, or which are deprecated.
*
* @param ruleSetBuilder
* The RuleSet being constructed.
* @param ruleElement
* Must be a rule element node.
* @param ref
* The RuleSet reference.
* @param rulesetReferences keeps track of already processed complete ruleset references in order to log a warning
*/
private void parseRuleSetReferenceNode(RuleSetBuilder ruleSetBuilder,
Element ruleElement,
String ref,
RuleSetReferenceId ruleSetReferenceId, Set<String> rulesetReferences,
PmdXmlReporter err) {
RulePriority priority = null;
Map<String, Element> excludedRulesCheck = new HashMap<>();
for (Element child : XmlUtil.getElementChildrenList(ruleElement)) {
if (EXCLUDE.matchesElt(child)) {
String excludedRuleName;
try {
excludedRuleName = NAME.getAttributeOrThrow(child, err);
} catch (XmlException ignored) {
// has been reported
continue;
}
excludedRuleName = compatibilityFilter.applyExclude(ref, excludedRuleName, this.warnDeprecated);
if (excludedRuleName != null) {
excludedRulesCheck.put(excludedRuleName, child);
}
} else if (PRIORITY.matchesElt(child)) {
priority = RuleFactory.parsePriority(err, child);
} else {
XmlUtil.reportIgnoredUnexpectedElt(ruleElement, child, setOf(EXCLUDE, PRIORITY), err);
}
}
final RuleSetReference ruleSetReference = new RuleSetReference(ref, true, excludedRulesCheck.keySet());
// load the ruleset with minimum priority low, so that we get all rules, to be able to exclude any rule
// minimum priority will be applied again, before constructing the final ruleset
RuleSetFactory ruleSetFactory = toLoader().filterAbovePriority(RulePriority.LOW).warnDeprecated(false).toFactory();
RuleSet otherRuleSet = ruleSetFactory.createRuleSet(ruleSetReferenceId);
List<RuleReference> potentialRules = new ArrayList<>();
int countDeprecated = 0;
for (Rule rule : otherRuleSet.getRules()) {
excludedRulesCheck.remove(rule.getName());
if (!ruleSetReference.getExcludes().contains(rule.getName())) {
RuleReference ruleReference = new RuleReference(rule, ruleSetReference);
// override the priority
if (priority != null) {
ruleReference.setPriority(priority);
}
if (rule.isDeprecated()) {
countDeprecated++;
}
potentialRules.add(ruleReference);
}
}
boolean rulesetDeprecated = false;
if (!potentialRules.isEmpty() && potentialRules.size() == countDeprecated) {
// all rules in the ruleset have been deprecated - the ruleset itself is considered to be deprecated
rulesetDeprecated = true;
err.at(REF.getAttributeNode(ruleElement))
.warn("The RuleSet {0} has been deprecated and will be removed in PMD {1}",
ref, PMDVersion.getNextMajorRelease());
}
for (RuleReference r : potentialRules) {
if (rulesetDeprecated || !r.getRule().isDeprecated()) {
// add the rule, if either the ruleset itself is deprecated (then we add all rules)
// or if the rule is not deprecated (in that case, the ruleset might contain deprecated as well
// as valid rules)
ruleSetBuilder.addRuleIfNotExists(r);
}
}
if (!excludedRulesCheck.isEmpty()) {
excludedRulesCheck.forEach(
(name, elt) ->
err.at(elt).warn("Exclude pattern ''{0}'' did not match any rule in ruleset ''{1}''", name, ref));
}
if (rulesetReferences.contains(ref)) {
err.at(ruleElement).warn("The ruleset {0} is referenced multiple times in ruleset ''{1}''", ref, ruleSetBuilder.getName());
}
rulesetReferences.add(ref);
}
private RuleSetReferenceId parseReferenceAndWarn(String ref,
Node xmlPlace,
PmdXmlReporter err) {
ref = compatibilityFilter.applyRef(ref, this.warnDeprecated);
if (ref == null) {
err.at(xmlPlace).warn("Rule reference references a deleted rule, ignoring");
return null; // deleted rule
}
// only emit a warning if we check for deprecated syntax
MessageReporter subReporter = warnDeprecated ? err.at(xmlPlace) : MessageReporter.quiet();
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(ref, subReporter);
if (references.size() > 1 && warnDeprecated) {
err.at(xmlPlace).warn("Using a comma separated list as a ref attribute is deprecated. "
+ "All references but the first are ignored.");
} else if (references.isEmpty()) {
err.at(xmlPlace).warn("Empty ref attribute");
return null;
}
return references.get(0);
}
/**
* Parse a rule node as a single Rule. The Rule has been fully defined
* within the context of the current RuleSet.
*
* @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed.
* @param ruleSetBuilder The RuleSet being constructed.
* @param ruleNode Must be a rule element node.
* @param err Error reporter
*/
private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId,
RuleSetBuilder ruleSetBuilder,
Element ruleNode,
PmdXmlReporter err) {
// Stop if we're looking for a particular Rule, and this element is not
// it.
if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName())
&& !isRuleName(ruleNode, ruleSetReferenceId.getRuleName())) {
return;
}
Rule rule = new RuleFactory(resourceLoader, languageRegistry).buildRule(ruleNode, err);
rule.setRuleSetName(ruleSetBuilder.getName());
if (warnDeprecated && StringUtils.isBlank(ruleNode.getAttribute("language"))) {
err.at(ruleNode).warn(
"Rule {0}/{1} does not mention attribute language='{2}',"
+ " please mention it explicitly to be compatible with PMD 7",
ruleSetReferenceId.getRuleSetFileName(), rule.getName(),
rule.getLanguage().getTerseName());
}
ruleSetBuilder.addRule(rule);
}
/**
* Parse a rule node as a RuleReference. A RuleReference is a single Rule
* which comes from another RuleSet with some of it's attributes potentially
* overridden.
*
* @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed.
* @param ruleSetBuilder The RuleSet being constructed.
* @param ruleNode Must be a rule element node.
* @param ref A reference to a Rule.
* @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored
* @param err Error reporter
*/
private void parseRuleReferenceNode(RuleSetReferenceId ruleSetReferenceId,
RuleSetBuilder ruleSetBuilder,
Element ruleNode,
String ref,
RuleSetReferenceId otherRuleSetReferenceId,
boolean withDeprecatedRuleReferences,
PmdXmlReporter err) {
// Stop if we're looking for a particular Rule, and this element is not
// it.
if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName())
&& !isRuleName(ruleNode, ruleSetReferenceId.getRuleName())) {
return;
}
// load the ruleset with minimum priority low, so that we get all rules, to be able to exclude any rule
// minimum priority will be applied again, before constructing the final ruleset
RuleSetFactory ruleSetFactory = toLoader().filterAbovePriority(RulePriority.LOW).warnDeprecated(false).toFactory();
boolean isSameRuleSet = false;
if (!otherRuleSetReferenceId.isExternal()
&& containsRule(ruleSetReferenceId, otherRuleSetReferenceId.getRuleName())) {
otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId, err.at(REF.getAttributeNode(ruleNode)));
isSameRuleSet = true;
} else if (otherRuleSetReferenceId.isExternal()
&& otherRuleSetReferenceId.getRuleSetFileName().equals(ruleSetReferenceId.getRuleSetFileName())) {
otherRuleSetReferenceId = new RuleSetReferenceId(otherRuleSetReferenceId.getRuleName(), ruleSetReferenceId, err.at(REF.getAttributeNode(ruleNode)));
isSameRuleSet = true;
}
// do not ignore deprecated rule references
Rule referencedRule = ruleSetFactory.createRule(otherRuleSetReferenceId, true);
if (referencedRule == null) {
throw err.at(ruleNode).error(
"Unable to find referenced rule {0}"
+ "; perhaps the rule name is misspelled?",
otherRuleSetReferenceId.getRuleName());
}
if (warnDeprecated && referencedRule.isDeprecated()) {
if (referencedRule instanceof RuleReference) {
RuleReference ruleReference = (RuleReference) referencedRule;
err.at(ruleNode).warn(
"Use Rule name {0}/{1} instead of the deprecated Rule name {2}. PMD {3}"
+ " will remove support for this deprecated Rule name usage.",
ruleReference.getRuleSetReference().getRuleSetFileName(),
ruleReference.getOriginalName(), otherRuleSetReferenceId,
PMDVersion.getNextMajorRelease());
} else {
err.at(ruleNode).warn(
"Discontinue using Rule name {0} as it is scheduled for removal from PMD."
+ " PMD {1} will remove support for this Rule.",
otherRuleSetReferenceId, PMDVersion.getNextMajorRelease());
}
}
RuleSetReference ruleSetReference = new RuleSetReference(otherRuleSetReferenceId.getRuleSetFileName(), false);
RuleReference ruleReference;
try {
ruleReference = new RuleFactory(resourceLoader, languageRegistry).decorateRule(referencedRule, ruleSetReference, ruleNode, err);
} catch (XmlException e) {
throw err.at(ruleNode).error(e, "Error while parsing rule reference");
}
if (warnDeprecated && ruleReference.isDeprecated() && !isSameRuleSet) {
err.at(ruleNode).warn(
"Use Rule name {0}/{1} instead of the deprecated Rule name {2}/{3}. PMD {4}"
+ " will remove support for this deprecated Rule name usage.",
ruleReference.getRuleSetReference().getRuleSetFileName(),
ruleReference.getOriginalName(),
ruleSetReferenceId.getRuleSetFileName(),
ruleReference.getName(),
PMDVersion.getNextMajorRelease());
}
if (withDeprecatedRuleReferences || !isSameRuleSet || !ruleReference.isDeprecated()) {
Rule existingRule = ruleSetBuilder.getExistingRule(ruleReference);
if (existingRule instanceof RuleReference) {
RuleReference existingRuleReference = (RuleReference) existingRule;
// the only valid use case is: the existing rule does not override anything yet
// which means, it is a plain reference. And the new reference overrides.
// for all other cases, we should log a warning
if (existingRuleReference.hasOverriddenAttributes() || !ruleReference.hasOverriddenAttributes()) {
err.at(ruleNode).warn(
"The rule {0} is referenced multiple times in ruleset ''{1}''. "
+ "Only the last rule configuration is used.",
ruleReference.getName(),
ruleSetBuilder.getName());
}
}
ruleSetBuilder.addRuleReplaceIfExists(ruleReference);
}
}
/**
* Check whether the given ruleName is contained in the given ruleset.
*
* @param ruleSetReferenceId the ruleset to check
* @param ruleName the rule name to search for
*
* @return {@code true} if the ruleName exists
*/
private boolean containsRule(RuleSetReferenceId ruleSetReferenceId, String ruleName) {
// TODO: avoid reloading the ruleset once again
boolean found = false;
try (InputStream ruleSet = ruleSetReferenceId.getInputStream(resourceLoader)) {
DocumentBuilder builder = createDocumentBuilder();
Document document = builder.parse(ruleSet);
Element ruleSetElement = document.getDocumentElement();
NodeList rules = ruleSetElement.getElementsByTagName("rule");
for (int i = 0; i < rules.getLength(); i++) {
Element rule = (Element) rules.item(i);
if (rule.hasAttribute("name") && rule.getAttribute("name").equals(ruleName)) {
found = true;
break;
}
}
} catch (Exception e) {
throw new RuleSetLoadException(ruleSetReferenceId, e);
}
return found;
}
/**
* Determine if the specified rule element will represent a Rule with the
* given name.
*
* @param ruleElement The rule element.
* @param ruleName The Rule name.
*
* @return {@code true} if the Rule would have the given name, {@code false} otherwise.
*/
private boolean isRuleName(Element ruleElement, String ruleName) {
if (ruleElement.hasAttribute("name")) {
return ruleElement.getAttribute("name").equals(ruleName);
} else if (ruleElement.hasAttribute("ref")) {
RuleSetReferenceId ruleSetReferenceId = RuleSetReferenceId.parse(ruleElement.getAttribute("ref")).get(0);
return ruleSetReferenceId.getRuleName() != null && ruleSetReferenceId.getRuleName().equals(ruleName);
} else {
return false;
}
}
/**
* Create a new {@link RuleSetLoader} with the same config as this
* factory. This is a transitional API.
*/
public RuleSetLoader toLoader() {
return new RuleSetLoader().loadResourcesWith(resourceLoader)
.filterAbovePriority(minimumPriority)
.warnDeprecated(warnDeprecated)
.enableCompatibility(compatibilityFilter != null)
.includeDeprecatedRuleReferences(includeDeprecatedRuleReferences);
}
private @NonNull XmlMessageHandler getXmlMessagePrinter() {
return entry -> {
Level level = entry.getSeverity() == XmlSeverity.WARNING ? Level.WARN : Level.ERROR;
String quotedText = StringUtil.quoteMessageFormat(entry.toString());
reporter.logEx(level, quotedText, new Object[0], entry.getCause());
};
}
private static final class PmdXmlReporterImpl
extends XmlMessageReporterBase<MessageReporter>
implements PmdXmlReporter {
private final MessageReporter pmdReporter;
private int errCount;
PmdXmlReporterImpl(MessageReporter pmdReporter, OoxmlFacade ooxml, XmlPositioner positioner) {
super(ooxml, positioner);
this.pmdReporter = pmdReporter;
}
@Override
protected MessageReporter create2ndStage(XmlPosition position, XmlPositioner positioner) {
return new MessageReporter() {
@Override
public boolean isLoggable(Level level) {
return pmdReporter.isLoggable(level);
}
@Override
public void log(Level level, String message, Object... formatArgs) {
logEx(level, message, formatArgs, null);
}
@Override
public void logEx(Level level, String message, Object[] formatArgs, @Nullable Throwable error) {
newException(level, error, message, formatArgs);
}
@Override
public XmlException error(@Nullable Throwable cause, @Nullable String contextMessage, Object... formatArgs) {
return newException(Level.ERROR, cause, contextMessage, formatArgs);
}
@Override
public XmlException newException(Level level, Throwable cause, String message, Object... formatArgs) {
XmlSeverity severity;
switch (level) {
case WARN:
severity = XmlSeverity.WARNING;
break;
case ERROR:
errCount++;
severity = XmlSeverity.ERROR;
break;
default:
throw new IllegalArgumentException("unexpected level " + level);
}
if (message == null && formatArgs.length != 0) {
throw new IllegalArgumentException("Cannot pass format arguments for null message");
}
String actualMessage = message == null ? cause.getMessage()
: MessageFormat.format(message, formatArgs);
NiceXmlMessageSpec spec =
new NiceXmlMessageSpec(position, actualMessage)
.withSeverity(severity)
.withCause(cause);
String fullMessage = ooxml.getFormatter().formatSpec(ooxml, spec, positioner);
XmlException ex = new XmlException(spec, fullMessage);
ooxml.getPrinter().accept(ex); // spec of newException is also to log.
return ex;
}
@Override
public int numErrors() {
return pmdReporter.numErrors();
}
};
}
}
}
| 35,471 | 45.982781 | 160 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/PMDConfiguration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.cache.AnalysisCache;
import net.sourceforge.pmd.cache.FileAnalysisCache;
import net.sourceforge.pmd.cache.NoopAnalysisCache;
import net.sourceforge.pmd.internal.util.ClasspathClassLoader;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.RendererFactory;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
/**
* This class contains the details for the runtime configuration of a
* PMD run. Once configured, use {@link PmdAnalysis#create(PMDConfiguration)}
* in a try-with-resources to execute the analysis (see {@link PmdAnalysis}).
*
* <h3>Rulesets</h3>
*
* <ul>
* <li>You can configure paths to the rulesets to use with {@link #addRuleSet(String)}.
* These can be file paths or classpath resources.</li>
* <li>Use {@link #setMinimumPriority(RulePriority)} to control the minimum priority a
* rule must have to be included. Defaults to the lowest priority, ie all rules are loaded.</li>
* <li>Use {@link #setRuleSetFactoryCompatibilityEnabled(boolean)} to disable the
* compatibility measures for removed and renamed rules in the rulesets that will
* be loaded.
* </ul>
*
* <h3>Source files</h3>
*
* <ul>
* <li>The default encoding of source files is the system default as
* returned by <code>System.getProperty("file.encoding")</code>.
* You can set it with {@link #setSourceEncoding(String)}.</li>
* <li>The source files to analyze can be given in many ways. See
* {@link #addInputPath(Path)} {@link #setInputFilePath(Path)}, {@link #setInputUri(URI)}.
* <li>Files are assigned a language based on their name. The language
* version of languages can be given with
* {@link #setDefaultLanguageVersion(LanguageVersion)}.
* The default language assignment can be overridden with
* {@link #setForceLanguageVersion(LanguageVersion)}.</li>
* </ul>
*
* <h3>Rendering</h3>
*
* <ul>
* <li>The renderer format to use for Reports. {@link #getReportFormat()}</li>
* <li>The file to which the Report should render. {@link #getReportFile()}</li>
* <li>Configure the root paths that are used to relativize file names in reports via {@link #addRelativizeRoot(Path)}.
* This enables to get short names in reports.</li>
* <li>The initialization properties to use when creating a Renderer instance.
* {@link #getReportProperties()}</li>
* <li>An indicator of whether to show suppressed Rule violations in Reports.
* {@link #isShowSuppressedViolations()}</li>
* </ul>
*
* <h3>Language configuration </h3>
* <ul>
* <li>Use {@link #setSuppressMarker(String)} to change the comment marker for suppression comments. Defaults to {@value #DEFAULT_SUPPRESS_MARKER}.</li>
* <li>See {@link #setClassLoader(ClassLoader)} and {@link #prependAuxClasspath(String)} for
* information for how to configure classpath for Java analysis.</li>
* <li>You can set additional language properties with {@link #getLanguageProperties(Language)}</li>
* </ul>
*
* <h3>Miscellaneous</h3>
* <ul>
* <li>Use {@link #setThreads(int)} to control the parallelism of the analysis. Defaults
* one thread per available processor. {@link #getThreads()}</li>
* </ul>
*/
public class PMDConfiguration extends AbstractConfiguration {
private static final LanguageRegistry DEFAULT_REGISTRY = LanguageRegistry.PMD;
/** The default suppress marker string. */
public static final String DEFAULT_SUPPRESS_MARKER = "NOPMD";
// General behavior options
private String suppressMarker = DEFAULT_SUPPRESS_MARKER;
private int threads = Runtime.getRuntime().availableProcessors();
private ClassLoader classLoader = getClass().getClassLoader();
private final LanguageVersionDiscoverer languageVersionDiscoverer;
private LanguageVersion forceLanguageVersion;
private MessageReporter reporter = new SimpleMessageReporter(LoggerFactory.getLogger(PmdAnalysis.class));
// Rule and source file options
private List<String> ruleSets = new ArrayList<>();
private RulePriority minimumPriority = RulePriority.LOW;
private @NonNull List<Path> inputPaths = new ArrayList<>();
private URI inputUri;
private Path inputFilePath;
private Path ignoreFilePath;
private boolean ruleSetFactoryCompatibilityEnabled = true;
// Reporting options
private String reportFormat;
private Path reportFile;
private Properties reportProperties = new Properties();
private boolean showSuppressedViolations = false;
private boolean failOnViolation = true;
private AnalysisCache analysisCache = new NoopAnalysisCache();
private boolean ignoreIncrementalAnalysis;
private final LanguageRegistry langRegistry;
private final List<Path> relativizeRoots = new ArrayList<>();
private final Map<Language, LanguagePropertyBundle> langProperties = new HashMap<>();
public PMDConfiguration() {
this(DEFAULT_REGISTRY);
}
public PMDConfiguration(@NonNull LanguageRegistry languageRegistry) {
this.langRegistry = Objects.requireNonNull(languageRegistry);
this.languageVersionDiscoverer = new LanguageVersionDiscoverer(languageRegistry);
}
/**
* Get the suppress marker. This is the source level marker used to indicate
* a RuleViolation should be suppressed.
*
* @return The suppress marker.
*/
public String getSuppressMarker() {
return suppressMarker;
}
/**
* Set the suppress marker.
*
* @param suppressMarker
* The suppress marker to use.
*/
public void setSuppressMarker(String suppressMarker) {
Objects.requireNonNull(suppressMarker, "Suppress marker was null");
this.suppressMarker = suppressMarker;
}
/**
* Get the number of threads to use when processing Rules.
*
* @return The number of threads.
*/
public int getThreads() {
return threads;
}
/**
* Set the number of threads to use when processing Rules.
*
* @param threads
* The number of threads.
*/
public void setThreads(int threads) {
this.threads = threads;
}
/**
* Get the ClassLoader being used by PMD when processing Rules.
*
* @return The ClassLoader being used
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Set the ClassLoader being used by PMD when processing Rules. Setting a
* value of <code>null</code> will cause the default ClassLoader to be used.
*
* @param classLoader
* The ClassLoader to use
*/
public void setClassLoader(ClassLoader classLoader) {
if (classLoader == null) {
this.classLoader = getClass().getClassLoader();
} else {
this.classLoader = classLoader;
}
}
/**
* Prepend the specified classpath like string to the current ClassLoader of
* the configuration. If no ClassLoader is currently configured, the
* ClassLoader used to load the {@link PMDConfiguration} class will be used
* as the parent ClassLoader of the created ClassLoader.
*
* <p>If the classpath String looks like a URL to a file (i.e. starts with
* <code>file://</code>) the file will be read with each line representing
* an entry on the classpath.</p>
*
* @param classpath
* The prepended classpath.
* @throws IOException
* if the given classpath is invalid (e.g. does not exist)
* @see PMDConfiguration#setClassLoader(ClassLoader)
* @see ClasspathClassLoader
*
* @deprecated Use {@link #prependAuxClasspath(String)}, which doesn't
* throw a checked {@link IOException}
*/
@Deprecated
public void prependClasspath(String classpath) throws IOException {
try {
prependAuxClasspath(classpath);
} catch (IllegalArgumentException e) {
throw new IOException(e);
}
}
/**
* Prepend the specified classpath like string to the current ClassLoader of
* the configuration. If no ClassLoader is currently configured, the
* ClassLoader used to load the {@link PMDConfiguration} class will be used
* as the parent ClassLoader of the created ClassLoader.
*
* <p>If the classpath String looks like a URL to a file (i.e. starts with
* <code>file://</code>) the file will be read with each line representing
* an entry on the classpath.</p>
*
* <p>You can specify multiple class paths separated by `:` on Unix-systems or `;` under Windows.
* See {@link File#pathSeparator}.
*
* @param classpath The prepended classpath.
*
* @throws IllegalArgumentException if the given classpath is invalid (e.g. does not exist)
* @see PMDConfiguration#setClassLoader(ClassLoader)
*/
public void prependAuxClasspath(String classpath) {
try {
if (classLoader == null) {
classLoader = PMDConfiguration.class.getClassLoader();
}
if (classpath != null) {
classLoader = new ClasspathClassLoader(classpath, classLoader);
}
} catch (IOException e) {
// Note: IOExceptions shouldn't appear anymore, they should already be converted
// to IllegalArgumentException in ClasspathClassLoader.
throw new IllegalArgumentException(e);
}
}
/**
* Returns the message reporter that is to be used while running
* the analysis.
*/
public @NonNull MessageReporter getReporter() {
return reporter;
}
/**
* Sets the message reporter that is to be used while running
* the analysis.
*
* @param reporter A non-null message reporter
*/
public void setReporter(@NonNull MessageReporter reporter) {
AssertionUtil.requireParamNotNull("reporter", reporter);
this.reporter = reporter;
}
/**
* Get the LanguageVersionDiscoverer, used to determine the LanguageVersion
* of a source file.
*
* @return The LanguageVersionDiscoverer.
*/
public LanguageVersionDiscoverer getLanguageVersionDiscoverer() {
return languageVersionDiscoverer;
}
/**
* Get the LanguageVersion specified by the force-language parameter. This overrides detection based on file
* extensions
*
* @return The LanguageVersion.
*/
public LanguageVersion getForceLanguageVersion() {
return forceLanguageVersion;
}
/**
* Is the force-language parameter set to anything?
*
* @return true if ${@link #getForceLanguageVersion()} is not null
*/
public boolean isForceLanguageVersion() {
return forceLanguageVersion != null;
}
/**
* Set the LanguageVersion specified by the force-language parameter. This overrides detection based on file
* extensions
*
* @param forceLanguageVersion the language version
*/
public void setForceLanguageVersion(@Nullable LanguageVersion forceLanguageVersion) {
if (forceLanguageVersion != null) {
checkLanguageIsRegistered(forceLanguageVersion.getLanguage());
}
this.forceLanguageVersion = forceLanguageVersion;
languageVersionDiscoverer.setForcedVersion(forceLanguageVersion);
}
/**
* Set the given LanguageVersion as the current default for it's Language.
*
* @param languageVersion
* the LanguageVersion
*/
public void setDefaultLanguageVersion(LanguageVersion languageVersion) {
Objects.requireNonNull(languageVersion);
languageVersionDiscoverer.setDefaultLanguageVersion(languageVersion);
getLanguageProperties(languageVersion.getLanguage()).setLanguageVersion(languageVersion.getVersion());
}
/**
* Set the given LanguageVersions as the current default for their
* Languages.
*
* @param languageVersions
* The LanguageVersions.
*/
public void setDefaultLanguageVersions(List<LanguageVersion> languageVersions) {
for (LanguageVersion languageVersion : languageVersions) {
setDefaultLanguageVersion(languageVersion);
}
}
/**
* Get the LanguageVersion of the source file with given name. This depends
* on the fileName extension, and the java version.
* <p>
* For compatibility with older code that does not always pass in a correct
* filename, unrecognized files are assumed to be java files.
* </p>
*
* @param fileName
* Name of the file, can be absolute, or simple.
* @return the LanguageVersion
*/
// FUTURE Delete this? I can't think of a good reason to keep it around.
// Failure to determine the LanguageVersion for a file should be a hard
// error, or simply cause the file to be skipped?
public @Nullable LanguageVersion getLanguageVersionOfFile(String fileName) {
LanguageVersion forcedVersion = getForceLanguageVersion();
if (forcedVersion != null) {
// use force language if given
return forcedVersion;
}
// otherwise determine by file extension
return languageVersionDiscoverer.getDefaultLanguageVersionForFile(fileName);
}
LanguageRegistry getLanguageRegistry() {
return langRegistry;
}
/**
* Get the comma separated list of RuleSet URIs.
*
* @return The RuleSet URIs.
*
* @deprecated Use {@link #getRuleSetPaths()}
*/
@Deprecated
@DeprecatedUntil700
public @Nullable String getRuleSets() {
if (ruleSets.isEmpty()) {
return null;
}
return String.join(",", ruleSets);
}
/**
* Returns the list of ruleset URIs.
*
* @see RuleSetLoader#loadFromResource(String)
*/
public @NonNull List<@NonNull String> getRuleSetPaths() {
return ruleSets;
}
/**
* Sets the list of ruleset paths to load when starting the analysis.
*
* @param ruleSetPaths A list of ruleset paths, understandable by {@link RuleSetLoader#loadFromResource(String)}.
*
* @throws NullPointerException If the parameter is null
*/
public void setRuleSets(@NonNull List<@NonNull String> ruleSetPaths) {
AssertionUtil.requireParamNotNull("ruleSetPaths", ruleSetPaths);
AssertionUtil.requireContainsNoNullValue("ruleSetPaths", ruleSetPaths);
this.ruleSets = new ArrayList<>(ruleSetPaths);
}
/**
* Add a new ruleset paths to load when starting the analysis.
* This list is initially empty.
*
* @param rulesetPath A ruleset path, understandable by {@link RuleSetLoader#loadFromResource(String)}.
*
* @throws NullPointerException If the parameter is null
*/
public void addRuleSet(@NonNull String rulesetPath) {
AssertionUtil.requireParamNotNull("rulesetPath", rulesetPath);
this.ruleSets.add(rulesetPath);
}
/**
* Set the comma separated list of RuleSet URIs.
*
* @param ruleSets the rulesets to set
*
* @deprecated Use {@link #setRuleSets(List)} or {@link #addRuleSet(String)}.
*/
@Deprecated
@DeprecatedUntil700
public void setRuleSets(@Nullable String ruleSets) {
if (ruleSets == null) {
this.ruleSets = new ArrayList<>();
} else {
this.ruleSets = new ArrayList<>(Arrays.asList(ruleSets.split(",")));
}
}
/**
* Get the minimum priority threshold when loading Rules from RuleSets.
*
* @return The minimum priority threshold.
*/
public RulePriority getMinimumPriority() {
return minimumPriority;
}
/**
* Set the minimum priority threshold when loading Rules from RuleSets.
*
* @param minimumPriority
* The minimum priority.
*/
public void setMinimumPriority(RulePriority minimumPriority) {
this.minimumPriority = minimumPriority;
}
/**
* Returns the list of input paths to explore. This is an
* unmodifiable list.
*/
public @NonNull List<Path> getInputPathList() {
return Collections.unmodifiableList(inputPaths);
}
/**
* Set the comma separated list of input paths to process for source files.
*
* @param inputPaths The comma separated list.
*
* @throws NullPointerException If the parameter is null
* @deprecated Use {@link #setInputPathList(List)} or {@link #addInputPath(Path)}
*/
@Deprecated
public void setInputPaths(String inputPaths) {
if (inputPaths.isEmpty()) {
return;
}
List<Path> paths = new ArrayList<>();
for (String s : inputPaths.split(",")) {
paths.add(Paths.get(s));
}
this.inputPaths = paths;
}
/**
* Set the input paths to the given list of paths.
*
* @throws NullPointerException If the parameter is null or contains a null value
*/
public void setInputPathList(final List<Path> inputPaths) {
AssertionUtil.requireContainsNoNullValue("input paths", inputPaths);
this.inputPaths = new ArrayList<>(inputPaths);
}
/**
* Add an input path. It is not split on commas.
*
* @throws NullPointerException If the parameter is null
*/
public void addInputPath(@NonNull Path inputPath) {
Objects.requireNonNull(inputPath);
this.inputPaths.add(inputPath);
}
/** Returns the path to the file list text file. */
public @Nullable Path getInputFile() {
return inputFilePath;
}
public @Nullable Path getIgnoreFile() {
return ignoreFilePath;
}
/**
* The input file path points to a single file, which contains a
* comma-separated list of source file names to process.
*
* @param inputFilePath path to the file
* @deprecated Use {@link #setInputFilePath(Path)}
*/
@Deprecated
public void setInputFilePath(String inputFilePath) {
this.inputFilePath = inputFilePath == null ? null : Paths.get(inputFilePath);
}
/**
* The input file path points to a single file, which contains a
* comma-separated list of source file names to process.
*
* @param inputFilePath path to the file
*/
public void setInputFilePath(Path inputFilePath) {
this.inputFilePath = inputFilePath;
}
/**
* The input file path points to a single file, which contains a
* comma-separated list of source file names to ignore.
*
* @param ignoreFilePath path to the file
* @deprecated Use {@link #setIgnoreFilePath(Path)}
*/
@Deprecated
public void setIgnoreFilePath(String ignoreFilePath) {
this.ignoreFilePath = ignoreFilePath == null ? null : Paths.get(ignoreFilePath);
}
/**
* The input file path points to a single file, which contains a
* comma-separated list of source file names to ignore.
*
* @param ignoreFilePath path to the file
*/
public void setIgnoreFilePath(Path ignoreFilePath) {
this.ignoreFilePath = ignoreFilePath;
}
/**
* Get the input URI to process for source code objects.
*
* @return URI
*/
public URI getUri() {
return inputUri;
}
/**
* Set the input URI to process for source code objects.
*
* @param inputUri a single URI
* @deprecated Use {@link PMDConfiguration#setInputUri(URI)}
*/
@Deprecated
public void setInputUri(String inputUri) {
this.inputUri = inputUri == null ? null : URI.create(inputUri);
}
/**
* Set the input URI to process for source code objects.
*
* @param inputUri a single URI
*/
public void setInputUri(URI inputUri) {
this.inputUri = inputUri;
}
/**
* Create a Renderer instance based upon the configured reporting options.
* No writer is created.
*
* @return renderer
*/
public Renderer createRenderer() {
return createRenderer(false);
}
/**
* Create a Renderer instance based upon the configured reporting options.
* If withReportWriter then we'll configure it with a writer for the
* reportFile specified.
*
* @param withReportWriter
* whether to configure a writer or not
* @return A Renderer instance.
*/
public Renderer createRenderer(boolean withReportWriter) {
Renderer renderer = RendererFactory.createRenderer(reportFormat, reportProperties);
renderer.setShowSuppressedViolations(showSuppressedViolations);
if (withReportWriter) {
renderer.setReportFile(reportFile == null ? null : reportFile.toString());
}
return renderer;
}
/**
* Get the report format.
*
* @return The report format.
*/
public String getReportFormat() {
return reportFormat;
}
/**
* Set the report format. This should be a name of a Renderer.
*
* @param reportFormat
* The report format.
*
* @see Renderer
*/
public void setReportFormat(String reportFormat) {
this.reportFormat = reportFormat;
}
/**
* Get the file to which the report should render.
*
* @return The file to which to render.
* @deprecated Use {@link #getReportFilePath()}
*/
@Deprecated
public String getReportFile() {
return reportFile == null ? null : reportFile.toString();
}
/**
* Get the file to which the report should render.
*
* @return The file to which to render.
*/
public Path getReportFilePath() {
return reportFile;
}
/**
* Set the file to which the report should render.
*
* @param reportFile the file to set
* @deprecated Use {@link #setReportFile(Path)}
*/
@Deprecated
public void setReportFile(String reportFile) {
this.reportFile = reportFile == null ? null : Paths.get(reportFile);
}
/**
* Set the file to which the report should render.
*
* @param reportFile the file to set
*/
public void setReportFile(Path reportFile) {
this.reportFile = reportFile;
}
/**
* Get whether the report should show suppressed violations.
*
* @return <code>true</code> if showing suppressed violations,
* <code>false</code> otherwise.
*/
public boolean isShowSuppressedViolations() {
return showSuppressedViolations;
}
/**
* Set whether the report should show suppressed violations.
*
* @param showSuppressedViolations
* <code>true</code> if showing suppressed violations,
* <code>false</code> otherwise.
*/
public void setShowSuppressedViolations(boolean showSuppressedViolations) {
this.showSuppressedViolations = showSuppressedViolations;
}
/**
* Get the Report properties. These are used to create the Renderer.
*
* @return The report properties.
*/
public Properties getReportProperties() {
return reportProperties;
}
/**
* Set the Report properties. These are used to create the Renderer.
*
* @param reportProperties
* The Report properties to set.
*/
public void setReportProperties(Properties reportProperties) {
this.reportProperties = reportProperties;
}
/**
* Whether PMD should exit with status 4 (the default behavior, true) if
* violations are found or just with 0 (to not break the build, e.g.).
*
* @return failOnViolation
*/
public boolean isFailOnViolation() {
return failOnViolation;
}
/**
* Sets whether PMD should exit with status 4 (the default behavior, true)
* if violations are found or just with 0 (to not break the build, e.g.).
*
* @param failOnViolation
* failOnViolation
*/
public void setFailOnViolation(boolean failOnViolation) {
this.failOnViolation = failOnViolation;
}
/**
* Checks if the rule set factory compatibility feature is enabled.
*
* @return true, if the rule set factory compatibility feature is enabled
*
* @see RuleSetLoader#enableCompatibility(boolean)
*/
public boolean isRuleSetFactoryCompatibilityEnabled() {
return ruleSetFactoryCompatibilityEnabled;
}
/**
* Sets the rule set factory compatibility feature enabled/disabled.
*
* @param ruleSetFactoryCompatibilityEnabled {@code true} if the feature should be enabled
*
* @see RuleSetLoader#enableCompatibility(boolean)
*/
public void setRuleSetFactoryCompatibilityEnabled(boolean ruleSetFactoryCompatibilityEnabled) {
this.ruleSetFactoryCompatibilityEnabled = ruleSetFactoryCompatibilityEnabled;
}
/**
* Retrieves the currently used analysis cache. Will never be null.
*
* @return The currently used analysis cache. Never null.
*/
public AnalysisCache getAnalysisCache() {
// Make sure we are not null
if (analysisCache == null || isIgnoreIncrementalAnalysis() && !(analysisCache instanceof NoopAnalysisCache)) {
// sets a noop cache
setAnalysisCache(new NoopAnalysisCache());
}
return analysisCache;
}
/**
* Sets the analysis cache to be used. Setting a
* value of {@code null} will cause a Noop AnalysisCache to be used.
* If incremental analysis was explicitly disabled ({@link #isIgnoreIncrementalAnalysis()}),
* then this method is a noop.
*
* @param cache The analysis cache to be used.
*/
public void setAnalysisCache(final AnalysisCache cache) {
// the doc says it's a noop if incremental analysis was disabled,
// but it's actually the getter that enforces that
this.analysisCache = cache == null ? new NoopAnalysisCache() : cache;
}
/**
* Sets the location of the analysis cache to be used. This will automatically configure
* and appropriate AnalysisCache implementation.
*
* @param cacheLocation The location of the analysis cache to be used.
*/
public void setAnalysisCacheLocation(final String cacheLocation) {
setAnalysisCache(cacheLocation == null
? new NoopAnalysisCache()
: new FileAnalysisCache(new File(cacheLocation)));
}
/**
* Sets whether the user has explicitly disabled incremental analysis or not.
* If so, incremental analysis is not used, and all suggestions to use it are
* disabled. The analysis cached location is ignored, even if it's specified.
*
* @param noCache Whether to ignore incremental analysis or not
*/
public void setIgnoreIncrementalAnalysis(boolean noCache) {
// see #getAnalysisCache for the implementation.
this.ignoreIncrementalAnalysis = noCache;
}
/**
* Returns whether incremental analysis was explicitly disabled by the user
* or not.
*
* @return {@code true} if incremental analysis is explicitly disabled
*/
public boolean isIgnoreIncrementalAnalysis() {
return ignoreIncrementalAnalysis;
}
/**
* Set the path used to shorten paths output in the report.
* The path does not need to exist. If it exists, it must point
* to a directory and not a file. See {@link #getRelativizeRoots()}
* for the interpretation.
*
* <p>If several paths are added, the shortest paths possible are
* built.
*
* @param path A path
*
* @throws IllegalArgumentException If the path points to a file, and not a directory
* @throws NullPointerException If the path is null
*/
public void addRelativizeRoot(Path path) {
// Note: the given path is not further modified or resolved. E.g. there is no special handling for symlinks.
// The goal is, that if the user inputs a path, PMD should output in terms of that path, not it's resolution.
this.relativizeRoots.add(Objects.requireNonNull(path));
if (Files.isRegularFile(path)) {
throw new IllegalArgumentException("Relativize root should be a directory: " + path);
}
}
/**
* Add several paths to shorten paths that are output in the report.
* See {@link #addRelativizeRoot(Path)}.
*
* @param paths A list of non-null paths
*
* @throws IllegalArgumentException If any path points to a file, and not a directory
* @throws NullPointerException If the list, or any path in the list is null
*/
public void addRelativizeRoots(List<Path> paths) {
for (Path path : paths) {
addRelativizeRoot(path);
}
}
/**
* Returns the paths used to shorten paths output in the report.
* <ul>
* <li>If the list is empty, then paths are not touched
* <li>If the list is non-empty, then source file paths are relativized with all the items in the list.
* The shortest of these relative paths is taken as the display name of the file.
* </ul>
*/
public List<Path> getRelativizeRoots() {
return Collections.unmodifiableList(relativizeRoots);
}
/**
* Returns a mutable bundle of language properties that are associated
* to the given language (always the same for a given language).
*
* @param language A language, which must be registered
*/
public @NonNull LanguagePropertyBundle getLanguageProperties(Language language) {
checkLanguageIsRegistered(language);
return langProperties.computeIfAbsent(language, Language::newPropertyBundle);
}
void checkLanguageIsRegistered(Language language) {
if (!langRegistry.getLanguages().contains(language)) {
throw new IllegalArgumentException(
"Language '" + language.getId() + "' is not registered in " + getLanguageRegistry());
}
}
}
| 31,224 | 33.125683 | 152 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import net.sourceforge.pmd.Report.GlobalReportBuilderListener;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.cache.AnalysisCacheListener;
import net.sourceforge.pmd.cache.NoopAnalysisCache;
import net.sourceforge.pmd.internal.LogMessages;
import net.sourceforge.pmd.internal.util.ClasspathClassLoader;
import net.sourceforge.pmd.internal.util.FileCollectionUtil;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.JvmLanguagePropertyBundle;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageProcessor.AnalysisTask;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry.LanguageTerminationException;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.document.FileCollector;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.reporting.ConfigurableFileNameRenderer;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
import net.sourceforge.pmd.reporting.ListenerInitializer;
import net.sourceforge.pmd.reporting.ReportStats;
import net.sourceforge.pmd.reporting.ReportStatsListener;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.StringUtil;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Main programmatic API of PMD. This is not a CLI entry point, see module
* {@code pmd-cli} for that.
*
* <h3>Usage overview</h3>
*
* Create and configure a {@link PMDConfiguration},
* then use {@link #create(PMDConfiguration)} to obtain an instance.
* You can perform additional configuration on the instance, e.g. adding
* files to process, or additional rulesets and renderers. Then, call
* {@link #performAnalysis()} or one of the related terminal methods.
*
* <h3>Simple example</h3>
*
* <pre>{@code
* PMDConfiguration config = new PMDConfiguration();
* config.setDefaultLanguageVersion(LanguageRegistry.findLanguageByTerseName("java").getVersion("11"));
* config.setInputPaths("src/main/java");
* config.prependClasspath("target/classes");
* config.setMinimumPriority(RulePriority.HIGH);
* config.addRuleSet("rulesets/java/quickstart.xml");
* config.setReportFormat("xml");
* config.setReportFile("target/pmd-report.xml");
*
* try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
* // note: don't use `config` once a PmdAnalysis has been created.
* // optional: add more rulesets
* pmd.addRuleSet(pmd.newRuleSetLoader().loadFromResource("custom-ruleset.xml"));
* // optional: add more files
* pmd.files().addFile(Paths.get("src", "main", "more-java", "ExtraSource.java"));
* // optional: add more renderers
* pmd.addRenderer(renderer);
*
* pmd.performAnalysis();
* }
* }</pre>
*
* <h3>Rendering reports</h3>
*
* If you just want to render a report to a file like with the CLI, you
* should use a {@link Renderer}. You can add a custom one with {@link PmdAnalysis#addRenderer(Renderer)}.
* You can add one of the builtin renderers from its ID using {@link PMDConfiguration#setReportFormat(String)}.
*
* <h3>Reports and events</h3>
*
* <p>If you want strongly typed access to violations and other analysis events,
* you can implement and register a {@link GlobalAnalysisListener} with {@link #addListener(GlobalAnalysisListener)}.
* The listener needs to provide a new {@link FileAnalysisListener} for each file,
* which will receive events from the analysis. The listener's lifecycle
* happens only once the analysis is started ({@link #performAnalysis()}).
*
* <p>If you want access to all events once the analysis ends instead of processing
* events as they go, you can obtain a {@link Report} instance from {@link #performAnalysisAndCollectReport()},
* or use {@link Report.GlobalReportBuilderListener} manually. Keep in
* mind collecting a report is less memory-efficient than using a listener.
*
* <p>If you want to process events in batches, one per file, you can
* use {@link Report.ReportBuilderListener}. to implement {@link GlobalAnalysisListener#startFileAnalysis(TextFile)}.
*
* <p>Listeners can be used alongside renderers.
*
* <h3>Specifying the Java classpath</h3>
*
* Java rules work better if you specify the path to the compiled classes
* of the analysed sources. See {@link PMDConfiguration#prependAuxClasspath(String)}.
*
* <h3>Customizing message output</h3>
*
* <p>The analysis reports messages like meta warnings and errors through a
* {@link MessageReporter} instance. To override how those messages are output,
* you can set it in {@link PMDConfiguration#setReporter(MessageReporter)}.
* By default, it forwards messages to SLF4J.
*
*/
public final class PmdAnalysis implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(PmdAnalysis.class);
private final FileCollector collector;
private final List<Renderer> renderers = new ArrayList<>();
private final List<GlobalAnalysisListener> listeners = new ArrayList<>();
private final List<RuleSet> ruleSets = new ArrayList<>();
private final PMDConfiguration configuration;
private final MessageReporter reporter;
private final Map<Language, LanguagePropertyBundle> langProperties = new HashMap<>();
private boolean closed;
private final ConfigurableFileNameRenderer fileNameRenderer = new ConfigurableFileNameRenderer();
/**
* Constructs a new instance. The files paths (input files, filelist,
* exclude list, etc) given in the configuration are collected into
* the file collector ({@link #files()}), but more can be added
* programmatically using the file collector.
*/
private PmdAnalysis(PMDConfiguration config) {
this.configuration = config;
this.reporter = config.getReporter();
this.collector = FileCollector.newCollector(
config.getLanguageVersionDiscoverer(),
reporter
);
}
/**
* Constructs a new instance from a configuration.
*
* <ul>
* <li> The files paths (input files, filelist,
* exclude list, etc) are explored and the files to analyse are
* collected into the file collector ({@link #files()}).
* More can be added programmatically using the file collector.
* <li>The rulesets given in the configuration are loaded ({@link PMDConfiguration#getRuleSets()})
* <li>A renderer corresponding to the parameters of the configuration
* is created and added (but not started).
* </ul>
*/
public static PmdAnalysis create(PMDConfiguration config) {
PmdAnalysis pmd = new PmdAnalysis(config);
// note: do not filter files by language
// they could be ignored later. The problem is if you call
// addRuleSet later, then you could be enabling new languages
// So the files should not be pruned in advance
FileCollectionUtil.collectFiles(config, pmd.files());
if (config.getReportFormat() != null) {
Renderer renderer = config.createRenderer(true);
pmd.addRenderer(renderer);
}
if (!config.getRuleSetPaths().isEmpty()) {
final RuleSetLoader ruleSetLoader = pmd.newRuleSetLoader();
final List<RuleSet> ruleSets = ruleSetLoader.loadRuleSetsWithoutException(config.getRuleSetPaths());
pmd.addRuleSets(ruleSets);
}
for (Language language : config.getLanguageRegistry()) {
LanguagePropertyBundle props = config.getLanguageProperties(language);
assert props.getLanguage().equals(language);
pmd.langProperties.put(language, props);
LanguageVersion forcedVersion = config.getForceLanguageVersion();
if (forcedVersion != null && forcedVersion.getLanguage().equals(language)) {
props.setLanguageVersion(forcedVersion.getVersion());
}
// TODO replace those with actual language properties when the
// CLI syntax is implemented.
props.setProperty(LanguagePropertyBundle.SUPPRESS_MARKER, config.getSuppressMarker());
if (props instanceof JvmLanguagePropertyBundle) {
((JvmLanguagePropertyBundle) props).setClassLoader(config.getClassLoader());
}
}
for (Path path : config.getRelativizeRoots()) {
pmd.fileNameRenderer.relativizeWith(path);
}
return pmd;
}
// test only
List<RuleSet> rulesets() {
return ruleSets;
}
// test only
List<Renderer> renderers() {
return renderers;
}
/**
* Returns the file collector for the analysed sources.
*/
public FileCollector files() {
return collector; // todo user can close collector programmatically
}
/**
* Returns a new ruleset loader, which can be used to create new
* rulesets (add them then with {@link #addRuleSet(RuleSet)}).
*
* <pre>{@code
* try (PmdAnalysis pmd = create(config)) {
* pmd.addRuleSet(pmd.newRuleSetLoader().loadFromResource("custom-ruleset.xml"));
* }
* }</pre>
*/
public RuleSetLoader newRuleSetLoader() {
return RuleSetLoader.fromPmdConfig(configuration);
}
/**
* Add a new renderer. The given renderer must not already be started,
* it will be started by {@link #performAnalysis()}.
*
* @throws NullPointerException If the parameter is null
*/
public void addRenderer(Renderer renderer) {
AssertionUtil.requireParamNotNull("renderer", renderer);
this.renderers.add(renderer);
}
/**
* Add several renderers at once.
*
* @throws NullPointerException If the parameter is null, or any of its items is null.
*/
public void addRenderers(Collection<Renderer> renderers) {
renderers.forEach(this::addRenderer);
}
/**
* Add a new listener. As per the contract of {@link GlobalAnalysisListener},
* this object must be ready for interaction. However, nothing will
* be done with the listener until {@link #performAnalysis()} is called.
* The listener will be closed by {@link #performAnalysis()}, or
* {@link #close()}, whichever happens first.
*
* @throws NullPointerException If the parameter is null
*/
public void addListener(GlobalAnalysisListener listener) {
AssertionUtil.requireParamNotNull("listener", listener);
this.listeners.add(listener);
}
/**
* Add several listeners at once.
*
* @throws NullPointerException If the parameter is null, or any of its items is null.
* @see #addListener(GlobalAnalysisListener)
*/
public void addListeners(Collection<? extends GlobalAnalysisListener> listeners) {
listeners.forEach(this::addListener);
}
/**
* Add a new ruleset.
*
* @throws NullPointerException If the parameter is null
*/
public void addRuleSet(RuleSet ruleSet) {
AssertionUtil.requireParamNotNull("rule set", ruleSet);
this.ruleSets.add(ruleSet);
}
/**
* Add several rulesets at once.
*
* @throws NullPointerException If the parameter is null, or any of its items is null.
*/
public void addRuleSets(Collection<RuleSet> ruleSets) {
ruleSets.forEach(this::addRuleSet);
}
/**
* Returns an unmodifiable view of the ruleset list. That will be
* processed.
*/
public List<RuleSet> getRulesets() {
return Collections.unmodifiableList(ruleSets);
}
/**
* Returns a mutable bundle of language properties that are associated
* to the given language (always the same for a given language).
*
* @param language A language, which must be registered
*/
public LanguagePropertyBundle getLanguageProperties(Language language) {
configuration.checkLanguageIsRegistered(language);
return langProperties.computeIfAbsent(language, Language::newPropertyBundle);
}
public ConfigurableFileNameRenderer fileNameRenderer() {
return fileNameRenderer;
}
/**
* Run PMD with the current state of this instance. This will start
* and finish the registered renderers, and close all
* {@linkplain #addListener(GlobalAnalysisListener) registered listeners}.
* All files collected in the {@linkplain #files() file collector} are
* processed. This does not return a report, as the analysis results
* are consumed by {@link GlobalAnalysisListener} instances (of which
* Renderers are a special case). Note that this does
* not throw, errors are instead accumulated into a {@link MessageReporter}.
*/
public void performAnalysis() {
performAnalysisImpl(Collections.emptyList());
}
/**
* Run PMD with the current state of this instance. This will start
* and finish the registered renderers. All files collected in the
* {@linkplain #files() file collector} are processed. Returns the
* output report. Note that this does not throw, errors are instead
* accumulated into a {@link MessageReporter}.
*/
public Report performAnalysisAndCollectReport() {
try (GlobalReportBuilderListener reportBuilder = new GlobalReportBuilderListener()) {
performAnalysisImpl(listOf(reportBuilder)); // closes the report builder
return reportBuilder.getResultImpl();
}
}
void performAnalysisImpl(List<? extends GlobalReportBuilderListener> extraListeners) {
try (FileCollector files = collector) {
files.filterLanguages(getApplicableLanguages(false));
performAnalysisImpl(extraListeners, files.getCollectedFiles());
}
}
void performAnalysisImpl(List<? extends GlobalReportBuilderListener> extraListeners, List<TextFile> textFiles) {
RuleSets rulesets = new RuleSets(this.ruleSets);
GlobalAnalysisListener listener;
try {
@SuppressWarnings("PMD.CloseResource")
AnalysisCacheListener cacheListener = new AnalysisCacheListener(configuration.getAnalysisCache(),
rulesets,
configuration.getClassLoader(),
textFiles);
listener = GlobalAnalysisListener.tee(listOf(createComposedRendererListener(renderers),
GlobalAnalysisListener.tee(listeners),
GlobalAnalysisListener.tee(extraListeners),
cacheListener));
// Initialize listeners
try (ListenerInitializer initializer = listener.initializer()) {
initializer.setNumberOfFilesToAnalyze(textFiles.size());
initializer.setFileNameRenderer(fileNameRenderer());
}
} catch (Exception e) {
reporter.errorEx("Exception while initializing analysis listeners", e);
throw new RuntimeException("Exception while initializing analysis listeners", e);
}
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.FILE_PROCESSING)) {
for (final Rule rule : removeBrokenRules(rulesets)) {
// todo Just like we throw for invalid properties, "broken rules"
// shouldn't be a "config error". This is the only instance of
// config errors...
// see https://github.com/pmd/pmd/issues/3901
listener.onConfigError(new Report.ConfigurationError(rule, rule.dysfunctionReason()));
}
encourageToUseIncrementalAnalysis(configuration);
try (LanguageProcessorRegistry lpRegistry = LanguageProcessorRegistry.create(
// only start the applicable languages (and dependencies)
new LanguageRegistry(getApplicableLanguages(true)),
langProperties,
reporter
)) {
// Note the analysis task is shared: all processors see
// the same file list, which may contain files for other
// languages.
AnalysisTask analysisTask = new AnalysisTask(
rulesets,
textFiles,
listener,
configuration.getThreads(),
configuration.getAnalysisCache(),
reporter,
lpRegistry
);
List<AutoCloseable> analyses = new ArrayList<>();
try {
for (Language lang : lpRegistry.getLanguages()) {
analyses.add(lpRegistry.getProcessor(lang).launchAnalysis(analysisTask));
}
} finally {
Exception e = IOUtil.closeAll(analyses);
if (e != null) {
reporter.errorEx("Error while joining analysis", e);
}
}
} catch (LanguageTerminationException e) {
reporter.errorEx("Error while closing language processors", e);
}
} finally {
try {
listener.close();
} catch (Exception e) {
reporter.errorEx("Exception while closing analysis listeners", e);
// todo better exception
throw new RuntimeException("Exception while closing analysis listeners", e);
}
}
}
private GlobalAnalysisListener createComposedRendererListener(List<Renderer> renderers) throws Exception {
if (renderers.isEmpty()) {
return GlobalAnalysisListener.noop();
}
List<GlobalAnalysisListener> rendererListeners = new ArrayList<>(renderers.size());
for (Renderer renderer : renderers) {
try {
@SuppressWarnings("PMD.CloseResource")
GlobalAnalysisListener listener =
Objects.requireNonNull(renderer.newListener(), "Renderer should provide non-null listener");
rendererListeners.add(listener);
} catch (Exception ioe) {
// close listeners so far, throw their close exception or the ioe
IOUtil.ensureClosed(rendererListeners, ioe);
throw AssertionUtil.shouldNotReachHere("ensureClosed should have thrown");
}
}
return GlobalAnalysisListener.tee(rendererListeners);
}
private Set<Language> getApplicableLanguages(boolean quiet) {
Set<Language> languages = new HashSet<>();
LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer();
for (RuleSet ruleSet : ruleSets) {
for (Rule rule : ruleSet.getRules()) {
Language ruleLanguage = rule.getLanguage();
Objects.requireNonNull(ruleLanguage, "Rule has no language " + rule);
if (!languages.contains(ruleLanguage)) {
LanguageVersion version = discoverer.getDefaultLanguageVersion(ruleLanguage);
if (RuleSet.applies(rule, version)) {
configuration.checkLanguageIsRegistered(ruleLanguage);
languages.add(ruleLanguage);
if (!quiet) {
LOG.trace("Using {} version ''{}''", version.getLanguage().getName(), version.getTerseName());
}
}
}
}
}
// collect all dependencies, they shouldn't be filtered out
LanguageRegistry reg = configuration.getLanguageRegistry();
boolean changed;
do {
changed = false;
for (Language lang : new HashSet<>(languages)) {
for (String depId : lang.getDependencies()) {
Language depLang = reg.getLanguageById(depId);
if (depLang == null) {
// todo maybe report all then throw
throw new IllegalStateException(
"Language " + lang.getId() + " has unsatisfied dependencies: "
+ depId + " is not found in " + reg
);
}
changed |= languages.add(depLang);
}
}
} while (changed);
return languages;
}
/**
* Remove and return the misconfigured rules from the rulesets and log them
* for good measure.
*/
private Set<Rule> removeBrokenRules(final RuleSets ruleSets) {
final Set<Rule> brokenRules = new HashSet<>();
ruleSets.removeDysfunctionalRules(brokenRules);
for (final Rule rule : brokenRules) {
reporter.warn("Removed misconfigured rule: {0} cause: {1}",
rule.getName(), rule.dysfunctionReason());
}
return brokenRules;
}
public MessageReporter getReporter() {
return reporter;
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
collector.close();
// close listeners if analysis is not run.
IOUtil.closeAll(listeners);
/*
* Make sure it's our own classloader before attempting to close it....
* Maven + Jacoco provide us with a cloaseable classloader that if closed
* will throw a ClassNotFoundException.
*/
if (configuration.getClassLoader() instanceof ClasspathClassLoader) {
IOUtil.tryCloseClassLoader(configuration.getClassLoader());
}
}
public ReportStats runAndReturnStats() {
if (getRulesets().isEmpty()) {
return ReportStats.empty();
}
@SuppressWarnings("PMD.CloseResource")
ReportStatsListener listener = new ReportStatsListener();
addListener(listener);
try {
performAnalysis();
} catch (Exception e) {
getReporter().errorEx("Exception during processing", e);
ReportStats stats = listener.getResult();
printErrorDetected(1 + stats.getNumErrors());
return stats; // should have been closed
}
ReportStats stats = listener.getResult();
if (stats.getNumErrors() > 0) {
printErrorDetected(stats.getNumErrors());
}
return stats;
}
static void printErrorDetected(MessageReporter reporter, int errors) {
String msg = LogMessages.errorDetectedMessage(errors, "PMD");
// note: using error level here increments the error count of the reporter,
// which we don't want.
reporter.info(StringUtil.quoteMessageFormat(msg));
}
void printErrorDetected(int errors) {
printErrorDetected(getReporter(), errors);
}
private static void encourageToUseIncrementalAnalysis(final PMDConfiguration configuration) {
final MessageReporter reporter = configuration.getReporter();
if (!configuration.isIgnoreIncrementalAnalysis()
&& configuration.getAnalysisCache() instanceof NoopAnalysisCache
&& reporter.isLoggable(Level.WARN)) {
final String version =
PMDVersion.isUnknown() || PMDVersion.isSnapshot() ? "latest" : "pmd-doc-" + PMDVersion.VERSION;
reporter.warn("This analysis could be faster, please consider using Incremental Analysis: "
+ "https://docs.pmd-code.org/{0}/pmd_userdocs_incremental_analysis.html", version);
}
}
}
| 24,895 | 39.547231 | 122 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetLoader.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Configurable object to load rulesets from XML resources.
* This can be configured using a fluent API, see eg {@link #warnDeprecated(boolean)}.
* To create a new ruleset, use {@link #loadFromResource(String)}
* or some such overload.
*/
public final class RuleSetLoader {
private static final Logger LOG = LoggerFactory.getLogger(RuleSetLoader.class);
private LanguageRegistry languageRegistry = LanguageRegistry.PMD;
private ResourceLoader resourceLoader = new ResourceLoader(RuleSetLoader.class.getClassLoader());
private RulePriority minimumPriority = RulePriority.LOW;
private boolean warnDeprecated = true;
private @NonNull RuleSetFactoryCompatibility compatFilter = RuleSetFactoryCompatibility.DEFAULT;
private boolean includeDeprecatedRuleReferences = false;
private @NonNull MessageReporter reporter = MessageReporter.quiet();
/**
* Create a new RuleSetLoader with a default configuration.
* The defaults are described on each configuration method of this class.
*/
public RuleSetLoader() { // NOPMD UnnecessaryConstructor
// default
}
RuleSetLoader withReporter(@NonNull MessageReporter reporter) {
this.reporter = Objects.requireNonNull(reporter);
return this;
}
/**
* Specify that the given classloader should be used to resolve
* paths to external ruleset references. The default uses PMD's
* own classpath.
*/
public RuleSetLoader loadResourcesWith(ClassLoader classLoader) {
this.resourceLoader = new ResourceLoader(classLoader);
return this;
}
// internal
RuleSetLoader loadResourcesWith(ResourceLoader loader) {
this.resourceLoader = loader;
return this;
}
public RuleSetLoader withLanguages(LanguageRegistry languageRegistry) {
this.languageRegistry = languageRegistry;
return this;
}
/**
* Filter loaded rules to only those that match or are above
* the given priority. The default is {@link RulePriority#LOW},
* ie, no filtering occurs.
*
* @return This instance, modified
*/
public RuleSetLoader filterAbovePriority(RulePriority minimumPriority) {
this.minimumPriority = minimumPriority;
return this;
}
/**
* Log a warning when referencing a deprecated rule.
* This is enabled by default.
*
* @return This instance, modified
*/
public RuleSetLoader warnDeprecated(boolean warn) {
this.warnDeprecated = warn;
return this;
}
/**
* Enable translating old rule references to newer ones, if they have
* been moved or renamed. This is enabled by default, if disabled,
* unresolved references will not be translated and will produce an
* error.
*
* @return This instance, modified
*/
public RuleSetLoader enableCompatibility(boolean enable) {
return setCompatibility(enable ? RuleSetFactoryCompatibility.DEFAULT
: RuleSetFactoryCompatibility.EMPTY);
}
// test only
RuleSetLoader setCompatibility(@NonNull RuleSetFactoryCompatibility filter) {
this.compatFilter = filter;
return this;
}
/**
* Follow deprecated rule references. By default this is off,
* and those references will be ignored (with a warning depending
* on {@link #enableCompatibility(boolean)}).
*
* @return This instance, modified
*/
public RuleSetLoader includeDeprecatedRuleReferences(boolean enable) {
this.includeDeprecatedRuleReferences = enable;
return this;
}
/**
* Create a new rule set factory, if you have to (that class is deprecated).
* That factory will use the configuration that was set using the setters of this.
*
* @deprecated {@link RuleSetFactory} is deprecated, replace its usages
* with usages of this class, or of static factory methods of {@link RuleSet}
*/
@Deprecated
public RuleSetFactory toFactory() {
return new RuleSetFactory(
this.resourceLoader,
this.languageRegistry,
this.minimumPriority,
this.warnDeprecated,
this.compatFilter,
this.includeDeprecatedRuleReferences,
this.reporter
);
}
private @Nullable MessageReporter filteredReporter() {
return warnDeprecated ? reporter : null;
}
/**
* Parses and returns a ruleset from its location. The location may
* be a file system path, or a resource path (see {@link #loadResourcesWith(ClassLoader)}).
*
* @param rulesetPath A reference to a single ruleset
*
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax, or resource not found)
*/
public RuleSet loadFromResource(String rulesetPath) {
return loadFromResource(new RuleSetReferenceId(rulesetPath, null, filteredReporter()));
}
/**
* Parses and returns a ruleset from string content.
*
* @param filename The symbolic "file name", for error messages.
* @param rulesetXmlContent Xml file contents
*
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax)
*/
public RuleSet loadFromString(String filename, final String rulesetXmlContent) {
return loadFromResource(new RuleSetReferenceId(filename, null, filteredReporter()) {
@Override
public InputStream getInputStream(ResourceLoader rl) {
return new ByteArrayInputStream(rulesetXmlContent.getBytes(StandardCharsets.UTF_8));
}
});
}
/**
* Parses several resources into a list of rulesets.
*
* @param paths Paths
*
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax, or resource not found),
* for any of the parameters
* @throws NullPointerException If the parameter, or any component is null
*/
public List<RuleSet> loadFromResources(Collection<String> paths) {
List<RuleSet> ruleSets = new ArrayList<>(paths.size());
for (String path : paths) {
ruleSets.add(loadFromResource(path));
}
return ruleSets;
}
/**
* Loads a list of rulesets, if any has an error, report it on the contextual
* error reporter instead of aborting, and continue loading the rest.
*
* <p>Internal API: might be published later, or maybe in PMD 7 this
* will be the default behaviour of every method of this class.
*/
@InternalApi
public List<RuleSet> loadRuleSetsWithoutException(List<String> rulesetPaths) {
List<RuleSet> ruleSets = new ArrayList<>(rulesetPaths.size());
boolean anyRules = false;
boolean error = false;
for (String path : rulesetPaths) {
try {
RuleSet ruleset = this.loadFromResource(path);
anyRules |= !ruleset.getRules().isEmpty();
printRulesInDebug(path, ruleset);
ruleSets.add(ruleset);
} catch (RuleSetLoadException e) {
error = true;
reporter.error(e);
}
}
if (!anyRules && !error) {
reporter.warn("No rules found. Maybe you misspelled a rule name? ({0})",
StringUtils.join(rulesetPaths, ','));
}
return ruleSets;
}
void printRulesInDebug(String path, RuleSet ruleset) {
if (LOG.isDebugEnabled()) {
LOG.debug("Rules loaded from {}:", path);
for (Rule rule : ruleset.getRules()) {
LOG.debug("- {} ({})", rule.getName(), rule.getLanguage().getName());
}
}
if (ruleset.getRules().isEmpty()) {
reporter.warn("No rules found in ruleset {0}", path);
}
}
/**
* Parses several resources into a list of rulesets.
*
* @param first First path
* @param rest Paths
*
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax, or resource not found),
* for any of the parameters
* @throws NullPointerException If the parameter, or any component is null
*/
public List<RuleSet> loadFromResources(String first, String... rest) {
return loadFromResources(CollectionUtil.listOf(first, rest));
}
// package private
RuleSet loadFromResource(RuleSetReferenceId ruleSetReferenceId) {
try {
return toFactory().createRuleSet(ruleSetReferenceId);
} catch (RuleSetLoadException e) {
throw e;
} catch (Exception e) {
throw new RuleSetLoadException(ruleSetReferenceId, e);
}
}
/**
* Configure a new ruleset factory builder according to the parameters
* of the given PMD configuration.
*/
public static RuleSetLoader fromPmdConfig(PMDConfiguration configuration) {
return new RuleSetLoader().filterAbovePriority(configuration.getMinimumPriority())
.enableCompatibility(configuration.isRuleSetFactoryCompatibilityEnabled())
.withLanguages(configuration.getLanguageRegistry())
.withReporter(configuration.getReporter());
}
/**
* Returns an Iterator of RuleSet objects loaded from descriptions from the
* "categories.properties" resource for each language. This
* uses the classpath of the resource loader ({@link #loadResourcesWith(ClassLoader)}).
*
* @return A list of all category rulesets
*
* @throws RuleSetLoadException If a standard ruleset cannot be loaded.
* This is a corner case, that probably should not be caught by clients.
* The standard rulesets are well-formed, at least in stock PMD distributions.
*
*/
public List<RuleSet> getStandardRuleSets() {
String rulesetsProperties;
List<String> ruleSetReferenceIds = new ArrayList<>();
for (Language language : languageRegistry.getLanguages()) {
Properties props = new Properties();
rulesetsProperties = "category/" + language.getTerseName() + "/categories.properties";
try (InputStream inputStream = resourceLoader.loadClassPathResourceAsStreamOrThrow(rulesetsProperties)) {
props.load(inputStream);
String rulesetFilenames = props.getProperty("rulesets.filenames");
// some languages might not have any rules and this property either doesn't exist or is empty
if (StringUtils.isNotBlank(rulesetFilenames)) {
ruleSetReferenceIds.addAll(Arrays.asList(rulesetFilenames.split(",")));
}
} catch (IOException e) {
throw new RuntimeException("Couldn't find " + rulesetsProperties
+ "; please ensure that the directory is on the classpath. The current classpath is: "
+ System.getProperty("java.class.path"));
}
}
List<RuleSet> ruleSets = new ArrayList<>();
for (String id : ruleSetReferenceIds) {
ruleSets.add(loadFromResource(id)); // may throw
}
return ruleSets;
}
}
| 12,355 | 36.90184 | 117 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/Report.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static java.util.Collections.synchronizedList;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.renderers.AbstractAccumulatingRenderer;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
import net.sourceforge.pmd.util.BaseResultProducingCloseable;
/**
* A {@link Report} collects all informations during a PMD execution. This
* includes violations, suppressed violations, metrics, error during processing
* and configuration errors.
*
* <p>A report may be created by a {@link GlobalReportBuilderListener} that you
* use as the {@linkplain GlobalAnalysisListener} in {@link PmdAnalysis#performAnalysisAndCollectReport() PMD's entry point}.
* You can also create one manually with {@link #buildReport(Consumer)}.
*
* <p>For special use cases, like filtering the report after PMD analysis and
* before rendering the report, some transformation operations are provided:
* <ul>
* <li>{@link #filterViolations(Predicate)}</li>
* <li>{@link #union(Report)}</li>
* </ul>
* These methods create a new {@link Report} rather than modifying their receiver.
* </p>
*/
public final class Report {
// todo move to package reporting
private final List<RuleViolation> violations = synchronizedList(new ArrayList<>());
private final List<SuppressedViolation> suppressedRuleViolations = synchronizedList(new ArrayList<>());
private final List<ProcessingError> errors = synchronizedList(new ArrayList<>());
private final List<ConfigurationError> configErrors = synchronizedList(new ArrayList<>());
@DeprecatedUntil700
@InternalApi
public Report() { // NOPMD - UnnecessaryConstructor
// TODO: should be package-private, you have to use a listener to build a report.
}
/**
* Represents a configuration error.
*/
public static class ConfigurationError {
private final Rule rule;
private final String issue;
/**
* Creates a new configuration error for a specific rule.
*
* @param theRule
* the rule which is configured wrongly
* @param theIssue
* the reason, why the configuration is wrong
*/
public ConfigurationError(Rule theRule, String theIssue) {
rule = theRule;
issue = theIssue;
}
/**
* Gets the wrongly configured rule
*
* @return the wrongly configured rule
*/
public Rule rule() {
return rule;
}
/**
* Gets the reason for the configuration error.
*
* @return the issue
*/
public String issue() {
return issue;
}
}
/**
* Represents a processing error, such as a parse error.
*/
public static class ProcessingError {
private final Throwable error;
private final FileId file;
/**
* Creates a new processing error
*
* @param error
* the error
* @param file
* the file during which the error occurred
*/
public ProcessingError(Throwable error, FileId file) {
this.error = error;
this.file = file;
}
public String getMsg() {
return error.getClass().getSimpleName() + ": " + error.getMessage();
}
public String getDetail() {
try (StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter)) {
error.printStackTrace(writer);
return stringWriter.toString();
} catch (IOException e) {
// IOException on close - should never happen when using StringWriter
throw new RuntimeException(e);
}
}
public FileId getFileId() {
return file;
}
public Throwable getError() {
return error;
}
}
/**
* Represents a violation, that has been suppressed.
*/
public static class SuppressedViolation {
private final RuleViolation rv;
private final String userMessage;
private final ViolationSuppressor suppressor;
/**
* Creates a suppressed violation.
*
* @param rv The violation, that has been suppressed
* @param suppressor The suppressor which suppressed the violation
* @param userMessage Any relevant info given by the suppressor
*/
public SuppressedViolation(RuleViolation rv, ViolationSuppressor suppressor, String userMessage) {
this.suppressor = suppressor;
this.rv = rv;
this.userMessage = userMessage;
}
public ViolationSuppressor getSuppressor() {
return suppressor;
}
public RuleViolation getRuleViolation() {
return this.rv;
}
public String getUserMessage() {
return userMessage;
}
}
/**
* Adds a new rule violation to the report and notify the listeners.
*
* @param violation the violation to add
*
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700
@Deprecated
@InternalApi
public void addRuleViolation(RuleViolation violation) {
synchronized (violations) {
// note that this binary search is inefficient as we usually
// report violations file by file.
int index = Collections.binarySearch(violations, violation, RuleViolation.DEFAULT_COMPARATOR);
violations.add(index < 0 ? -index - 1 : index, violation);
}
}
/**
* Adds a new suppressed violation.
*/
private void addSuppressedViolation(SuppressedViolation sv) {
suppressedRuleViolations.add(sv);
}
/**
* Adds a new configuration error to the report.
*
* @param error the error to add
*
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700
@Deprecated
@InternalApi
public void addConfigError(ConfigurationError error) {
configErrors.add(error);
}
/**
* Adds a new processing error to the report.
*
* @param error
* the error to add
* @deprecated PMD's way of creating a report is internal and may be changed in pmd 7.
*/
@DeprecatedUntil700
@Deprecated
@InternalApi
public void addError(ProcessingError error) {
errors.add(error);
}
/**
* Merges the given report into this report. This might be necessary, if a
* summary over all violations is needed as PMD creates one report per file
* by default.
*
* <p>This is synchronized on an internal lock (note that other mutation
* operations are not synchronized, todo for pmd 7).
*
* @param r the report to be merged into this.
*
* @see AbstractAccumulatingRenderer
*
* @deprecated Convert Renderer to use the reports.
*/
@Deprecated
public void merge(Report r) {
errors.addAll(r.errors);
configErrors.addAll(r.configErrors);
suppressedRuleViolations.addAll(r.suppressedRuleViolations);
for (RuleViolation violation : r.getViolations()) {
addRuleViolation(violation);
}
}
/**
* Returns an unmodifiable list of violations that were suppressed.
*/
public List<SuppressedViolation> getSuppressedViolations() {
return Collections.unmodifiableList(suppressedRuleViolations);
}
/**
* Returns an unmodifiable list of violations that have been
* recorded until now. None of those violations were suppressed.
*
* <p>The violations list is sorted with {@link RuleViolation#DEFAULT_COMPARATOR}.
*/
public List<RuleViolation> getViolations() {
return Collections.unmodifiableList(violations);
}
/**
* Returns an unmodifiable list of processing errors that have been
* recorded until now.
*/
public List<ProcessingError> getProcessingErrors() {
return Collections.unmodifiableList(errors);
}
/**
* Returns an unmodifiable list of configuration errors that have
* been recorded until now.
*/
public List<ConfigurationError> getConfigurationErrors() {
return Collections.unmodifiableList(configErrors);
}
/**
* Create a report by making side effects on a {@link FileAnalysisListener}.
* This wraps a {@link ReportBuilderListener}.
*/
public static Report buildReport(Consumer<? super FileAnalysisListener> lambda) {
return BaseResultProducingCloseable.using(new ReportBuilderListener(), lambda);
}
/**
* A {@link FileAnalysisListener} that accumulates events into a
* {@link Report}.
*/
public static final class ReportBuilderListener extends BaseResultProducingCloseable<Report> implements FileAnalysisListener {
private final Report report;
public ReportBuilderListener() {
this(new Report());
}
ReportBuilderListener(Report report) {
this.report = report;
}
@Override
protected Report getResultImpl() {
return report;
}
@Override
public void onRuleViolation(RuleViolation violation) {
report.addRuleViolation(violation);
}
@Override
public void onSuppressedRuleViolation(SuppressedViolation violation) {
report.addSuppressedViolation(violation);
}
@Override
public void onError(ProcessingError error) {
report.addError(error);
}
@Override
public String toString() {
return "ReportBuilderListener";
}
}
/**
* A {@link GlobalAnalysisListener} that accumulates the events of
* all files into a {@link Report}.
*/
public static final class GlobalReportBuilderListener extends BaseResultProducingCloseable<Report> implements GlobalAnalysisListener {
private final Report report = new Report();
@Override
public FileAnalysisListener startFileAnalysis(TextFile file) {
// note that the report is shared, but Report is now thread-safe
return new ReportBuilderListener(this.report);
}
@Override
public void onConfigError(ConfigurationError error) {
report.addConfigError(error);
}
@Override
protected Report getResultImpl() {
return report;
}
}
/**
* Creates a new report taking all the information from this report,
* but filtering the violations.
*
* @param filter when true, the violation will be kept.
* @return copy of this report
*/
@Experimental
public Report filterViolations(Predicate<RuleViolation> filter) {
Report copy = new Report();
for (RuleViolation violation : violations) {
if (filter.test(violation)) {
copy.addRuleViolation(violation);
}
}
copy.suppressedRuleViolations.addAll(suppressedRuleViolations);
copy.errors.addAll(errors);
copy.configErrors.addAll(configErrors);
return copy;
}
/**
* Creates a new report by combining this report with another report.
* This is similar to {@link #merge(Report)}, but instead a new report
* is created. The lowest start time and greatest end time are kept in the copy.
*
* @param other the other report to combine
* @return
*/
@Experimental
public Report union(Report other) {
Report copy = new Report();
for (RuleViolation violation : violations) {
copy.addRuleViolation(violation);
}
for (RuleViolation violation : other.violations) {
copy.addRuleViolation(violation);
}
copy.suppressedRuleViolations.addAll(suppressedRuleViolations);
copy.suppressedRuleViolations.addAll(other.suppressedRuleViolations);
copy.errors.addAll(errors);
copy.errors.addAll(other.errors);
copy.configErrors.addAll(configErrors);
copy.configErrors.addAll(other.configErrors);
return copy;
}
}
| 13,129 | 30.040189 | 138 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleContext.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.ViolationDecorator;
/**
* The API for rules to report violations or errors during analysis.
* This forwards events to a {@link FileAnalysisListener}. It implements
* violation suppression by filtering some violations out, according to
* the {@link ViolationSuppressor}s for the language.
*
* A RuleContext contains a Rule instance and violation reporting methods
* implicitly report only for that rule. Contrary to PMD 6, RuleContext is
* not unique throughout the analysis, a separate one is used per file and rule.
*/
public final class RuleContext {
// todo move to package reporting
// Rule contexts do not need to be thread-safe, within PmdRunnable
// they are stack-local
private static final Object[] NO_ARGS = new Object[0];
private static final List<ViolationSuppressor> DEFAULT_SUPPRESSORS = listOf(ViolationSuppressor.NOPMD_COMMENT_SUPPRESSOR,
ViolationSuppressor.REGEX_SUPPRESSOR,
ViolationSuppressor.XPATH_SUPPRESSOR);
private final FileAnalysisListener listener;
private final Rule rule;
private RuleContext(FileAnalysisListener listener, Rule rule) {
Objects.requireNonNull(listener, "Listener was null");
Objects.requireNonNull(rule, "Rule was null");
this.listener = listener;
this.rule = rule;
}
/**
* @deprecated Used in {@link AbstractRule#asCtx(Object)}, when that is gone, will be removed.
*/
@Deprecated
@InternalApi
public Rule getRule() {
return rule;
}
private String getDefaultMessage() {
return rule.getMessage();
}
/**
* Record a new violation of the contextual rule, at the given node.
*
* @param location Location of the violation
*/
public void addViolation(Node location) {
addViolationWithMessage(location, getDefaultMessage(), NO_ARGS);
}
/**
* Record a new violation of the contextual rule, at the given node.
* The default violation message ({@link Rule#getMessage()}) is formatted
* using the given format arguments.
*
* @param location Location of the violation
* @param formatArgs Format arguments for the message
*
* @see MessageFormat
*/
public void addViolation(Node location, Object... formatArgs) {
addViolationWithMessage(location, getDefaultMessage(), formatArgs);
}
/**
* Record a new violation of the contextual rule, at the given node.
* The given violation message ({@link Rule#getMessage()}) is treated
* as a format string for a {@link MessageFormat} and should hence use
* appropriate escapes. No formatting arguments are provided.
*
* @param location Location of the violation
* @param message Violation message
*/
public void addViolationWithMessage(Node location, String message) {
addViolationWithPosition(location, -1, -1, message, NO_ARGS);
}
/**
* Record a new violation of the contextual rule, at the given node.
* The given violation message ({@link Rule#getMessage()}) is treated
* as a format string for a {@link MessageFormat} and should hence use
* appropriate escapes. The given formatting arguments are used.
*
* @param location Location of the violation
* @param message Violation message
* @param formatArgs Format arguments for the message
*/
public void addViolationWithMessage(Node location, String message, Object... formatArgs) {
addViolationWithPosition(location, -1, -1, message, formatArgs);
}
/**
* Record a new violation of the contextual rule, at the given node.
* The position is refined using the given begin and end line numbers.
* The given violation message ({@link Rule#getMessage()}) is treated
* as a format string for a {@link MessageFormat} and should hence use
* appropriate escapes. The given formatting arguments are used.
*
* @param node Location of the violation
* @param message Violation message
* @param formatArgs Format arguments for the message
*/
public void addViolationWithPosition(Node node, int beginLine, int endLine, String message, Object... formatArgs) {
Objects.requireNonNull(node, "Node was null");
Objects.requireNonNull(message, "Message was null");
Objects.requireNonNull(formatArgs, "Format arguments were null, use an empty array");
LanguageVersionHandler handler = node.getAstInfo().getLanguageProcessor().services();
FileLocation location = node.getReportLocation();
if (beginLine != -1 && endLine != -1) {
location = FileLocation.range(location.getFileId(), TextRange2d.range2d(beginLine, 1, endLine, 1));
}
final Map<String, String> extraVariables = ViolationDecorator.apply(handler.getViolationDecorator(), node);
final String description = makeMessage(message, formatArgs, extraVariables);
final RuleViolation violation = new ParametricRuleViolation(rule, location, description, extraVariables);
final SuppressedViolation suppressed = suppressOrNull(node, violation, handler);
if (suppressed != null) {
listener.onSuppressedRuleViolation(suppressed);
} else {
listener.onRuleViolation(violation);
}
}
private static @Nullable SuppressedViolation suppressOrNull(Node location, RuleViolation rv, LanguageVersionHandler handler) {
SuppressedViolation suppressed = ViolationSuppressor.suppressOrNull(handler.getExtraViolationSuppressors(), rv, location);
if (suppressed == null) {
suppressed = ViolationSuppressor.suppressOrNull(DEFAULT_SUPPRESSORS, rv, location);
}
return suppressed;
}
/**
* Force the recording of a violation, ignoring the violation
* suppression mechanism ({@link ViolationSuppressor}).
*
* @param rv A violation
*/
@InternalApi
public void addViolationNoSuppress(RuleViolation rv) {
listener.onRuleViolation(rv);
}
private String makeMessage(@NonNull String message, Object[] args, Map<String, String> extraVars) {
// Escape PMD specific variable message format, specifically the {
// in the ${, so MessageFormat doesn't bitch.
final String escapedMessage = StringUtils.replace(message, "${", "$'{'");
String formatted = MessageFormat.format(escapedMessage, args);
return expandVariables(formatted, extraVars);
}
private String expandVariables(String message, Map<String, String> extraVars) {
if (!message.contains("${")) {
return message;
}
StringBuilder buf = new StringBuilder(message);
int startIndex = -1;
while ((startIndex = buf.indexOf("${", startIndex + 1)) >= 0) {
final int endIndex = buf.indexOf("}", startIndex);
if (endIndex >= 0) {
final String name = buf.substring(startIndex + 2, endIndex);
String variableValue = getVariableValue(name, extraVars);
if (variableValue != null) {
buf.replace(startIndex, endIndex + 1, variableValue);
}
}
}
return buf.toString();
}
private String getVariableValue(String name, Map<String, String> extraVars) {
String value = extraVars.get(name);
if (value != null) {
return value;
}
final PropertyDescriptor<?> propertyDescriptor = rule.getPropertyDescriptor(name);
return propertyDescriptor == null ? null : String.valueOf(rule.getProperty(propertyDescriptor));
}
/**
* Create a new RuleContext.
*
* The listener must be closed by its creator.
*/
@InternalApi
public static RuleContext create(FileAnalysisListener listener, Rule rule) {
return new RuleContext(listener, rule);
}
}
| 9,130 | 38.7 | 130 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetWriter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyDescriptorField;
import net.sourceforge.pmd.properties.PropertyTypeId;
/**
* This class represents a way to serialize a RuleSet to an XML configuration
* file.
*/
public class RuleSetWriter {
private static final Logger LOG = LoggerFactory.getLogger(RuleSetWriter.class);
public static final String RULESET_2_0_0_NS_URI = "http://pmd.sourceforge.net/ruleset/2.0.0";
private final OutputStream outputStream;
private Document document;
private Set<String> ruleSetFileNames;
public RuleSetWriter(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void close() {
IOUtil.closeQuietly(outputStream);
}
public void write(RuleSet ruleSet) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.newDocument();
ruleSetFileNames = new HashSet<>();
Element ruleSetElement = createRuleSetElement(ruleSet);
document.appendChild(ruleSetElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
transformerFactory.setAttribute("indent-number", 3);
} catch (IllegalArgumentException iae) {
// ignore it, specific to one parser
LOG.debug("Couldn't set indentation", iae);
}
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
// This is as close to pretty printing as we'll get using standard
// Java APIs.
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(document), new StreamResult(outputStream));
} catch (DOMException | FactoryConfigurationError | ParserConfigurationException | TransformerException e) {
throw new RuntimeException(e);
}
}
private Element createRuleSetElement(RuleSet ruleSet) {
Element ruleSetElement = document.createElementNS(RULESET_2_0_0_NS_URI, "ruleset");
ruleSetElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
ruleSetElement.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
RULESET_2_0_0_NS_URI + " https://pmd.sourceforge.io/ruleset_2_0_0.xsd");
ruleSetElement.setAttribute("name", ruleSet.getName());
Element descriptionElement = createDescriptionElement(ruleSet.getDescription());
ruleSetElement.appendChild(descriptionElement);
for (Pattern excludePattern : ruleSet.getFileExclusions()) {
Element excludePatternElement = createExcludePatternElement(excludePattern.pattern());
ruleSetElement.appendChild(excludePatternElement);
}
for (Pattern includePattern : ruleSet.getFileInclusions()) {
Element includePatternElement = createIncludePatternElement(includePattern.pattern());
ruleSetElement.appendChild(includePatternElement);
}
for (Rule rule : ruleSet.getRules()) {
Element ruleElement = createRuleElement(rule);
if (ruleElement != null) {
ruleSetElement.appendChild(ruleElement);
}
}
return ruleSetElement;
}
private Element createDescriptionElement(String description) {
return createTextElement("description", description);
}
private Element createExcludePatternElement(String excludePattern) {
return createTextElement("exclude-pattern", excludePattern);
}
private Element createIncludePatternElement(String includePattern) {
return createTextElement("include-pattern", includePattern);
}
private Element createRuleElement() {
return document.createElementNS(RULESET_2_0_0_NS_URI, "rule");
}
private Element createExcludeElement(String exclude) {
Element element = document.createElementNS(RULESET_2_0_0_NS_URI, "exclude");
element.setAttribute("name", exclude);
return element;
}
private Element createExampleElement(String example) {
return createCDATASectionElement("example", example);
}
private Element createPriorityElement(RulePriority priority) {
return createTextElement("priority", String.valueOf(priority.getPriority()));
}
private Element createPropertiesElement() {
return document.createElementNS(RULESET_2_0_0_NS_URI, "properties");
}
private Element createRuleElement(Rule rule) {
if (rule instanceof RuleReference) {
RuleReference ruleReference = (RuleReference) rule;
RuleSetReference ruleSetReference = ruleReference.getRuleSetReference();
if (ruleSetReference.isAllRules()) {
if (!ruleSetFileNames.contains(ruleSetReference.getRuleSetFileName())) {
ruleSetFileNames.add(ruleSetReference.getRuleSetFileName());
return createRuleSetReferenceElement(ruleSetReference);
} else {
return null;
}
} else {
LanguageVersion minimumLanguageVersion = ruleReference.getOverriddenMinimumLanguageVersion();
LanguageVersion maximumLanguageVersion = ruleReference.getOverriddenMaximumLanguageVersion();
Boolean deprecated = ruleReference.isOverriddenDeprecated();
String name = ruleReference.getOverriddenName();
String ref = ruleReference.getRuleSetReference().getRuleSetFileName() + '/'
+ ruleReference.getRule().getName();
String message = ruleReference.getOverriddenMessage();
String externalInfoUrl = ruleReference.getOverriddenExternalInfoUrl();
String description = ruleReference.getOverriddenDescription();
RulePriority priority = ruleReference.getOverriddenPriority();
List<PropertyDescriptor<?>> propertyDescriptors = ruleReference.getOverriddenPropertyDescriptors();
Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor = ruleReference
.getOverriddenPropertiesByPropertyDescriptor();
List<String> examples = ruleReference.getOverriddenExamples();
return createSingleRuleElement(null, minimumLanguageVersion, maximumLanguageVersion, deprecated,
name, null, ref, message, externalInfoUrl, null, description, priority,
propertyDescriptors, propertiesByPropertyDescriptor, examples);
}
} else {
return createSingleRuleElement(rule.getLanguage(),
rule.getMinimumLanguageVersion(), rule.getMaximumLanguageVersion(), rule.isDeprecated(),
rule.getName(), rule.getSince(), null, rule.getMessage(), rule.getExternalInfoUrl(),
rule.getRuleClass(),
rule.getDescription(),
rule.getPriority(), rule.getPropertyDescriptors(), rule.getPropertiesByPropertyDescriptor(),
rule.getExamples());
}
}
private void setIfNonNull(Object value, Element target, String id) {
if (value != null) {
target.setAttribute(id, value.toString());
}
}
private Element createSingleRuleElement(Language language, LanguageVersion minimumLanguageVersion,
LanguageVersion maximumLanguageVersion, Boolean deprecated, String name, String since, String ref,
String message, String externalInfoUrl, String clazz,
String description, RulePriority priority, List<PropertyDescriptor<?>> propertyDescriptors,
Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor, List<String> examples) {
Element ruleElement = createRuleElement();
// language is now a required attribute, unless this is a rule reference
if (clazz != null) {
ruleElement.setAttribute("language", language.getTerseName());
}
if (minimumLanguageVersion != null) {
ruleElement.setAttribute("minimumLanguageVersion", minimumLanguageVersion.getVersion());
}
if (maximumLanguageVersion != null) {
ruleElement.setAttribute("maximumLanguageVersion", maximumLanguageVersion.getVersion());
}
setIfNonNull(deprecated, ruleElement, "deprecated");
setIfNonNull(name, ruleElement, "name");
setIfNonNull(since, ruleElement, "since");
setIfNonNull(ref, ruleElement, "ref");
setIfNonNull(message, ruleElement, "message");
setIfNonNull(clazz, ruleElement, "class");
setIfNonNull(externalInfoUrl, ruleElement, "externalInfoUrl");
if (description != null) {
Element descriptionElement = createDescriptionElement(description);
ruleElement.appendChild(descriptionElement);
}
if (priority != null) {
Element priorityElement = createPriorityElement(priority);
ruleElement.appendChild(priorityElement);
}
Element propertiesElement = createPropertiesElement(propertyDescriptors, propertiesByPropertyDescriptor);
if (propertiesElement != null) {
ruleElement.appendChild(propertiesElement);
}
if (examples != null) {
for (String example : examples) {
Element exampleElement = createExampleElement(example);
ruleElement.appendChild(exampleElement);
}
}
return ruleElement;
}
private Element createRuleSetReferenceElement(RuleSetReference ruleSetReference) {
Element ruleSetReferenceElement = createRuleElement();
ruleSetReferenceElement.setAttribute("ref", ruleSetReference.getRuleSetFileName());
for (String exclude : ruleSetReference.getExcludes()) {
Element excludeElement = createExcludeElement(exclude);
ruleSetReferenceElement.appendChild(excludeElement);
}
return ruleSetReferenceElement;
}
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private Element createPropertiesElement(List<PropertyDescriptor<?>> propertyDescriptors,
Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor) {
Element propertiesElement = null;
if (propertyDescriptors != null) {
for (PropertyDescriptor<?> propertyDescriptor : propertyDescriptors) {
// For each provided PropertyDescriptor
if (propertyDescriptor.isDefinedExternally()) {
// Any externally defined property needs to go out as a definition.
if (propertiesElement == null) {
propertiesElement = createPropertiesElement();
}
Element propertyElement = createPropertyDefinitionElementBR(propertyDescriptor);
propertiesElement.appendChild(propertyElement);
} else {
if (propertiesByPropertyDescriptor != null) {
// Otherwise, any property which has a value different than the default needs to go out as a value.
Object defaultValue = propertyDescriptor.defaultValue();
Object value = propertiesByPropertyDescriptor.get(propertyDescriptor);
if (value != defaultValue && (value == null || !value.equals(defaultValue))) {
if (propertiesElement == null) {
propertiesElement = createPropertiesElement();
}
Element propertyElement = createPropertyValueElement(propertyDescriptor, value);
propertiesElement.appendChild(propertyElement);
}
}
}
}
}
if (propertiesByPropertyDescriptor != null) {
// Then, for each PropertyDescriptor not explicitly provided
for (Map.Entry<PropertyDescriptor<?>, Object> entry : propertiesByPropertyDescriptor.entrySet()) {
// If not explicitly given...
PropertyDescriptor<?> propertyDescriptor = entry.getKey();
if (!propertyDescriptors.contains(propertyDescriptor)) {
// Otherwise, any property which has a value different than
// the
// default needs to go out as a value.
Object defaultValue = propertyDescriptor.defaultValue();
Object value = entry.getValue();
if (value != defaultValue && (value == null || !value.equals(defaultValue))) {
if (propertiesElement == null) {
propertiesElement = createPropertiesElement();
}
Element propertyElement = createPropertyValueElement(propertyDescriptor, value);
propertiesElement.appendChild(propertyElement);
}
}
}
}
return propertiesElement;
}
private Element createPropertyValueElement(PropertyDescriptor propertyDescriptor, Object value) {
Element propertyElement = document.createElementNS(RULESET_2_0_0_NS_URI, "property");
propertyElement.setAttribute("name", propertyDescriptor.name());
String valueString = propertyDescriptor.asDelimitedString(value);
if (XPathRule.XPATH_DESCRIPTOR.equals(propertyDescriptor)) {
Element valueElement = createCDATASectionElement("value", valueString);
propertyElement.appendChild(valueElement);
} else {
propertyElement.setAttribute("value", valueString);
}
return propertyElement;
}
private Element createPropertyDefinitionElementBR(PropertyDescriptor<?> propertyDescriptor) {
final Element propertyElement = createPropertyValueElement(propertyDescriptor,
propertyDescriptor.defaultValue());
propertyElement.setAttribute(PropertyDescriptorField.TYPE.attributeName(),
PropertyTypeId.typeIdFor(propertyDescriptor.type(),
propertyDescriptor.isMultiValue()));
Map<PropertyDescriptorField, String> propertyValuesById = propertyDescriptor.attributeValuesById();
for (Map.Entry<PropertyDescriptorField, String> entry : propertyValuesById.entrySet()) {
propertyElement.setAttribute(entry.getKey().attributeName(), entry.getValue());
}
return propertyElement;
}
private Element createTextElement(String name, String value) {
Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name);
Text text = document.createTextNode(value);
element.appendChild(text);
return element;
}
private Element createCDATASectionElement(String name, String value) {
Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name);
CDATASection cdataSection = document.createCDATASection(value);
element.appendChild(cdataSection);
return element;
}
}
| 17,118 | 46.15978 | 135 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.cache.ChecksumAware;
import net.sourceforge.pmd.internal.util.PredicateUtil;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.lang.rule.XPathRule;
/**
* This class represents a collection of rules along with some optional filter
* patterns that can preclude their application on specific files.
*
* @see Rule
*/
public class RuleSet implements ChecksumAware {
private static final Logger LOG = LoggerFactory.getLogger(RuleSet.class);
private static final String MISSING_RULE = "Missing rule";
private static final String MISSING_RULESET_DESCRIPTION = "RuleSet description must not be null";
private static final String MISSING_RULESET_NAME = "RuleSet name must not be null";
private final long checksum;
private final List<Rule> rules;
private final String fileName;
private final String name;
private final String description;
/*
* Order is unimportant, but we preserve the order given by the user to be deterministic.
* Using Sets is useless, since Pattern does not override #equals anyway.
*/
private final List<Pattern> excludePatterns;
private final List<Pattern> includePatterns;
private final Predicate<String> filter;
/**
* Creates a new RuleSet with the given checksum.
*
* @param builder
* A rule set builder.
*/
private RuleSet(final RuleSetBuilder builder) {
checksum = builder.checksum;
fileName = builder.fileName;
name = Objects.requireNonNull(builder.name, MISSING_RULESET_NAME);
description = Objects.requireNonNull(builder.description, MISSING_RULESET_DESCRIPTION);
// TODO: ideally, the rules would be unmodifiable, too. But removeDysfunctionalRules might change the rules.
rules = builder.rules;
excludePatterns = Collections.unmodifiableList(new ArrayList<>(builder.excludePatterns));
includePatterns = Collections.unmodifiableList(new ArrayList<>(builder.includePatterns));
final Predicate<String> regexFilter = PredicateUtil.buildRegexFilterIncludeOverExclude(includePatterns, excludePatterns);
filter = PredicateUtil.toNormalizedFileFilter(regexFilter);
}
public RuleSet(final RuleSet rs) {
checksum = rs.checksum;
fileName = rs.fileName;
name = rs.name;
description = rs.description;
rules = new ArrayList<>(rs.rules.size());
for (final Rule rule : rs.rules) {
rules.add(rule.deepCopy());
}
excludePatterns = rs.excludePatterns; // we can share immutable lists of immutable elements
includePatterns = rs.includePatterns;
filter = rs.filter; // filters are immutable, can be shared
}
/**
* Creates a new ruleset containing a single rule. The ruleset will
* have default description, name, and null file name.
*
* @param rule The rule being created
*
* @return The newly created RuleSet
*/
public static RuleSet forSingleRule(final Rule rule) {
final long checksum;
if (rule instanceof XPathRule) {
checksum = ((XPathRule) rule).getXPathExpression().hashCode();
} else {
// TODO : Is this good enough? all properties' values + rule name
checksum = rule.getPropertiesByPropertyDescriptor().values().hashCode() * 31 + rule.getName().hashCode();
}
final RuleSetBuilder builder =
new RuleSetBuilder(checksum)
.withName(rule.getName())
.withDescription("RuleSet for " + rule.getName());
builder.addRule(rule);
return builder.build();
}
/**
* Creates a new ruleset with the given metadata such as name, description,
* fileName, exclude/include patterns are used. The rules are taken from the given
* collection.
*
* <p><strong>Note:</strong> The rule instances are shared between the collection
* and the new ruleset (copy-by-reference). This might lead to concurrency issues,
* if the rules of the collection are also referenced by other rulesets and used
* in different threads.
* </p>
*
* @param name the name of the ruleset
* @param description the description
* @param fileName the filename
* @param excludePatterns list of exclude patterns
* @param includePatterns list of include patterns, that override the exclude patterns
* @param rules the collection with the rules to add to the new ruleset
*
* @return the new ruleset
*
* @throws NullPointerException If any parameter is null, or the collections contain null elements
*/
public static RuleSet create(String name,
String description,
String fileName,
Collection<Pattern> excludePatterns,
Collection<Pattern> includePatterns,
Iterable<? extends Rule> rules) {
RuleSetBuilder builder = new RuleSetBuilder(0L); // TODO: checksum missing
builder.withName(name)
.withDescription(description)
.withFileName(fileName)
.replaceFileExclusions(excludePatterns)
.replaceFileInclusions(includePatterns);
for (Rule rule : rules) {
builder.addRule(rule);
}
return builder.build();
}
/**
* Creates a copy of the given ruleset. All properties like name, description, fileName
* and exclude/include patterns are copied.
*
* <p><strong>Note:</strong> The rule instances are shared between the original
* and the new ruleset (copy-by-reference). This might lead to concurrency issues,
* if the original ruleset and the new ruleset are used in different threads.
* </p>
*
* @param original the original rule set to copy from
*
* @return the copy
*/
public static RuleSet copy(RuleSet original) {
return new RuleSet(original);
}
/* package */ static class RuleSetBuilder {
public String description;
public String name;
public String fileName;
private final List<Rule> rules = new ArrayList<>();
private final Set<Pattern> excludePatterns = new LinkedHashSet<>();
private final Set<Pattern> includePatterns = new LinkedHashSet<>();
private final long checksum;
/* package */ RuleSetBuilder(final long checksum) {
this.checksum = checksum;
}
/** Copy constructor. Takes the same checksum as the original ruleset. */
/* package */ RuleSetBuilder(final RuleSet original) {
checksum = original.getChecksum();
this.withName(original.getName())
.withDescription(original.getDescription())
.withFileName(original.getFileName())
.replaceFileExclusions(original.getFileExclusions())
.replaceFileInclusions(original.getFileInclusions());
addRuleSet(original);
}
/**
* Add a new rule to this ruleset. Note that this method does not check
* for duplicates.
*
* @param newRule
* the rule to be added
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRule(final Rule newRule) {
if (newRule == null) {
throw new IllegalArgumentException(MISSING_RULE);
}
// check for duplicates - adding more than one rule with the same name will
// be problematic - see #RuleSet.getRuleByName(String)
for (Rule rule : rules) {
if (rule.getName().equals(newRule.getName()) && rule.getLanguage().equals(newRule.getLanguage())) {
LOG.warn("The rule with name {} is duplicated. "
+ "Future versions of PMD will reject to load such rulesets.",
newRule.getName());
break;
}
}
rules.add(newRule);
return this;
}
/**
* Finds an already added rule by same name and language, if it already exists.
* @param rule the rule to search
* @return the already added rule or <code>null</code> if no rule was added yet to the builder.
*/
Rule getExistingRule(final Rule rule) {
for (Rule r : rules) {
if (r.getName().equals(rule.getName()) && r.getLanguage().equals(rule.getLanguage())) {
return r;
}
}
return null;
}
/**
* Checks, whether a rule with the same name and language already exists in the
* ruleset.
* @param rule to rule to check
* @return <code>true</code> if the rule already exists, <code>false</code> if the given
* rule is the first configuration of this rule.
*/
boolean hasRule(final Rule rule) {
return getExistingRule(rule) != null;
}
/**
* Adds a rule. If a rule with the same name and language already
* existed before in the ruleset, then the new rule will replace it.
* This makes sure that the rule configured is overridden.
*
* @param rule
* the new rule to add
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleReplaceIfExists(final Rule rule) {
if (rule == null) {
throw new IllegalArgumentException(MISSING_RULE);
}
for (final Iterator<Rule> it = rules.iterator(); it.hasNext();) {
final Rule r = it.next();
if (r.getName().equals(rule.getName()) && r.getLanguage().equals(rule.getLanguage())) {
it.remove();
}
}
addRule(rule);
return this;
}
/**
* Only adds a rule to the ruleset if no rule with the same name for the
* same language was added before, so that the existent rule
* configuration won't be overridden.
*
* @param ruleOrRef
* the new rule to add
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleIfNotExists(final Rule ruleOrRef) {
if (ruleOrRef == null) {
throw new IllegalArgumentException(MISSING_RULE);
}
// resolve the underlying rule, to avoid adding duplicated rules
// if the rule has been renamed/merged and moved at the same time
Rule rule = ruleOrRef;
while (rule instanceof RuleReference) {
rule = ((RuleReference) rule).getRule();
}
boolean exists = hasRule(rule);
if (!exists) {
addRule(ruleOrRef);
}
return this;
}
/**
* Add a new rule by reference to this ruleset.
*
* @param ruleSetFileName
* the ruleset which contains the rule
* @param rule
* the rule to be added
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleByReference(final String ruleSetFileName, final Rule rule) {
if (StringUtils.isBlank(ruleSetFileName)) {
throw new RuntimeException(
"Adding a rule by reference is not allowed with an empty rule set file name.");
}
if (rule == null) {
throw new IllegalArgumentException("Cannot add a null rule reference to a RuleSet");
}
final RuleReference ruleReference;
if (rule instanceof RuleReference) {
ruleReference = (RuleReference) rule;
} else {
final RuleSetReference ruleSetReference = new RuleSetReference(ruleSetFileName);
ruleReference = new RuleReference(rule, ruleSetReference);
}
rules.add(ruleReference);
return this;
}
/**
* Add all rules of a whole RuleSet to this RuleSet
*
* @param ruleSet
* the RuleSet to add
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleSet(final RuleSet ruleSet) {
rules.addAll(ruleSet.getRules());
return this;
}
/**
* Add all rules by reference from one RuleSet to this RuleSet. The
* rules can be added as individual references, or collectively as an
* all rule reference.
*
* @param ruleSet
* the RuleSet to add
* @param allRules
* <code>true</code> if the ruleset should be added
* collectively or <code>false</code> to add individual
* references for each rule.
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleSetByReference(final RuleSet ruleSet, final boolean allRules) {
return addRuleSetByReference(ruleSet, allRules, (String[]) null);
}
/**
* Add all rules by reference from one RuleSet to this RuleSet. The
* rules can be added as individual references, or collectively as an
* all rule reference.
*
* @param ruleSet
* the RuleSet to add
* @param allRules
* <code>true</code> if the ruleset should be added
* collectively or <code>false</code> to add individual
* references for each rule.
* @param excludes
* names of the rules that should be excluded.
* @return The same builder, for a fluid programming interface
*/
public RuleSetBuilder addRuleSetByReference(final RuleSet ruleSet, final boolean allRules,
final String... excludes) {
if (StringUtils.isBlank(ruleSet.getFileName())) {
throw new RuntimeException(
"Adding a rule by reference is not allowed with an empty rule set file name.");
}
final RuleSetReference ruleSetReference;
if (excludes == null) {
ruleSetReference = new RuleSetReference(ruleSet.getFileName(), allRules);
} else {
ruleSetReference = new RuleSetReference(ruleSet.getFileName(), allRules, new LinkedHashSet<>(Arrays.asList(excludes)));
}
for (final Rule rule : ruleSet.getRules()) {
final RuleReference ruleReference = new RuleReference(rule, ruleSetReference);
rules.add(ruleReference);
}
return this;
}
/**
* Adds some new file exclusion patterns.
*
* @param p1 The first pattern
* @param rest Additional patterns
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder withFileExclusions(Pattern p1, Pattern... rest) {
Objects.requireNonNull(p1, "Pattern was null");
Objects.requireNonNull(rest, "Other patterns was null");
excludePatterns.add(p1);
for (Pattern p : rest) {
Objects.requireNonNull(p, "Pattern was null");
excludePatterns.add(p);
}
return this;
}
/**
* Adds some new file exclusion patterns.
*
* @param patterns Exclusion patterns to add
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder withFileExclusions(Collection<? extends Pattern> patterns) {
Objects.requireNonNull(patterns, "Pattern collection was null");
for (Pattern p : patterns) {
Objects.requireNonNull(p, "Pattern was null");
excludePatterns.add(p);
}
return this;
}
/**
* Replaces the existing exclusion patterns with the given patterns.
*
* @param patterns Exclusion patterns to set
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder replaceFileExclusions(Collection<? extends Pattern> patterns) {
Objects.requireNonNull(patterns, "Pattern collection was null");
excludePatterns.clear();
for (Pattern p : patterns) {
Objects.requireNonNull(p, "Pattern was null");
excludePatterns.add(p);
}
return this;
}
/**
* Adds some new file inclusion patterns.
*
* @param p1 The first pattern
* @param rest Additional patterns
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder withFileInclusions(Pattern p1, Pattern... rest) {
Objects.requireNonNull(p1, "Pattern was null");
Objects.requireNonNull(rest, "Other patterns was null");
includePatterns.add(p1);
for (Pattern p : rest) {
Objects.requireNonNull(p, "Pattern was null");
includePatterns.add(p);
}
return this;
}
/**
* Adds some new file inclusion patterns.
*
* @param patterns Inclusion patterns to add
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder withFileInclusions(Collection<? extends Pattern> patterns) {
Objects.requireNonNull(patterns, "Pattern collection was null");
for (Pattern p : patterns) {
Objects.requireNonNull(p, "Pattern was null");
includePatterns.add(p);
}
return this;
}
/**
* Replaces the existing inclusion patterns with the given patterns.
*
* @param patterns Inclusion patterns to set
*
* @return This builder
*
* @throws NullPointerException If any of the specified patterns is null
*/
public RuleSetBuilder replaceFileInclusions(Collection<? extends Pattern> patterns) {
Objects.requireNonNull(patterns, "Pattern collection was null");
includePatterns.clear();
for (Pattern p : patterns) {
Objects.requireNonNull(p, "Pattern was null");
includePatterns.add(p);
}
return this;
}
public RuleSetBuilder withFileName(final String fileName) {
this.fileName = fileName;
return this;
}
public RuleSetBuilder withName(final String name) {
this.name = Objects.requireNonNull(name, MISSING_RULESET_NAME);
return this;
}
public RuleSetBuilder withDescription(final String description) {
this.description = Objects.requireNonNull(description, MISSING_RULESET_DESCRIPTION);
return this;
}
public boolean hasDescription() {
return this.description != null;
}
public String getName() {
return name;
}
public RuleSet build() {
return new RuleSet(this);
}
public void filterRulesByPriority(RulePriority minimumPriority) {
Iterator<Rule> iterator = rules.iterator();
while (iterator.hasNext()) {
Rule rule = iterator.next();
if (rule.getPriority().compareTo(minimumPriority) > 0) {
LOG.debug("Removing rule {} due to priority: {} required: {}",
rule.getName(), rule.getPriority(), minimumPriority);
iterator.remove();
}
}
}
}
/**
* Returns the number of rules in this ruleset
*
* @return an int representing the number of rules
*/
public int size() {
return rules.size();
}
/**
* Returns the actual Collection of rules in this ruleset
*
* @return a Collection with the rules. All objects are of type {@link Rule}
*/
public Collection<Rule> getRules() {
return rules;
}
/**
* Returns the first Rule found with the given name (case-sensitive).
*
* Note: Since we support multiple languages, rule names are not expected to
* be unique within any specific ruleset.
*
* @param ruleName
* the exact name of the rule to find
* @return the rule or null if not found
*/
public Rule getRuleByName(String ruleName) {
for (Rule r : rules) {
if (r.getName().equals(ruleName)) {
return r;
}
}
return null;
}
/**
* Check if a given source file should be checked by rules in this RuleSet.
* A file should not be checked if there is an <code>exclude</code> pattern
* which matches the file, unless there is an <code>include</code> pattern
* which also matches the file. In other words, <code>include</code>
* patterns override <code>exclude</code> patterns.
*
* @param qualFileName the source path to check
*
* @return <code>true</code> if the file should be checked,
* <code>false</code> otherwise
*/
// TODO get rid of this overload
@InternalApi
public boolean applies(FileId qualFileName) {
return filter.test(qualFileName.getAbsolutePath());
}
/**
* Check if a given source file should be checked by rules in this RuleSet.
* A file should not be checked if there is an <code>exclude</code> pattern
* which matches the file, unless there is an <code>include</code> pattern
* which also matches the file. In other words, <code>include</code>
* patterns override <code>exclude</code> patterns.
*
* @param file a text file
*
* @return <code>true</code> if the file should be checked,
* <code>false</code> otherwise
*/
boolean applies(TextFile file) {
return applies(file.getFileId());
}
/**
* Does the given Rule apply to the given LanguageVersion? If so, the
* Language must be the same and be between the minimum and maximums
* versions on the Rule.
*
* @param rule
* The rule.
* @param languageVersion
* The language version.
*
* @return <code>true</code> if the given rule matches the given language,
* which means, that the rule would be executed.
*
* @deprecated This is internal API, removed in PMD 7. You should
* not use a ruleset directly.
*/
@Deprecated
@InternalApi
public static boolean applies(Rule rule, LanguageVersion languageVersion) {
final LanguageVersion min = rule.getMinimumLanguageVersion();
final LanguageVersion max = rule.getMaximumLanguageVersion();
assert rule.getLanguage() != null : "Rule has no language " + rule;
return rule.getLanguage().equals(languageVersion.getLanguage())
&& (min == null || min.compareTo(languageVersion) <= 0)
&& (max == null || max.compareTo(languageVersion) >= 0);
}
/**
* Two rulesets are equals, if they have the same name and contain the same
* rules.
*
* @param o
* the other ruleset to compare with
* @return <code>true</code> if o is a ruleset with the same name and rules,
* <code>false</code> otherwise
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof RuleSet)) {
return false; // Trivial
}
if (this == o) {
return true; // Basic equality
}
RuleSet ruleSet = (RuleSet) o;
return getName().equals(ruleSet.getName()) && getRules().equals(ruleSet.getRules());
}
@Override
public int hashCode() {
return getName().hashCode() + 13 * getRules().hashCode();
}
public String getFileName() {
return fileName;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
/**
* Returns the file exclusion patterns as an unmodifiable list.
*/
public List<Pattern> getFileExclusions() {
return excludePatterns;
}
/**
* Returns the file inclusion patterns as an unmodifiable list.
*/
public List<Pattern> getFileInclusions() {
return includePatterns;
}
/**
* Remove and collect any misconfigured rules.
* TODO remove this method. This mutates rulesets for nothing. Whether
* a rule is dysfunctional or not should be checked when it is initialized.
*
* @param collector
* the removed rules will be added to this collection
*
* @deprecated This is internal API, removed in PMD 7. You should
* not use a ruleset directly.
*/
@Deprecated
@InternalApi
public void removeDysfunctionalRules(Collection<Rule> collector) {
Iterator<Rule> iter = rules.iterator();
while (iter.hasNext()) {
Rule rule = iter.next();
if (rule.dysfunctionReason() != null) {
iter.remove();
collector.add(rule);
}
}
}
@Override
public long getChecksum() {
return checksum;
}
}
| 27,094 | 35.369128 | 135 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/ViolationSuppressor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
import net.sourceforge.pmd.lang.rule.xpath.internal.DeprecatedAttrLogger;
import net.sourceforge.pmd.lang.rule.xpath.internal.SaxonXPathRuleQuery;
/**
* An object that suppresses rule violations. Suppressors are used by
* {@link RuleContext} to filter out violations. In PMD 6.0.x,
* the {@link Report} object filtered violations itself - but it has
* no knowledge of language-specific suppressors.
*/
public interface ViolationSuppressor {
// todo move to package reporting
/**
* Suppressor for the violationSuppressRegex property.
*/
ViolationSuppressor REGEX_SUPPRESSOR = new ViolationSuppressor() {
@Override
public String getId() {
return "Regex";
}
@Override
public @Nullable SuppressedViolation suppressOrNull(RuleViolation rv, @NonNull Node node) {
String regex = rv.getRule().getProperty(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR); // Regex
if (regex != null && rv.getDescription() != null) {
if (Pattern.matches(regex, rv.getDescription())) {
return new SuppressedViolation(rv, this, regex);
}
}
return null;
}
};
/**
* Suppressor for the violationSuppressXPath property.
*/
ViolationSuppressor XPATH_SUPPRESSOR = new ViolationSuppressor() {
@Override
public String getId() {
return "XPath";
}
@Override
public @Nullable SuppressedViolation suppressOrNull(RuleViolation rv, @NonNull Node node) {
// todo this should not be implemented via a rule property
// because the parsed xpath expression should be stored, not a random string
// this needs to be checked to be a valid xpath expression in the ruleset,
// not at the time it is evaluated, and also parsed by the XPath parser only once
Rule rule = rv.getRule();
String xpath = rule.getProperty(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR);
if (xpath == null) {
return null;
}
SaxonXPathRuleQuery rq = new SaxonXPathRuleQuery(
xpath,
XPathVersion.DEFAULT,
rule.getPropertiesByPropertyDescriptor(),
node.getAstInfo().getLanguageProcessor().services().getXPathHandler(),
DeprecatedAttrLogger.createForSuppression(rv.getRule())
);
if (!rq.evaluate(node).isEmpty()) {
return new SuppressedViolation(rv, this, xpath);
}
return null;
}
};
/**
* Suppressor for regular NOPMD comments.
*
* @implNote This requires special support from the language, namely,
* the parser must fill-in {@link AstInfo#getSuppressionComments()}.
*/
ViolationSuppressor NOPMD_COMMENT_SUPPRESSOR = new ViolationSuppressor() {
@Override
public String getId() {
return "//NOPMD";
}
@Override
public @Nullable SuppressedViolation suppressOrNull(RuleViolation rv, @NonNull Node node) {
Map<Integer, String> noPmd = node.getAstInfo().getSuppressionComments();
if (noPmd.containsKey(rv.getBeginLine())) {
return new SuppressedViolation(rv, this, noPmd.get(rv.getBeginLine()));
}
return null;
}
};
/**
* A name, for reporting and documentation purposes.
*/
String getId();
/**
* Returns a {@link SuppressedViolation} if the given violation is
* suppressed by this object. The node and the rule are provided
* for context. Returns null if the violation is not suppressed.
*/
@Nullable
SuppressedViolation suppressOrNull(RuleViolation rv, @NonNull Node node);
/**
* Apply a list of suppressors on the violation. Returns the violation
* of the first suppressor that matches the input violation. If no
* suppressor matches, then returns null.
*/
static @Nullable SuppressedViolation suppressOrNull(List<ViolationSuppressor> suppressorList,
RuleViolation rv,
Node node) {
for (ViolationSuppressor suppressor : suppressorList) {
SuppressedViolation suppressed = suppressor.suppressOrNull(rv, node);
if (suppressed != null) {
return suppressed;
}
}
return null;
}
}
| 5,086 | 35.335714 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RulePriority.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
/**
* These are the possible Rule priority values.
*
* For backward compatibility, priorities range in value from 1 to 5, with 5
* being the lowest priority. This means the ordinal value of the Enum should be
* avoided in favor of {@link RulePriority#getPriority()} and
* {@link RulePriority#valueOf(int)}
*
* @see <a href="https://docs.pmd-code.org/latest/pmd_userdocs_extending_rule_guidelines.html">How
* to define rules priority</a>
*/
public enum RulePriority {
/** High: Change absolutely required. Behavior is critically broken/buggy */
HIGH(1, "High"),
/**
* Medium to high: Change highly recommended. Behavior is quite likely to be
* broken/buggy.
*/
MEDIUM_HIGH(2, "Medium High"),
/**
* Medium: Change recommended. Behavior is confusing, perhaps buggy, and/or
* against standards/best practices.
*/
MEDIUM(3, "Medium"),
/**
* Medium to low: Change optional. Behavior is not likely to be buggy, but
* more just flies in the face of standards/style/good taste.
*/
MEDIUM_LOW(4, "Medium Low"),
/**
* Low: Change highly optional. Nice to have, such as a consistent naming
* policy for package/class/fields...
*/
LOW(5, "Low");
private final int priority;
private final String name;
RulePriority(int priority, String name) {
this.priority = priority;
this.name = name;
}
/**
* Get the priority value as a number. This is the value to be used in the
* externalized form of a priority (e.g. in RuleSet XML).
*
* @return The <code>int</code> value of the priority.
*/
public int getPriority() {
return priority;
}
/**
* Get the descriptive name of this priority.
*
* @return The descriptive name.
*/
public String getName() {
return name;
}
/**
* Returns the descriptive name of the priority.
*
* @return descriptive name of the priority
* @see #getName()
*/
@Override
public String toString() {
return name;
}
/**
* Get the priority which corresponds to the given number as returned by
* {@link RulePriority#getPriority()}. If the number is an invalid value,
* then {@link RulePriority#LOW} will be returned.
*
* @param priority
* The numeric priority value.
* @return The priority.
*/
public static RulePriority valueOf(int priority) {
try {
return RulePriority.values()[priority - 1];
} catch (ArrayIndexOutOfBoundsException e) {
return LOW;
}
}
/**
* Returns the priority which corresponds to the given number as returned by
* {@link RulePriority#getPriority()}. If the number is an invalid value,
* then null will be returned.
*
* @param priority The numeric priority value.
*/
public static RulePriority valueOfNullable(int priority) {
try {
return RulePriority.values()[priority - 1];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
/**
* Returns the priority which corresponds to the given number as returned by
* {@link RulePriority#getPriority()}. If the number is an invalid value,
* then null will be returned.
*
* @param priority The numeric priority value.
*/
public static RulePriority valueOfNullable(String priority) {
try {
int integer = Integer.parseInt(priority);
return RulePriority.values()[integer - 1];
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
return null;
}
}
}
| 3,843 | 28.79845 | 98 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.Comparator;
import java.util.Map;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
/**
* A RuleViolation is created by a Rule when it identifies a violation of the
* Rule constraints. RuleViolations are simple data holders that are collected
* into a {@link Report}.
*
* <p>Since PMD 6.21.0, implementations of this interface are considered internal
* API and hence deprecated. Clients should exclusively use this interface.
*
* @see Rule
*/
public interface RuleViolation {
// todo move to package reporting
/**
* A comparator for rule violations. This compares all exposed attributes
* of a violation, filename first. The remaining parameters are compared
* in an unspecified order.
*/
Comparator<RuleViolation> DEFAULT_COMPARATOR =
Comparator.comparing(RuleViolation::getFileId)
.thenComparingInt(RuleViolation::getBeginLine)
.thenComparingInt(RuleViolation::getBeginColumn)
.thenComparing(RuleViolation::getDescription, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparingInt(RuleViolation::getEndLine)
.thenComparingInt(RuleViolation::getEndColumn)
.thenComparing(rv -> rv.getRule().getName());
/**
* Key in {@link #getAdditionalInfo()} for the name of the class in
* which the violation was identified.
*/
String CLASS_NAME = "className";
/**
* Key in {@link #getAdditionalInfo()} for the name of the variable
* related to the violation.
*/
String VARIABLE_NAME = "variableName";
/**
* Key in {@link #getAdditionalInfo()} for the name of the method in
* which the violation was identified.
*/
String METHOD_NAME = "methodName";
/**
* Key in {@link #getAdditionalInfo()} for the name of the package in
* which the violation was identified.
*/
String PACKAGE_NAME = "packageName";
/**
* Get the Rule which identified this violation.
*
* @return The identifying Rule.
*/
Rule getRule();
/**
* Get the description of this violation.
*
* @return The description.
*/
String getDescription();
/**
* Returns the location where the violation should be reported.
*/
FileLocation getLocation();
/**
* Return the ID of the file where the violation was found.
*/
default FileId getFileId() {
return getLocation().getFileId();
}
/**
* Get the begin line number in the source file in which this violation was
* identified.
*
* @return Begin line number.
*/
default int getBeginLine() {
return getLocation().getStartPos().getLine();
}
/**
* Get the column number of the begin line in the source file in which this
* violation was identified.
*
* @return Begin column number.
*/
default int getBeginColumn() {
return getLocation().getStartPos().getColumn();
}
/**
* Get the end line number in the source file in which this violation was
* identified.
*
* @return End line number.
*/
default int getEndLine() {
return getLocation().getEndPos().getLine();
}
/**
* Get the column number of the end line in the source file in which this
* violation was identified.
*
* @return End column number.
*/
default int getEndColumn() {
return getLocation().getEndPos().getColumn();
}
/**
* A map of additional key-value pairs known about this violation.
* What data is in there is language specific. Common keys supported
* by several languages are defined as constants on this interface.
* The map is unmodifiable.
*/
Map<String, String> getAdditionalInfo();
/**
* Get the package name of the Class in which this violation was identified.
*
* @return The package name.
*
* @deprecated Use {@link #PACKAGE_NAME}
*/
@Deprecated
@DeprecatedUntil700
default String getPackageName() {
return getAdditionalInfo().get(PACKAGE_NAME);
}
/**
* Get the name of the Class in which this violation was identified.
*
* @return The Class name.
* @deprecated Use {@link #CLASS_NAME}
*/
@Deprecated
@DeprecatedUntil700
default String getClassName() {
return getAdditionalInfo().get(CLASS_NAME);
}
/**
* Get the method name in which this violation was identified.
*
* @return The method name.
* @deprecated Use {@link #METHOD_NAME}
*/
@Deprecated
@DeprecatedUntil700
default String getMethodName() {
return getAdditionalInfo().get(METHOD_NAME);
}
/**
* Get the variable name on which this violation was identified.
*
* @return The variable name.
* @deprecated Use {@link #VARIABLE_NAME}
*/
@Deprecated
@DeprecatedUntil700
default String getVariableName() {
return getAdditionalInfo().get(VARIABLE_NAME);
}
}
| 5,332 | 27.068421 | 112 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetLoadException.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* An exception that is thrown when something wrong occurs while
* {@linkplain RuleSetLoader loading rulesets}. This may be because the
* XML is not well-formed, does not respect the ruleset schema, is
* not a valid ruleset or is otherwise unparsable.
*/
public final class RuleSetLoadException extends RuntimeException {
/** Constructors are internal. */
@InternalApi
public RuleSetLoadException(RuleSetReferenceId rsetId, @NonNull Throwable cause) {
super("Cannot load ruleset " + rsetId + ": " + cause.getMessage(), cause);
}
/** Constructors are internal. */
@InternalApi
public RuleSetLoadException(RuleSetReferenceId rsetId, String message) {
super("Cannot load ruleset " + rsetId + ": " + message);
}
}
| 999 | 30.25 | 86 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetReference.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* This class represents a reference to RuleSet.
*
* @deprecated This is part of the internals of the {@link RuleSetLoader}.
*/
@Deprecated
@InternalApi
public class RuleSetReference {
private final String ruleSetFileName;
private final boolean allRules;
private final Set<String> excludes;
public RuleSetReference(final String theFilename, final boolean allRules, final Set<String> excludes) {
ruleSetFileName = theFilename;
this.allRules = allRules;
this.excludes = Collections.unmodifiableSet(new LinkedHashSet<>(excludes));
}
public RuleSetReference(final String theFilename, final boolean allRules) {
ruleSetFileName = theFilename;
this.allRules = allRules;
this.excludes = Collections.<String>emptySet();
}
public RuleSetReference(final String theFilename) {
this(theFilename, false);
}
public String getRuleSetFileName() {
return ruleSetFileName;
}
public boolean isAllRules() {
return allRules;
}
public Set<String> getExcludes() {
return excludes;
}
}
| 1,370 | 24.867925 | 107 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactoryCompatibility.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides a simple filter mechanism to avoid failing to parse an old ruleset,
* which references rules, that have either been removed from PMD already or
* renamed or moved to another ruleset.
*
* @see <a href="https://sourceforge.net/p/pmd/bugs/1360/">issue 1360</a>
*/
final class RuleSetFactoryCompatibility {
static final RuleSetFactoryCompatibility EMPTY = new RuleSetFactoryCompatibility();
/** The instance with the built-in filters for the modified PMD rules. */
static final RuleSetFactoryCompatibility DEFAULT = new RuleSetFactoryCompatibility();
static {
// PMD 5.3.0
DEFAULT.addFilterRuleRenamed("java", "design", "UncommentedEmptyMethod", "UncommentedEmptyMethodBody");
DEFAULT.addFilterRuleRemoved("java", "controversial", "BooleanInversion");
// PMD 5.3.1
DEFAULT.addFilterRuleRenamed("java", "design", "UseSingleton", "UseUtilityClass");
// PMD 5.4.0
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyCatchBlock");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyIfStatement");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyWhileStmt");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyTryBlock");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyFinallyBlock");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptySwitchStatements");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptySynchronizedBlock");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyStatementNotInLoop");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyInitializer");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyStatementBlock");
DEFAULT.addFilterRuleMoved("java", "basic", "empty", "EmptyStaticInitializer");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UnnecessaryConversionTemporary");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UnnecessaryReturn");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UnnecessaryFinalModifier");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UselessOverridingMethod");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UselessOperationOnImmutable");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UnusedNullCheckInEquals");
DEFAULT.addFilterRuleMoved("java", "basic", "unnecessary", "UselessParentheses");
// PMD 5.6.0
DEFAULT.addFilterRuleRenamed("java", "design", "AvoidConstantsInterface", "ConstantsInInterface");
// unused/UnusedModifier moved AND renamed, order is important!
DEFAULT.addFilterRuleMovedAndRenamed("java", "unusedcode", "UnusedModifier", "unnecessary", "UnnecessaryModifier");
// PMD 6.0.0
DEFAULT.addFilterRuleMoved("java", "controversial", "unnecessary", "UnnecessaryParentheses");
DEFAULT.addFilterRuleRenamed("java", "unnecessary", "UnnecessaryParentheses", "UselessParentheses");
DEFAULT.addFilterRuleMoved("java", "typeresolution", "coupling", "LooseCoupling");
DEFAULT.addFilterRuleMoved("java", "typeresolution", "clone", "CloneMethodMustImplementCloneable");
DEFAULT.addFilterRuleMoved("java", "typeresolution", "imports", "UnusedImports");
DEFAULT.addFilterRuleMoved("java", "typeresolution", "strictexception", "SignatureDeclareThrowsException");
DEFAULT.addFilterRuleRenamed("java", "naming", "MisleadingVariableName", "MIsLeadingVariableName");
DEFAULT.addFilterRuleRenamed("java", "unnecessary", "UnnecessaryFinalModifier", "UnnecessaryModifier");
DEFAULT.addFilterRuleRenamed("java", "empty", "EmptyStaticInitializer", "EmptyInitializer");
// GuardLogStatementJavaUtil moved and renamed...
DEFAULT.addFilterRuleMovedAndRenamed("java", "logging-java", "GuardLogStatementJavaUtil", "logging-jakarta-commons", "GuardLogStatement");
DEFAULT.addFilterRuleRenamed("java", "logging-jakarta-commons", "GuardDebugLogging", "GuardLogStatement");
}
private static final Logger LOG = LoggerFactory.getLogger(RuleSetFactoryCompatibility.class);
private final List<RuleSetFilter> filters = new ArrayList<>();
void addFilterRuleMovedAndRenamed(String language, String oldRuleset, String oldName, String newRuleset, String newName) {
filters.add(RuleSetFilter.ruleMoved(language, oldRuleset, newRuleset, oldName));
filters.add(RuleSetFilter.ruleRenamed(language, newRuleset, oldName, newName));
}
void addFilterRuleRenamed(String language, String ruleset, String oldName, String newName) {
filters.add(RuleSetFilter.ruleRenamed(language, ruleset, oldName, newName));
}
void addFilterRuleMoved(String language, String oldRuleset, String newRuleset, String ruleName) {
filters.add(RuleSetFilter.ruleMoved(language, oldRuleset, newRuleset, ruleName));
}
void addFilterRuleRemoved(String language, String ruleset, String name) {
filters.add(RuleSetFilter.ruleRemoved(language, ruleset, name));
}
@Nullable String applyRef(String ref) {
return applyRef(ref, false);
}
/**
* Returns the new rule ref, or null if the rule was deleted. Returns
* the argument if no replacement is needed.
*
* @param ref Original ref
* @param warn Whether to output a warning if a replacement is done
*/
public @Nullable String applyRef(String ref, boolean warn) {
String result = ref;
for (RuleSetFilter filter : filters) {
result = filter.applyRef(result, warn);
if (result == null) {
return null;
}
}
return result;
}
/**
* Returns the new rule name, or null if the rule was deleted. Returns
* the argument if no replacement is needed.
*
* @param rulesetRef Ruleset name
* @param excludeName Original excluded name
* @param warn Whether to output a warning if a replacement is done
*/
public @Nullable String applyExclude(String rulesetRef, String excludeName, boolean warn) {
String result = excludeName;
for (RuleSetFilter filter : filters) {
result = filter.applyExclude(rulesetRef, result, warn);
if (result == null) {
return null;
}
}
return result;
}
private static final class RuleSetFilter {
private static final String MOVED_MESSAGE = "The rule \"{1}\" has been moved from ruleset \"{0}\" to \"{2}\". Please change your ruleset!";
private static final String RENAMED_MESSAGE = "The rule \"{1}\" has been renamed to \"{3}\". Please change your ruleset!";
private static final String REMOVED_MESSAGE = "The rule \"{1}\" in ruleset \"{0}\" has been removed from PMD and no longer exists. Please change your ruleset!";
private final String ruleRef;
private final String oldRuleset;
private final String oldName;
private final String newRuleset;
private final String newName;
private final String logMessage;
private RuleSetFilter(String oldRuleset,
String oldName,
@Nullable String newRuleset,
@Nullable String newName,
String logMessage) {
this.oldRuleset = oldRuleset;
this.oldName = oldName;
this.newRuleset = newRuleset;
this.newName = newName;
this.logMessage = logMessage;
this.ruleRef = oldRuleset + "/" + oldName;
}
public static RuleSetFilter ruleRenamed(String language, String ruleset, String oldName, String newName) {
String base = "rulesets/" + language + "/" + ruleset + ".xml";
return new RuleSetFilter(base, oldName, base, newName, RENAMED_MESSAGE);
}
public static RuleSetFilter ruleMoved(String language, String oldRuleset, String newRuleset, String ruleName) {
String base = "rulesets/" + language + "/";
return new RuleSetFilter(base + oldRuleset + ".xml", ruleName,
base + newRuleset + ".xml", ruleName,
MOVED_MESSAGE);
}
public static RuleSetFilter ruleRemoved(String language, String ruleset, String name) {
String oldRuleset = "rulesets/" + language + "/" + ruleset + ".xml";
return new RuleSetFilter(oldRuleset, name,
null, null,
REMOVED_MESSAGE);
}
@Nullable String applyExclude(String ref, String name, boolean warn) {
if (oldRuleset.equals(ref)
&& oldName.equals(name)
&& oldRuleset.equals(newRuleset)) {
if (warn) {
warn();
}
return newName;
}
return name;
}
@Nullable String applyRef(String ref, boolean warn) {
if (ref.equals(this.ruleRef)) {
if (warn) {
warn();
}
if (newName != null) {
return newRuleset + "/" + newName;
} else {
// deleted
return null;
}
}
return ref;
}
private void warn() {
if (LOG.isWarnEnabled()) {
String log = MessageFormat.format(logMessage, oldRuleset, oldName, newRuleset, newName);
LOG.warn("Applying rule set filter: {}", log);
}
}
}
}
| 10,176 | 43.635965 | 168 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/LanguageModuleBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.StringUtil;
/**
* Base class for language modules.
*
* @author Clément Fournier
*/
public abstract class LanguageModuleBase implements Language {
private final LanguageMetadata meta;
private final List<LanguageVersion> distinctVersions;
private final Map<String, LanguageVersion> byName;
private final LanguageVersion defaultVersion;
private final Set<String> dependencies;
/**
* Construct a module instance using the given metadata. The metadata must
* be properly constructed.
*
* @throws IllegalStateException If the metadata is invalid (eg missing extensions or name or no versions)
*/
protected LanguageModuleBase(LanguageMetadata metadata) {
this.meta = metadata;
metadata.validate();
this.dependencies = Collections.unmodifiableSet(metadata.dependencies);
List<LanguageVersion> versions = new ArrayList<>();
Map<String, LanguageVersion> byName = new HashMap<>();
LanguageVersion defaultVersion = null;
if (metadata.versionMetadata.isEmpty()) {
throw new IllegalStateException("No versions for '" + getId() + "'");
}
int i = 0;
for (LanguageMetadata.LangVersionMetadata versionId : metadata.versionMetadata) {
String versionStr = versionId.name;
LanguageVersion languageVersion = new LanguageVersion(this, versionStr, i++);
versions.add(languageVersion);
checkNotPresent(byName, versionStr);
byName.put(versionStr, languageVersion);
for (String alias : versionId.aliases) {
checkNotPresent(byName, alias);
byName.put(alias, languageVersion);
}
if (versionId.isDefault) {
if (defaultVersion != null) {
throw new IllegalStateException(
"Default version already set to " + defaultVersion + ", cannot set it to " + languageVersion);
}
defaultVersion = languageVersion;
}
}
this.byName = Collections.unmodifiableMap(byName);
this.distinctVersions = Collections.unmodifiableList(versions);
this.defaultVersion = Objects.requireNonNull(defaultVersion, "No default version for " + getId());
}
private static void checkNotPresent(Map<String, ?> map, String alias) {
if (map.containsKey(alias)) {
throw new IllegalArgumentException("Version key '" + alias + "' is duplicated");
}
}
@Override
public List<LanguageVersion> getVersions() {
return distinctVersions;
}
@Override
public LanguageVersion getDefaultVersion() {
return defaultVersion;
}
@Override
public LanguageVersion getVersion(String version) {
return byName.get(version);
}
@Override
public Set<String> getVersionNamesAndAliases() {
return Collections.unmodifiableSet(byName.keySet());
}
@Override
public Set<String> getDependencies() {
return dependencies;
}
@Override
public String getName() {
return meta.name;
}
@Override
public String getShortName() {
return meta.getShortName();
}
@Override
public String getTerseName() {
return meta.id;
}
@Override
public @NonNull List<String> getExtensions() {
return Collections.unmodifiableList(meta.extensions);
}
@Override
public String toString() {
return getTerseName();
}
@Override
public int compareTo(Language o) {
return getName().compareTo(o.getName());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LanguageModuleBase other = (LanguageModuleBase) obj;
return Objects.equals(getId(), other.getId());
}
/**
* Metadata about a language, basically a builder pattern for the
* language instance.
*
* <p>Some of the metadata are mandatory:
* <ul>
* <li>The id ({@link #withId(String)})
* <li>The display name ({@link #name(String)})
* <li>The file extensions ({@link #extensions(String, String...)}
* </ul>
*
*/
protected static final class LanguageMetadata {
/** Language IDs should be conventional Java package names. */
private static final Pattern VALID_LANG_ID = Pattern.compile("[a-z][_a-z0-9]*");
private static final Pattern SPACE_PAT = Pattern.compile("\\s");
private final Set<String> dependencies = new HashSet<>();
private String name;
private @Nullable String shortName;
private final @NonNull String id;
private List<String> extensions;
private final List<LangVersionMetadata> versionMetadata = new ArrayList<>();
private LanguageMetadata(@NonNull String id) {
this.id = id;
if (!VALID_LANG_ID.matcher(id).matches()) {
throw new IllegalArgumentException(
"ID '" + id + "' is not a valid language ID (should match " + VALID_LANG_ID + ").");
}
}
void validate() {
AssertionUtil.validateState(name != null, "Language " + id + " should have a name");
AssertionUtil.validateState(
extensions != null, "Language " + id + " has not registered any file extensions");
}
String getShortName() {
return shortName == null ? name : shortName;
}
/**
* Factory method to create an ID.
*
* @param id The language id. Must be usable as a Java package name segment,
* ie be lowercase, alphanumeric, starting with a letter.
*
* @return A builder for language metadata
*
* @throws IllegalArgumentException If the parameter is not a valid ID
* @throws NullPointerException If the parameter is null
*/
public static LanguageMetadata withId(@NonNull String id) {
return new LanguageMetadata(id);
}
/**
* Record the {@linkplain Language#getName() display name} of
* the language. This also serves as the {@linkplain Language#getShortName() short name}
* if {@link #shortName(String)} is not called.
*
* @param name Display name of the language
*
* @throws NullPointerException If the parameter is null
* @throws IllegalArgumentException If the parameter is not a valid language name
*/
public LanguageMetadata name(@NonNull String name) {
AssertionUtil.requireParamNotNull("name", name);
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Not a valid language name: " + StringUtil.inSingleQuotes(name));
}
this.name = name.trim();
return this;
}
/**
* Record the {@linkplain Language#getShortName() short name} of the language.
*
* @param shortName Short name of the language
*
* @throws NullPointerException If the parameter is null
* @throws IllegalArgumentException If the parameter is not a valid language name
*/
public LanguageMetadata shortName(@NonNull String shortName) {
AssertionUtil.requireParamNotNull("short name", shortName);
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Not a valid language name: " + StringUtil.inSingleQuotes(name));
}
this.shortName = shortName.trim();
return this;
}
/**
* Record the {@linkplain Language#getExtensions() extensions}
* assigned to the language. Extensions should not start with a period
* {@code .}.
*
* @param e1 First extensions
* @param others Other extensions (optional)
*
* @throws NullPointerException If any extension is null
*/
public LanguageMetadata extensions(String e1, String... others) {
this.extensions = new ArrayList<>(setOf(e1, others));
AssertionUtil.requireContainsNoNullValue("extensions", this.extensions);
return this;
}
/**
* Record the {@linkplain Language#getExtensions() extensions}
* assigned to the language. Extensions should not start with a period
* {@code .}. At least one extension must be provided.
*
* @param extensions the extensions
*
* @throws NullPointerException If any extension is null
* @throws IllegalArgumentException If no extensions are provided
*/
public LanguageMetadata extensions(Collection<String> extensions) {
this.extensions = new ArrayList<>(new HashSet<>(extensions));
AssertionUtil.requireContainsNoNullValue("extensions", this.extensions);
if (this.extensions.isEmpty()) {
throw new IllegalArgumentException("At least one extension is required.");
}
return this;
}
/**
* Add a new version by its name.
*
* @param name Version name. Must contain no spaces.
* @param aliases Additional names that are mapped to this version. Must contain no spaces.
*
* @throws NullPointerException If any parameter is null
* @throws IllegalArgumentException If the name or aliases are empty or contain spaces
*/
public LanguageMetadata addVersion(String name, String... aliases) {
versionMetadata.add(new LangVersionMetadata(name, Arrays.asList(aliases), false));
return this;
}
/**
* Add a new version by its name and make it the default version.
*
* @param name Version name. Must contain no spaces.
* @param aliases Additional names that are mapped to this version. Must contain no spaces.
*
* @throws NullPointerException If any parameter is null
* @throws IllegalArgumentException If the name or aliases are empty or contain spaces
*/
public LanguageMetadata addDefaultVersion(String name, String... aliases) {
versionMetadata.add(new LangVersionMetadata(name, Arrays.asList(aliases), true));
return this;
}
/**
* Record that this language depends on another language, identified
* by its id. This means any {@link LanguageProcessorRegistry} that
* contains a processor for this language is asserted upon construction
* to also contain a processor for the language depended on.
*
* @param id ID of the language to depend on.
*
* @throws NullPointerException If any parameter is null
* @throws IllegalArgumentException If the name is not a valid language Id
*/
public LanguageMetadata dependsOnLanguage(String id) {
if (!VALID_LANG_ID.matcher(id).matches()) {
throw new IllegalArgumentException(
"ID '" + id + "' is not a valid language ID (should match " + VALID_LANG_ID + ").");
}
dependencies.add(id);
return this;
}
static final class LangVersionMetadata {
final String name;
final List<String> aliases;
final boolean isDefault;
private LangVersionMetadata(String name, List<String> aliases, boolean isDefault) {
checkVersionName(name);
for (String alias : aliases) {
checkVersionName(alias);
}
this.name = name;
this.aliases = aliases;
this.isDefault = isDefault;
}
private static void checkVersionName(String name) {
if (StringUtils.isBlank(name) || SPACE_PAT.matcher(name).find()) {
throw new IllegalArgumentException("Invalid version name: " + StringUtil.inSingleQuotes(name));
}
}
}
}
}
| 13,247 | 34.140584 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/LanguageVersionHandler.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.ViolationSuppressor;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
import net.sourceforge.pmd.reporting.ViolationDecorator;
import net.sourceforge.pmd.util.designerbindings.DesignerBindings;
import net.sourceforge.pmd.util.designerbindings.DesignerBindings.DefaultDesignerBindings;
/**
* Interface for obtaining the classes necessary for checking source files of a
* specific language.
*
* @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be
*/
public interface LanguageVersionHandler {
/**
* Get the XPathHandler.
*/
default XPathHandler getXPathHandler() {
return XPathHandler.noFunctionDefinitions();
}
/**
* Returns the parser instance.
*/
Parser getParser();
/**
* Returns the language-specific violation decorator.
*/
default ViolationDecorator getViolationDecorator() {
return ViolationDecorator.noop();
}
/**
* Returns additional language-specific violation suppressors.
* These take precedence over the default suppressors (eg nopmd comment),
* but do not replace them.
*/
default List<ViolationSuppressor> getExtraViolationSuppressors() {
return Collections.emptyList();
}
/**
* Returns the metrics provider for this language version,
* or null if it has none.
*
* Note: this is experimental, ie unstable until 7.0.0, after
* which it will probably be promoted to a stable API. For
* instance the return type will probably be changed to an Optional.
*/
@Experimental
default LanguageMetricsProvider getLanguageMetricsProvider() {
return null;
}
/**
* Returns the designer bindings for this language version.
* Null is not an acceptable result, use {@link DefaultDesignerBindings#getInstance()}
* instead.
*
* @since 6.20.0
*/
@Experimental
default DesignerBindings getDesignerBindings() {
return DefaultDesignerBindings.getInstance();
}
}
| 2,399 | 26.906977 | 90 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/Language.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
/**
* Represents a language module, and provides access to language-specific
* functionality. You can get a language instance from a {@link LanguageRegistry}.
*
* <p>Language instances are extensions to the core of PMD. They can be
* registered with a {@linkplain ServiceLoader service file} so that the
* PMD CLI automatically finds them on the classpath.
*
* <p>Instances of this interface are stateless and immutable after construction.
* They mostly provide metadata about the language, like ID, name and different
* versions that are supported. Languages can create a {@link LanguageProcessor}
* to actually run the analysis. That object can maintain analysis-global state,
* and has a proper lifecycle.
*
* @see LanguageVersion
* @see LanguageVersionDiscoverer
*/
public interface Language extends Comparable<Language> {
/**
* Returns the full name of this Language. This is generally the name of this
* language without the use of acronyms, but possibly some capital letters,
* eg {@code "Java"}. It's suitable for displaying in a GUI.
*
* @return The full name of this language.
*/
String getName();
/**
* Returns the short name of this language. This is the commonly
* used short form of this language's name, perhaps an acronym,
* but possibly with special characters.
*
* @return The short name of this language.
*/
String getShortName();
/**
* Returns the terse name of this language. This is a short, alphanumeric,
* lowercase name, eg {@code "java"}. It's used to identify the language
* in the ruleset XML, and is also in the package name of the language
* module.
*
* @return The terse name of this language.
*/
String getTerseName();
/**
* Returns the ID of this language. This is a short, alphanumeric,
* lowercase name, eg {@code "java"}. It's used to identify the language
* in the ruleset XML, and is also in the package name of the language
* module.
*
* @return The ID of this language.
*/
default String getId() {
return getTerseName();
}
/**
* Returns the list of file extensions associated with this language.
* This list is unmodifiable. Extensions do not have a '.' prefix.
*
* @return A list of file extensions.
*/
List<String> getExtensions();
/**
* Returns whether this language handles the given file extension.
* The comparison is done ignoring case.
*
* @param extensionWithoutDot A file extension (without '.' prefix)
*
* @return <code>true</code> if this language handles the extension,
* <code>false</code> otherwise.
*/
default boolean hasExtension(String extensionWithoutDot) {
return getExtensions().contains(extensionWithoutDot);
}
/**
* Returns an ordered list of supported versions for this language.
*
* @return All supported language versions.
*/
List<LanguageVersion> getVersions();
/**
* Returns the latest language version. May not be the
* {@linkplain #getDefaultVersion() default}.
*
* @return The latest language version
*/
default LanguageVersion getLatestVersion() {
List<LanguageVersion> versions = getVersions();
return versions.get(versions.size() - 1);
}
/**
* Returns a complete set of supported version names for this language
* including all aliases.
*
* @return All supported language version names and aliases.
*/
Set<String> getVersionNamesAndAliases();
/**
* Returns true if a language version with the given {@linkplain LanguageVersion#getVersion() version string}
* is registered. Then, {@link #getVersion(String) getVersion} will return a non-null value.
*
* @param version A version string
*
* @return True if the version string is known
*/
default boolean hasVersion(String version) {
return getVersion(version) != null;
}
/**
* Returns the language version with the given {@linkplain LanguageVersion#getVersion() version string}.
* Returns null if no such version exists.
*
* @param version A language version string.
*
* @return The corresponding LanguageVersion, {@code null} if the
* version string is not recognized.
*/
default LanguageVersion getVersion(String version) {
for (LanguageVersion v : getVersions()) {
if (v.getVersion().equals(version)) {
return v;
}
}
return null;
}
/**
* Returns the default language version for this language.
* This is an arbitrary choice made by the PMD product, and can change
* between PMD releases. Every language has a default version.
*
* @return The current default language version for this language.
*/
LanguageVersion getDefaultVersion();
/**
* Creates a new bundle of properties that will serve to configure
* the {@link LanguageProcessor} for this language. The returned
* bundle must have all relevant properties already declared.
*
* @return A new set of properties
*/
default LanguagePropertyBundle newPropertyBundle() {
return new LanguagePropertyBundle(this);
}
/**
* Create a new {@link LanguageProcessor} for this language, given
* a property bundle with configuration. The bundle was created by
* this instance using {@link #newPropertyBundle()}. It can be assumed
* that the bundle will never be mutated anymore, and this method
* takes ownership of it.
*
* @param bundle A bundle of properties created by this instance.
*
* @return A new language processor
*/
LanguageProcessor createProcessor(LanguagePropertyBundle bundle);
/**
* Returns a set of the IDs of languages that this language instance
* depends on. Whenever this language is loaded into a {@link LanguageProcessorRegistry},
* those dependencies need to be loaded as well.
*/
Set<String> getDependencies();
}
| 6,375 | 32.036269 | 113 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.