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/main/java/net/sourceforge/pmd/reporting/package-info.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * Logic about reporting: violations, suppression etc. * * <p>TODO move {@link net.sourceforge.pmd.Report}, {@link net.sourceforge.pmd.RuleViolation}, * {@link net.sourceforge.pmd.RuleContext}, {@link net.sourceforge.pmd.ViolationSuppressor} * into this package */ package net.sourceforge.pmd.reporting;
402
30
94
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Report.GlobalReportBuilderListener; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.ast.FileAnalysisException; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.util.AssertionUtil; import net.sourceforge.pmd.util.BaseResultProducingCloseable; import net.sourceforge.pmd.util.CollectionUtil; /** * Listens to an analysis. This object produces new {@link FileAnalysisListener} * for each analyzed file, which themselves handle events like violations, * in their file. Thread-safety is required. * * <p>The listener may provide a {@link ListenerInitializer} to get context * information on the analysis before events start occurring. * * <p>Listeners are the main API to obtain results of an analysis. The * entry point of the API ({@link PmdAnalysis}) runs a set of rules on * a set of files. What happens to events is entirely the concern of the * listener. * * <p>A useful kind of listener are the ones produced by {@linkplain Renderer#newListener() renderers}. * Another is the {@linkplain GlobalReportBuilderListener report builder}. */ public interface GlobalAnalysisListener extends AutoCloseable { /** * Provides an initializer to gather analysis context before events * start occurring. * * @return A listener initializer. */ default ListenerInitializer initializer() { return ListenerInitializer.noop(); } /** * Returns a file listener that will handle events occurring during * the analysis of the given file. The new listener may receive events * as soon as this method returns. The analysis stops when the * {@link FileAnalysisListener#close()} method is called. * * @implSpec This routine may be called from several threads at once and * needs to be thread-safe. But the returned listener will only be * used in a single thread. * * @param file File to be processed * * @return A new listener * * @throws IllegalStateException If {@link #close()} has already been called. * This prevents manipulation mistakes but is * not a strong requirement. */ FileAnalysisListener startFileAnalysis(TextFile file); /** * Notify the implementation that the analysis ended, ie all files * have been processed. This listener won't be used after this is * called. * * <p>Closing listeners multiple times should have no effect. * * @throws Exception If an error occurs. For example, renderer listeners * may throw {@link IOException} */ @Override void close() throws Exception; /** * Record a configuration error. This happens before the start of * file analysis. */ default void onConfigError(ConfigurationError error) { // do nothing } /** * A listener that does nothing. */ static GlobalAnalysisListener noop() { return NoopAnalysisListener.INSTANCE; } /** * Produce an analysis listener that forwards all events to the given * listeners. * * @param listeners Listeners * * @return A composed listener * * @throws IllegalArgumentException If the parameter is empty * @throws NullPointerException If the parameter or any of its elements is null */ static GlobalAnalysisListener tee(Collection<? extends GlobalAnalysisListener> listeners) { AssertionUtil.requireParamNotNull("Listeners", listeners); AssertionUtil.requireContainsNoNullValue("Listeners", listeners); final class TeeListener implements GlobalAnalysisListener { final List<GlobalAnalysisListener> myList; TeeListener(List<GlobalAnalysisListener> myList) { this.myList = myList; } @Override public ListenerInitializer initializer() { return ListenerInitializer.tee(CollectionUtil.map(myList, GlobalAnalysisListener::initializer)); } @Override public FileAnalysisListener startFileAnalysis(TextFile file) { return FileAnalysisListener.tee(CollectionUtil.map(myList, it -> it.startFileAnalysis(file))); } @Override public void close() throws Exception { Exception composed = IOUtil.closeAll(myList); if (composed != null) { throw composed; } } @Override public String toString() { return "TeeListener{" + myList + '}'; } @Override public void onConfigError(ConfigurationError error) { myList.forEach(l -> l.onConfigError(error)); } } // Flatten other tee listeners in the list // This prevents suppressed exceptions from being chained too deep if they occur in close() List<GlobalAnalysisListener> myList = listeners.stream() .flatMap(l -> l instanceof TeeListener ? ((TeeListener) l).myList.stream() : Stream.of(l)) .filter(l -> !(l instanceof NoopAnalysisListener)) .collect(CollectionUtil.toUnmodifiableList()); if (myList.isEmpty()) { return noop(); } else if (myList.size() == 1) { return myList.iterator().next(); } return new TeeListener(myList); } /** * A listener that just counts recorded violations. The result is * available after the listener is closed ({@link #getResult()}). */ final class ViolationCounterListener extends BaseResultProducingCloseable<Integer> implements GlobalAnalysisListener { private final AtomicInteger count = new AtomicInteger(); @Override protected Integer getResultImpl() { return count.get(); } @Override public FileAnalysisListener startFileAnalysis(TextFile file) { return violation -> count.incrementAndGet(); } } /** * A listener that throws processing errors when they occur. They * are all thrown as {@link FileAnalysisException}s. Config errors * are ignored. * * <p>This will abort the analysis on the first error, which is * usually not what you want to do, but is useful for unit tests. */ static GlobalAnalysisListener exceptionThrower() { class ExceptionThrowingListener implements GlobalAnalysisListener { @Override public FileAnalysisListener startFileAnalysis(TextFile file) { FileId filename = file.getFileId(); // capture the filename instead of the file return new FileAnalysisListener() { @Override public void onRuleViolation(RuleViolation violation) { // do nothing } @Override public void onError(ProcessingError error) throws FileAnalysisException { throw FileAnalysisException.wrap(filename, error.getError().getMessage(), error.getError()); } @Override public String toString() { return "ExceptionThrower"; } }; } @Override public void close() { // nothing to do } } return new ExceptionThrowingListener(); } }
8,298
34.165254
122
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/NoopListenerInitializer.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; final class NoopListenerInitializer implements ListenerInitializer { static final NoopListenerInitializer INSTANCE = new NoopListenerInitializer(); private NoopListenerInitializer() { // singleton } @Override public String toString() { return "Noop"; } }
426
20.35
82
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ReportStats.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; /** * Summarized info about a report. * * @author Clément Fournier */ public final class ReportStats { private final int numErrors; private final int numViolations; ReportStats(int numErrors, int numViolations) { this.numErrors = numErrors; this.numViolations = numViolations; } public static ReportStats empty() { return new ReportStats(0, 0); } public int getNumErrors() { return numErrors; } public int getNumViolations() { return numViolations; } @Override public String toString() { return "ReportStats{numErrors=" + numErrors + ", numViolations=" + numViolations + '}'; } }
818
20
95
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ViolationDecorator.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.ast.Node; /** * Adds additional key/value pairs to a violation in a language-specific manner. * The keys are completely free. {@link RuleViolation} defines some of these keys. */ @FunctionalInterface public interface ViolationDecorator { /** * Compute additional key/value pairs about the violation that should be * reflected in {@link RuleViolation#getAdditionalInfo()}. This additional * info should be accumulated into the {@code additionalInfo} parameter. * * @param violationNode The node on which the violation was reported * @param additionalInfo Accumulator */ void decorate(Node violationNode, Map<String, String> additionalInfo); static Map<String, String> apply(ViolationDecorator decorator, Node violationNode) { Map<String, String> additionalInfo = new HashMap<>(); decorator.decorate(violationNode, additionalInfo); if (!additionalInfo.isEmpty()) { return Collections.unmodifiableMap(additionalInfo); } else { return Collections.emptyMap(); } } /** * Apply several decorators in a chain. */ static ViolationDecorator chain(List<? extends ViolationDecorator> list) { return (node, map) -> { for (ViolationDecorator decorator : list) { decorator.decorate(node, map); } }; } static ViolationDecorator noop() { return (node, map) -> { }; } }
1,774
30.140351
88
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ReportStatsListener.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import java.util.concurrent.atomic.AtomicInteger; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.util.BaseResultProducingCloseable; /** * Collects summarized info about a PMD run. * * @author Clément Fournier */ public final class ReportStatsListener extends BaseResultProducingCloseable<ReportStats> implements GlobalAnalysisListener { private final AtomicInteger numErrors = new AtomicInteger(0); private final AtomicInteger numViolations = new AtomicInteger(0); @Override public FileAnalysisListener startFileAnalysis(TextFile file) { return new FileAnalysisListener() { // this object does not need thread-safety so we avoid using atomics, // except during the merge. private int numErrors = 0; private int numViolations = 0; @Override public void onRuleViolation(RuleViolation violation) { numViolations++; } @Override public void onError(ProcessingError error) { numErrors++; } @Override public void close() { if (numErrors > 0) { ReportStatsListener.this.numErrors.addAndGet(this.numErrors); } if (numViolations > 0) { ReportStatsListener.this.numViolations.addAndGet(this.numViolations); } } }; } @Override protected ReportStats getResultImpl() { return new ReportStats( numErrors.get(), numViolations.get() ); } }
1,869
28.21875
124
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** * Strategy to render a {@link FileId} into a display name. This is used * to prettify file names in renderers using relative paths eg. * * @author Clément Fournier */ public interface FileNameRenderer { /** * Return a display name for the given file id. * @param fileId A file id * @return A display name */ String getDisplayName(@NonNull FileId fileId); default String getDisplayName(@NonNull TextFile textFile) { return getDisplayName(textFile.getFileId()); } }
811
22.882353
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** * @author Clément Fournier */ public class ConfigurableFileNameRenderer implements FileNameRenderer { private final List<Path> relativizeRootPaths = new ArrayList<>(); /** * Add a prefix that is used to relativize file paths as their display name. * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a * display name of {@code main/java/org/foo.java}. * * <p>This only matters for files added from a {@link Path} object. * * @param path Path with which to relativize */ public void relativizeWith(Path path) { this.relativizeRootPaths.add(Objects.requireNonNull(path)); this.relativizeRootPaths.sort(Comparator.naturalOrder()); } @Override public String getDisplayName(@NonNull FileId fileId) { String localDisplayName = getLocalDisplayName(fileId); FileId parent = fileId.getParentFsPath(); if (parent != null) { return getDisplayName(parent) + "!" + localDisplayName; } return localDisplayName; } private String getLocalDisplayName(FileId file) { if (!relativizeRootPaths.isEmpty()) { return getDisplayName(file, relativizeRootPaths); } return file.getOriginalPath(); } private static int countSegments(String best) { return StringUtils.countMatches(best, File.separatorChar); } private static final Pattern PATH_SEP_PAT = Pattern.compile("[/\\\\]"); // both input paths represent absolute paths private static String relativizePath(Path base, String other) { assert base.isAbsolute() : "Expected an absolute path: " + base; // If the second path starts with C:\, remove the C: part for // consistency. int windowsDriveEndIndex = other.indexOf(':'); if (windowsDriveEndIndex != -1 && windowsDriveEndIndex < other.length() - 1) { other = other.substring(windowsDriveEndIndex + 1); } String[] otherSegments = PATH_SEP_PAT.split(other); int prefixLength = 0; // We remove 1 because since 'other' is absolute it always starts // with the empty string. int maxi = Math.min(base.getNameCount(), otherSegments.length - 1); while (prefixLength < maxi // here we add 1 for the same reason vvvvvvvvvvvvvvvv && base.getName(prefixLength).toString().equals(otherSegments[prefixLength + 1])) { prefixLength++; } if (prefixLength == 0) { return other; } List<String> relative = new ArrayList<>(); for (int i = prefixLength; i < base.getNameCount(); i++) { relative.add(".."); } relative.addAll(Arrays.asList(otherSegments).subList(prefixLength + 1, otherSegments.length)); return String.join(File.separator, relative); } /** Return whether the path is the root path (/). */ private static boolean isFileSystemRoot(Path root) { return root.isAbsolute() && root.getNameCount() == 0; } /** * Return the textfile's display name. Takes the shortest path we * can construct from the relativize roots. * * <p>package private for test only</p> */ static String getDisplayName(FileId file, List<Path> relativizeRoots) { final String fileAbsPath = file.getAbsolutePath(); String best = fileAbsPath; for (Path root : relativizeRoots) { if (isFileSystemRoot(root)) { // Absolutize the path. Since the relativize roots are // sorted by ascending length, this should be the first in the list // (so another root can override it). best = fileAbsPath; continue; } String relative = relativizePath(root.toAbsolutePath(), fileAbsPath); if (countSegments(relative) < countSegments(best)) { best = relative; } } return best; } }
4,763
35.090909
102
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/Reportable.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.document.FileLocation; /** * Interface implemented by those objects that can be the target of * a {@link RuleViolation}. {@link Node}s and {@link GenericToken tokens} * implement this interface. * * TODO use this in RuleViolationFactory */ public interface Reportable { // todo add optional method to get the nearest node, to implement // suppression that depends on tree structure (eg annotations) for // not just nodes, for example, for comments or individual tokens /** * Returns the location at which this element should be reported. * * <p>Use this instead of {@link #getBeginColumn()}/{@link #getBeginLine()}, etc. */ FileLocation getReportLocation(); /** * Gets the line where the token's region begins * * @deprecated Use {@link #getReportLocation()} */ @Deprecated @DeprecatedUntil700 default int getBeginLine() { return getReportLocation().getStartPos().getLine(); } /** * Gets the line where the token's region ends * * @deprecated Use {@link #getReportLocation()} */ @Deprecated @DeprecatedUntil700 default int getEndLine() { return getReportLocation().getEndPos().getLine(); } /** * Gets the column offset from the start of the begin line where the token's region begins * * @deprecated Use {@link #getReportLocation()} */ @Deprecated @DeprecatedUntil700 default int getBeginColumn() { return getReportLocation().getStartPos().getColumn(); } /** * Gets the column offset from the start of the end line where the token's region ends * * @deprecated Use {@link #getReportLocation()} */ @Deprecated @DeprecatedUntil700 default int getEndColumn() { return getReportLocation().getEndPos().getColumn(); } }
2,220
25.440476
94
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/NoopAnalysisListener.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import net.sourceforge.pmd.lang.document.TextFile; /** * @author Clément Fournier */ final class NoopAnalysisListener implements GlobalAnalysisListener { static final NoopAnalysisListener INSTANCE = new NoopAnalysisListener(); private NoopAnalysisListener() { } @Override public FileAnalysisListener startFileAnalysis(TextFile file) { return FileAnalysisListener.noop(); } @Override public void close() { // do nothing } }
611
19.4
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/NoopFileListener.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.reporting; import net.sourceforge.pmd.RuleViolation; final class NoopFileListener implements FileAnalysisListener { static final NoopFileListener INSTANCE = new NoopFileListener(); private NoopFileListener() { // singleton } @Override public void onRuleViolation(RuleViolation violation) { // do nothing } @Override public String toString() { return "Noop"; } }
544
19.185185
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/annotation/DeprecatedUntil700.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.annotation; /** * Tags a deprecated member that should not be removed before PMD 7.0.0. * Such members were made deprecated on the PMD 7 development branch and * may be kept for backwards compatibility on the day of the PMD 7 release, * because the replacement API cannot be backported to PMD 6. */ public @interface DeprecatedUntil700 { }
462
29.866667
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/annotation/ReservedSubclassing.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Indicates that subclassing this type is not publicly * supported API. Abstract methods may be added or removed * at any time, which could break binary compatibility with * existing implementors. Protected methods are also part of * the private API of this type. * * <p>The API that is not inheritance-specific (unless {@linkplain InternalApi noted otherwise}, * all public members), is still public API and will remain binary- * compatible between major releases. * * <p>Types tagged with this annotation will remain supported * until 7.0.0, at which point no guarantees will be maintained * about the stability of the inheritance hierarchy for external * clients. * * <p>This should be used for example for base rule classes that * are meant to be used in PMD only, or for AST-related interfaces * and abstract classes. * * @since 6.7.0 */ @Target(ElementType.TYPE) @Documented public @interface ReservedSubclassing { }
1,197
30.526316
96
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/annotation/Experimental.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.annotation; import java.lang.annotation.Documented; /** * Indicates the feature is in experimental state: its existence, signature * or behavior might change without warning from one release to the next. * The only clients that are "safe" using experimental APIs are the sources * of PMD itself. * * @since 6.7.0 */ @Documented public @interface Experimental { /** A reason given for the experimental status. */ String value() default ""; }
577
22.12
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/annotation/InternalApi.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.annotation; import java.lang.annotation.Documented; /** * Tags API members that are not publicly supported API. * Such members may be removed, renamed, moved, or otherwise * broken at any time and should not be relied upon outside * of the main PMD codebase. * * <p>Members and types tagged with this annotation will remain * supported until 7.0.0, after which some will be moved to internal * packages, or will see their visibility reduced. * * @since 6.7.0 */ // NOTE: use @Deprecated with this annotation to raise a compiler warning until 7.0.0 @Documented public @interface InternalApi { }
725
26.923077
85
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/Slf4jSimpleConfiguration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import org.slf4j.event.Level; public final class Slf4jSimpleConfiguration { private static final String SIMPLE_LOGGER_FACTORY_CLASS = "org.slf4j.impl.SimpleLoggerFactory"; private static final String SIMPLE_LOGGER_CLASS = "org.slf4j.impl.SimpleLogger"; private static final String SIMPLE_LOGGER_CONFIGURATION = "org.slf4j.impl.SimpleLoggerConfiguration"; private static final String PMD_ROOT_LOGGER = "net.sourceforge.pmd"; private Slf4jSimpleConfiguration() { } public static void reconfigureDefaultLogLevel(Level level) { if (!isSimpleLogger()) { // do nothing, not even set system properties, if not Simple Logger is in use return; } if (level != null) { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", level.toString()); } // Call SimpleLogger.init() by reflection. // Alternatively: move the CLI related classes into an own module, add // slf4j-simple as a compile dependency and create a PmdSlf4jSimpleFriend class in // the package org.slf4j.simple to gain access to this package-private init method. // // SimpleLogger.init() will reevaluate the configuration from the system properties or // simplelogger.properties file. ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); ClassLoader classLoader = loggerFactory.getClass().getClassLoader(); try { Class<?> simpleLoggerClass = classLoader.loadClass(SIMPLE_LOGGER_CLASS); Method initMethod = simpleLoggerClass.getDeclaredMethod("init"); initMethod.setAccessible(true); initMethod.invoke(null); int newDefaultLogLevel = getDefaultLogLevelInt(simpleLoggerClass); Field currentLogLevelField = simpleLoggerClass.getDeclaredField("currentLogLevel"); currentLogLevelField.setAccessible(true); Method levelStringMethod = simpleLoggerClass.getDeclaredMethod("recursivelyComputeLevelString"); levelStringMethod.setAccessible(true); Method stringToLevelMethod = classLoader.loadClass(SIMPLE_LOGGER_CONFIGURATION) .getDeclaredMethod("stringToLevel", String.class); stringToLevelMethod.setAccessible(true); // Change the logging level of loggers that were already created. // For this we fetch the map of name to logger that is stored in the logger factory, // then set the log level field of each logger via reflection. // The new log level is determined similar to the constructor of SimpleLogger, that // means, configuration params are being considered. Class<?> loggerFactoryClass = classLoader.loadClass(SIMPLE_LOGGER_FACTORY_CLASS); Field loggerMapField = loggerFactoryClass.getDeclaredField("loggerMap"); loggerMapField.setAccessible(true); // we checked previously, that loggerFactory instanceof SimpleLoggerFactory // see #isSimpleLogger() @SuppressWarnings("unchecked") Map<String, Logger> loggerMap = (Map<String, Logger>) loggerMapField.get(loggerFactory); for (Logger logger : loggerMap.values()) { if (logger.getName().startsWith(PMD_ROOT_LOGGER) && simpleLoggerClass.isAssignableFrom(logger.getClass())) { String newConfiguredLevel = (String) levelStringMethod.invoke(logger); int newLogLevel = newDefaultLogLevel; if (newConfiguredLevel != null) { newLogLevel = (int) stringToLevelMethod.invoke(null, newConfiguredLevel); } currentLogLevelField.set(logger, newLogLevel); } } } catch (ReflectiveOperationException | ClassCastException ex) { System.err.println("Error while initializing logging: " + ex); } } private static int getDefaultLogLevelInt(Class<?> simpleLoggerClass) throws ReflectiveOperationException { Field configParamsField = simpleLoggerClass.getDeclaredField("CONFIG_PARAMS"); configParamsField.setAccessible(true); Object configParams = configParamsField.get(null); Field defaultLogLevelField = configParams.getClass().getDeclaredField("defaultLogLevel"); defaultLogLevelField.setAccessible(true); return (int) defaultLogLevelField.get(configParams); } public static Level getDefaultLogLevel() { Logger rootLogger = LoggerFactory.getLogger(PMD_ROOT_LOGGER); // check the lowest log level first if (rootLogger.isTraceEnabled()) { return Level.TRACE; } if (rootLogger.isDebugEnabled()) { return Level.DEBUG; } if (rootLogger.isInfoEnabled()) { return Level.INFO; } if (rootLogger.isWarnEnabled()) { return Level.WARN; } if (rootLogger.isErrorEnabled()) { return Level.ERROR; } return Level.INFO; } public static void disableLogging(Class<?> clazz) { if (!isSimpleLogger()) { // do nothing, not even set system properties, if not Simple Logger is in use return; } System.setProperty("org.slf4j.simpleLogger.log." + clazz.getName(), "off"); } public static boolean isSimpleLogger() { try { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); Class<?> loggerFactoryClass = loggerFactory.getClass().getClassLoader().loadClass(SIMPLE_LOGGER_FACTORY_CLASS); return loggerFactoryClass.isAssignableFrom(loggerFactory.getClass()); } catch (ClassNotFoundException e) { // not slf4j simple logger return false; } } public static void installJulBridge() { if (!SLF4JBridgeHandler.isInstalled()) { SLF4JBridgeHandler.removeHandlersForRootLogger(); // removes any existing ConsoleLogger SLF4JBridgeHandler.install(); } } }
6,520
42.765101
123
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/LanguageServiceBase.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeSet; import net.sourceforge.pmd.annotation.InternalApi; @InternalApi public abstract class LanguageServiceBase<T> { protected interface NameExtractor<T> { String getName(T language); } protected final Set<T> languages; protected final Map<String, T> languagesByName; protected final Map<String, T> languagesByTerseName; protected LanguageServiceBase(final Class<T> serviceType, final Comparator<T> comparator, final NameExtractor<T> nameExtractor, final NameExtractor<T> terseNameExtractor) { Set<T> sortedLangs = new TreeSet<>(comparator); // Use current class' classloader instead of the threads context classloader, see https://github.com/pmd/pmd/issues/1788 ServiceLoader<T> languageLoader = ServiceLoader.load(serviceType, getClass().getClassLoader()); Iterator<T> iterator = languageLoader.iterator(); while (true) { // this loop is weird, but both hasNext and next may throw ServiceConfigurationError, // it's more robust that way try { if (iterator.hasNext()) { T language = iterator.next(); sortedLangs.add(language); } else { break; } } catch (UnsupportedClassVersionError | ServiceConfigurationError e) { // Some languages require java8 and are therefore only available // if java8 or later is used as runtime. System.err.println("Ignoring language for PMD: " + e.toString()); } } // using a linked hash map to maintain insertion order languages = Collections.unmodifiableSet(new LinkedHashSet<>(sortedLangs)); // TODO there may be languages with duplicate names Map<String, T> byName = new LinkedHashMap<>(); Map<String, T> byTerseName = new LinkedHashMap<>(); for (T language : sortedLangs) { byName.put(nameExtractor.getName(language), language); byTerseName.put(terseNameExtractor.getName(language), language); } languagesByName = Collections.unmodifiableMap(byName); languagesByTerseName = Collections.unmodifiableMap(byTerseName); } }
2,686
37.942029
128
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/LogMessages.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal; /** * @author Clément Fournier */ public final class LogMessages { private LogMessages() { // utility class } public static String errorDetectedMessage(int errors, String program) { String anError = errors == 1 ? "An error" : errors + " errors"; return anError + " occurred while executing " + program + ".\n" + "Run in verbose mode to see a stack-trace.\n" + "If you think this is a bug in " + program + ", please report this issue at https://github.com/pmd/pmd/issues/new/choose\n" + "If you do so, please include a stack-trace, the code sample\n" + " causing the issue, and details about your run configuration."; } @Deprecated public static String runWithHelpFlagMessage() { return "Run with --help for command line help."; } }
984
30.774194
92
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/SystemProps.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal; public final class SystemProps { public static final String PMD_ERROR_RECOVERY = "pmd.error_recovery"; private SystemProps() { } /** * In error recovery mode errors like StackOverflowError or AssertionErrors are logged * and the execution continues. * These exceptions mean, that something went really wrong while executing and * depending on where the error occurred, the internal state might be corrupted * or not. Hence, it might work to continue and "ignore" (just log) the error * or we'll see more problems when continuing. That's why error recovery mode * is not enabled by default. * <p> * The System Property is called {@code pmd.error_recovery}. */ public static boolean isErrorRecoveryMode() { return System.getProperty(PMD_ERROR_RECOVERY) != null; } }
976
32.689655
90
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.IOException; import java.io.Reader; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.sql.SQLException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.lang.document.FileCollector; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.util.database.DBMSMetadata; import net.sourceforge.pmd.util.database.DBURI; import net.sourceforge.pmd.util.database.SourceObject; import net.sourceforge.pmd.util.log.MessageReporter; import net.sourceforge.pmd.util.log.internal.ErrorsAsWarningsReporter; /** * @author Clément Fournier */ public final class FileCollectionUtil { private static final Logger LOG = LoggerFactory.getLogger(FileCollectionUtil.class); private FileCollectionUtil() { } public static void collectFiles(PMDConfiguration configuration, FileCollector collector) { if (configuration.getSourceEncoding() != null) { collector.setCharset(configuration.getSourceEncoding()); } collectFiles(collector, configuration.getInputPathList()); if (configuration.getUri() != null) { collectDB(collector, configuration.getUri()); } if (configuration.getInputFile() != null) { collectFileList(collector, configuration.getInputFile()); } if (configuration.getIgnoreFile() != null) { // This is to be able to interpret the log (will report 'adding' xxx) LOG.debug("Now collecting files to exclude."); // errors like "excluded file does not exist" are reported as warnings. // todo better reporting of *where* exactly the path is MessageReporter mutedLog = new ErrorsAsWarningsReporter(collector.getReporter()); try (FileCollector excludeCollector = collector.newCollector(mutedLog)) { collectFileList(excludeCollector, configuration.getIgnoreFile()); collector.exclude(excludeCollector); } } } public static void collectFiles(FileCollector collector, List<Path> filePaths) { for (Path rootLocation : filePaths) { try { addRoot(collector, rootLocation); } catch (IOException e) { collector.getReporter().errorEx("Error collecting " + rootLocation, e); } } } public static void collectFileList(FileCollector collector, Path fileList) { LOG.debug("Reading file list {}.", fileList); if (!Files.exists(fileList)) { collector.getReporter().error("No such file {}", fileList); return; } List<Path> filePaths; try { filePaths = FileUtil.readFilelistEntries(fileList); } catch (IOException e) { collector.getReporter().errorEx("Error reading {}", new Object[] { fileList }, e); return; } collectFiles(collector, filePaths); } private static void addRoot(FileCollector collector, Path path) throws IOException { String pathStr = path.toString(); if (!Files.exists(path)) { collector.getReporter().error("No such file {0}", path); return; } if (Files.isDirectory(path)) { LOG.debug("Adding directory {}.", path); collector.addDirectory(path); } else if (pathStr.endsWith(".zip") || pathStr.endsWith(".jar")) { collector.addZipFileWithContent(path); } else if (Files.isRegularFile(path)) { LOG.debug("Adding regular file {}.", path); collector.addFile(path); } else { LOG.debug("Ignoring {}: not a regular file or directory", path); } } public static void collectDB(FileCollector collector, URI uri) { try { LOG.debug("Connecting to {}", uri); DBURI dbUri = new DBURI(uri); DBMSMetadata dbmsMetadata = new DBMSMetadata(dbUri); LOG.trace("DBMSMetadata retrieved"); List<SourceObject> sourceObjectList = dbmsMetadata.getSourceObjectList(); LOG.trace("Located {} database source objects", sourceObjectList.size()); for (SourceObject sourceObject : sourceObjectList) { String falseFilePath = sourceObject.getPseudoFileName(); LOG.trace("Adding database source object {}", falseFilePath); try (Reader sourceCode = dbmsMetadata.getSourceCode(sourceObject)) { String source = IOUtil.readToString(sourceCode); collector.addSourceFile(FileId.fromPathLikeString(falseFilePath), source); } catch (SQLException ex) { collector.getReporter().warnEx("Cannot get SourceCode for {} - skipping ...", new Object[] { falseFilePath }, ex); } } } catch (ClassNotFoundException e) { collector.getReporter().errorEx("Cannot get files from DB - probably missing database JDBC driver", e); } catch (Exception e) { collector.getReporter().errorEx("Cannot get files from DB - ''{}''", new Object[] { uri }, e); } } }
5,543
37.5
115
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/ShortFilenameUtil.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public final class ShortFilenameUtil { private ShortFilenameUtil() { } /** * Determines the filename that should be used in the report depending on the * option "shortnames". If the option is enabled, then the filename in the report * is without the directory prefix of the directories, that have been analyzed. * If the option "shortnames" is not enabled, then the inputFileName is returned as-is. * * @param inputPathPrefixes * @param inputFileName * @return * */ public static String determineFileName(List<String> inputPathPrefixes, String inputFileName) { for (final String prefix : inputPathPrefixes) { final Path prefPath = Paths.get(prefix).toAbsolutePath(); final String prefPathString = prefPath.toString(); if (inputFileName.startsWith(prefPathString)) { if (prefPath.toFile().isDirectory()) { return trimAnyPathSep(inputFileName.substring(prefPathString.length())); } else { if (inputFileName.indexOf(File.separatorChar) == -1) { return inputFileName; } return trimAnyPathSep(inputFileName.substring(prefPathString.lastIndexOf(File.separatorChar))); } } } return inputFileName; } private static String trimAnyPathSep(String name) { return name != null && name.charAt(0) == File.separatorChar ? name.substring(1) : name; } }
1,784
33.326923
115
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/ClasspathClassLoader.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sourceforge.pmd.util.AssertionUtil; /** * Create a ClassLoader which loads classes using a CLASSPATH like String. If * the String looks like a URL to a file (e.g. starts with <code>file://</code>) * the file will be read with each line representing an path on the classpath. * * @author Edwin Chan */ public class ClasspathClassLoader extends URLClassLoader { private static final Logger LOG = LoggerFactory.getLogger(ClasspathClassLoader.class); static { registerAsParallelCapable(); } public ClasspathClassLoader(List<File> files, ClassLoader parent) throws IOException { super(fileToURL(files), parent); } public ClasspathClassLoader(String classpath, ClassLoader parent) throws IOException { super(initURLs(classpath), parent); } private static URL[] fileToURL(List<File> files) throws IOException { List<URL> urlList = new ArrayList<>(); for (File f : files) { urlList.add(f.toURI().toURL()); } return urlList.toArray(new URL[0]); } private static URL[] initURLs(String classpath) { AssertionUtil.requireParamNotNull("classpath", classpath); final List<URL> urls = new ArrayList<>(); try { if (classpath.startsWith("file:")) { // Treat as file URL addFileURLs(urls, new URL(classpath)); } else { // Treat as classpath addClasspathURLs(urls, classpath); } } catch (IOException e) { throw new IllegalArgumentException("Cannot prepend classpath " + classpath + "\n" + e.getMessage(), e); } return urls.toArray(new URL[0]); } private static void addClasspathURLs(final List<URL> urls, final String classpath) throws MalformedURLException { StringTokenizer toker = new StringTokenizer(classpath, File.pathSeparator); while (toker.hasMoreTokens()) { String token = toker.nextToken(); LOG.debug("Adding classpath entry: <{}>", token); urls.add(createURLFromPath(token)); } } private static void addFileURLs(List<URL> urls, URL fileURL) throws IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(fileURL.openStream()))) { String line; while ((line = in.readLine()) != null) { LOG.debug("Read classpath entry line: <{}>", line); line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { LOG.debug("Adding classpath entry: <{}>", line); urls.add(createURLFromPath(line)); } } } } private static URL createURLFromPath(String path) throws MalformedURLException { File file = new File(path); return file.getAbsoluteFile().toURI().normalize().toURL(); } @Override public String toString() { return getClass().getSimpleName() + "[[" + StringUtils.join(getURLs(), ":") + "] parent: " + getParent() + ']'; } @Override public URL getResource(String name) { // Override to make it child-first. This is the method used by // pmd-java's type resolution to fetch classes, instead of loadClass. Objects.requireNonNull(name); URL url = findResource(name); if (url == null) { // note this will actually call back into this.findResource, but // we can't avoid this as the super implementation uses JDK internal // stuff that we can't copy down here. return super.getResource(name); } return url; } @Override protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { try { // checking local c = findClass(name); } catch (final ClassNotFoundException | SecurityException e) { // checking parent // This call to loadClass may eventually call findClass again, in case the parent doesn't find anything. c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } } }
5,164
33.433333
124
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/PredicateUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import static net.sourceforge.pmd.util.AssertionUtil.requireOver1; import static net.sourceforge.pmd.util.AssertionUtil.requireParamNotNull; import java.util.Collection; import java.util.function.Predicate; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.util.AssertionUtil; /** * Utility class for working with {@link Predicate}. */ public final class PredicateUtil { private PredicateUtil() { // utility class } /** A predicate that always returns false. */ public static <T> Predicate<T> never() { return t -> false; } /** A predicate that always returns true. */ public static <T> Predicate<T> always() { return t -> true; } /** * Returns a case-insensitive predicate for files with the given extensions. * * @throws NullPointerException If the extensions array is null */ public static Predicate<String> getFileExtensionFilter(String... extensions) { requireParamNotNull("extensions", extensions); // TODO add first parameter to mandate that. This affects a // constructor of AbstractLanguage and should be done later requireOver1("Extension count", extensions.length); return new FileExtensionFilter(true, extensions); } /** * Returns a predicate that tests if the name of a file matches the * given string filter. The returned predicate normalizes backslashes * ({@code '\'}) to {@code '/'} to be more easily cross-platform. * * @param filter A predicate on the file name * * @return A predicate on files */ public static Predicate<String> toNormalizedFileFilter(final Predicate<? super String> filter) { return path -> { path = path.replace('\\', '/'); return filter.test(path); }; } /** * Builds a string filter using a set of include and exclude regular * expressions. A string S matches the predicate if either * <ul> * <li>1. no exclude regex matches S, or * <li>2. some include regex matches S * </ul> * In other words, include patterns override exclude patterns. * * @param includeRegexes Regular expressions overriding the excludes. * @param excludeRegexes Regular expressions filtering strings out. * * @return A predicate for strings. */ public static Predicate<String> buildRegexFilterIncludeOverExclude(@NonNull Collection<Pattern> includeRegexes, @NonNull Collection<Pattern> excludeRegexes) { AssertionUtil.requireParamNotNull("includeRegexes", includeRegexes); AssertionUtil.requireParamNotNull("excludeRegexes", includeRegexes); return union(excludeRegexes).negate().or(union(includeRegexes)); } private static Predicate<String> union(Collection<Pattern> regexes) { return regexes.stream().map(PredicateUtil::matchesRegex).reduce(never(), Predicate::or); } private static Predicate<String> matchesRegex(Pattern regex) { return s -> regex.matcher(s).matches(); } }
3,330
33.340206
117
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/IOUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.Closeable; import java.io.File; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.Nullable; /** * * @author Brian Remedios */ public final class IOUtil { /** * Unicode BOM character. Replaces commons io ByteOrderMark. */ public static final char UTF_BOM = '\uFEFF'; /** Conventional return value for readers. */ public static final int EOF = -1; private static final int BUFFER_SIZE = 8192; private IOUtil() { } /** * Creates a writer that writes to stdout using the system default charset. * * @return a writer, never null * * @see #createWriter(String) * @see #createWriter(Charset, String) */ public static Writer createWriter() { return createWriter(null); } /** * Gets the current default charset. * * <p>In contrast to {@link Charset#defaultCharset()}, the result is not cached, * so that in unit tests, the charset can be changed. * @return */ private static Charset getDefaultCharset() { String csn = AccessController.doPrivileged(new PrivilegedAction<String>() { @Override public String run() { return System.getProperty("file.encoding"); } }); try { return Charset.forName(csn); } catch (UnsupportedCharsetException e) { return StandardCharsets.UTF_8; } } /** * Creates a writer that writes to the given file or to stdout. * The file is created if it does not exist. * * <p>Warning: This writer always uses the system default charset. * * @param reportFile the file name (optional) * * @return the writer, never null */ public static Writer createWriter(String reportFile) { return createWriter(getDefaultCharset(), reportFile); } /** * Creates a writer that writes to the given file or to stdout. * The file is created if it does not exist. * * <p>Unlike {@link #createWriter(String)}, this method always uses * the given charset. Even for writing to stdout. It never * falls back to the default charset.</p> * * @param charset the charset to be used (required) * @param reportFile the file name (optional) * @return */ public static Writer createWriter(Charset charset, String reportFile) { try { if (StringUtils.isBlank(reportFile)) { return new OutputStreamWriter(new FilterOutputStream(System.out) { @Override public void close() { // avoid closing stdout, simply flush try { out.flush(); } catch (IOException ignored) { // Nothing left to do } } @Override public void write(byte[] b, int off, int len) throws IOException { /* * FilterOutputStream iterates over each byte, asking subclasses to provide more efficient implementations * It therefore negates any such optimizations that the underlying stream actually may implement. */ out.write(b, off, len); } }, charset); } Path path = new File(reportFile).toPath().toAbsolutePath(); Files.createDirectories(path.getParent()); // ensure parent dir exists // this will create the file if it doesn't exist return Files.newBufferedWriter(path, charset); } catch (IOException e) { throw new IllegalArgumentException(e); } } public static void tryCloseClassLoader(ClassLoader classLoader) { if (classLoader instanceof Closeable) { closeQuietly((Closeable) classLoader); } } /** * Close all closeable resources in order. If any exception occurs, * it is saved and returned. If more than one exception occurs, the * following are accumulated as suppressed exceptions in the first. * * @param closeables Resources to close * * @return An exception, or null if no 'close' routine threw */ @SuppressWarnings("PMD.CloseResource") // false-positive public static Exception closeAll(Collection<? extends AutoCloseable> closeables) { Exception composed = null; for (AutoCloseable it : closeables) { try { it.close(); } catch (Exception e) { if (composed == null) { composed = e; } else { composed.addSuppressed(e); } } } return composed; } /** * Ensure that the closeables are closed. In the end, throws the * pending exception if not null, or the exception retuned by {@link #closeAll(Collection)} * if not null. If both are non-null, adds one of them to the suppress * list of the other, and throws that one. */ public static void ensureClosed(List<? extends AutoCloseable> toClose, @Nullable Exception pendingException) throws Exception { Exception closeException = closeAll(toClose); if (closeException != null) { if (pendingException != null) { closeException.addSuppressed(pendingException); throw closeException; } // else no exception at all } else if (pendingException != null) { throw pendingException; } } // The following methods are taken from Apache Commons IO. // The dependency was removed from PMD 6 because it had a security issue, // and upgrading was not possible without upgrading to Java 8. // See https://github.com/pmd/pmd/pull/3968 // TODO PMD 7: consider bringing back commons-io and cleaning this class up. public static void closeQuietly(Closeable closeable) { try { closeable.close(); } catch (IOException ignored) { // ignored } } public static byte[] toByteArray(InputStream stream) throws IOException { byte[] result = new byte[0]; byte[] buffer = new byte[BUFFER_SIZE]; int count = stream.read(buffer); while (count > -1) { byte[] newResult = new byte[result.length + count]; System.arraycopy(result, 0, newResult, 0, result.length); System.arraycopy(buffer, 0, newResult, result.length, count); result = newResult; count = stream.read(buffer); } return result; } public static long skipFully(InputStream stream, long n) throws IOException { if (n < 0) { throw new IllegalArgumentException(); } long bytesToSkip = n; byte[] buffer = new byte[(int) Math.min(BUFFER_SIZE, bytesToSkip)]; while (bytesToSkip > 0) { int count = stream.read(buffer, 0, (int) Math.min(BUFFER_SIZE, bytesToSkip)); if (count < 0) { // reached eof break; } bytesToSkip -= count; } return n - bytesToSkip; } public static String normalizePath(String path) { Path path1 = Paths.get(path); path1.isAbsolute(); String normalized = path1.normalize().toString(); if (normalized.contains("." + File.separator) || normalized.contains(".." + File.separator) || "".equals(normalized)) { return null; } return normalized; } public static boolean equalsNormalizedPaths(String path1, String path2) { return Objects.equals(normalizePath(path1), normalizePath(path2)); } public static String getFilenameExtension(String name) { String filename = Paths.get(name).getFileName().toString(); int dot = filename.lastIndexOf('.'); if (dot > -1) { return filename.substring(dot + 1); } return ""; } public static String getFilenameBase(String name) { String filename = Paths.get(name).getFileName().toString(); int dot = filename.lastIndexOf('.'); if (dot > -1) { return filename.substring(0, dot); } return filename; } public static void copy(InputStream from, OutputStream to) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int count = from.read(buffer); while (count > -1) { to.write(buffer, 0, count); count = from.read(buffer); } } public static void copy(Reader from, Writer to) throws IOException { char[] buffer = new char[BUFFER_SIZE]; int count = from.read(buffer); while (count > -1) { to.write(buffer, 0, count); count = from.read(buffer); } } public static String readFileToString(File file) throws IOException { return readFileToString(file, Charset.defaultCharset()); } public static String readFileToString(File file, Charset charset) throws IOException { byte[] bytes = Files.readAllBytes(file.toPath()); return charset.decode(ByteBuffer.wrap(bytes)).toString(); } public static String readToString(Reader reader) throws IOException { StringBuilder sb = new StringBuilder(BUFFER_SIZE); char[] buffer = new char[BUFFER_SIZE]; int count = reader.read(buffer); while (count > -1) { sb.append(buffer, 0, count); count = reader.read(buffer); } return sb.toString(); } public static String readToString(InputStream stream, Charset charset) throws IOException { byte[] bytes = toByteArray(stream); return charset.decode(ByteBuffer.wrap(bytes)).toString(); } public static InputStream fromReader(Reader reader) throws IOException { class ReaderInputStream extends InputStream { private final Reader reader; private final CharBuffer charBuffer = CharBuffer.allocate(BUFFER_SIZE); private final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); private final CharsetEncoder encoder; private boolean eof; ReaderInputStream(Reader reader) { this.reader = reader; encoder = Charset.defaultCharset().newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); charBuffer.clear(); byteBuffer.clear(); byteBuffer.flip(); // byte buffer is empty at the beginning, no bytes read yet } @Override public int read() throws IOException { if (!byteBuffer.hasRemaining()) { if (charBuffer.hasRemaining() && !eof) { int count = reader.read(charBuffer); eof = count == -1; } byteBuffer.clear(); charBuffer.flip(); encoder.encode(charBuffer, byteBuffer, eof); byteBuffer.flip(); charBuffer.compact(); } if (byteBuffer.hasRemaining()) { return byteBuffer.get(); } return -1; } @Override public int available() throws IOException { return byteBuffer.remaining(); } @Override public void close() throws IOException { reader.close(); } } return new ReaderInputStream(reader); } public static OutputStream fromWriter(Writer writer, String encoding) throws UnsupportedCharsetException { class WriterOutputStream extends OutputStream { private final Writer writer; private final CharsetDecoder decoder; private final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); private final CharBuffer charBuffer = CharBuffer.allocate(BUFFER_SIZE); WriterOutputStream(Writer writer, String encoding) throws UnsupportedCharsetException { this.writer = writer; Charset charset = Charset.forName(encoding); decoder = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); byteBuffer.clear(); charBuffer.clear(); } @Override public void write(int b) throws IOException { if (!byteBuffer.hasRemaining()) { decodeByteBuffer(false); } byteBuffer.put((byte) b); } @Override public void flush() throws IOException { decodeByteBuffer(false); } private void decodeByteBuffer(boolean isClosing) throws IOException { byteBuffer.flip(); charBuffer.clear(); decoder.decode(byteBuffer, charBuffer, isClosing); writer.write(charBuffer.array(), 0, charBuffer.position()); writer.flush(); byteBuffer.compact(); } @Override public void close() throws IOException { flush(); decodeByteBuffer(true); writer.close(); } } return new WriterOutputStream(writer, encoding); } /** * <p> * Input stream that skips an optional byte order mark at the beginning * of the stream. Whether the stream had a byte order mark (encoded in either UTF-8, * UTF-16LE or UTF-16BE) can be checked with {@link #hasBom()}. The corresponding * charset can be retrieved with {@link #getBomCharsetName()}. * </p> * * <p> * If the stream didn't had a BOM, then no bytes are skipped. * </p> */ public static class BomAwareInputStream extends FilterInputStream { private byte[] begin; int beginIndex; private String charset; public BomAwareInputStream(InputStream in) { super(in); begin = determineBom(); } private byte[] determineBom() { byte[] bytes = new byte[3]; try { int count = in.read(bytes); if (count == 3 && bytes[0] == (byte) 0xef && bytes[1] == (byte) 0xbb && bytes[2] == (byte) 0xbf) { charset = StandardCharsets.UTF_8.name(); return new byte[0]; // skip all 3 bytes } else if (count >= 2 && bytes[0] == (byte) 0xfe && bytes[1] == (byte) 0xff) { charset = StandardCharsets.UTF_16BE.name(); return new byte[] { bytes[2] }; } else if (count >= 2 && bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xfe) { charset = StandardCharsets.UTF_16LE.name(); return new byte[] { bytes[2] }; } else if (count == 3) { return bytes; } if (count < 0) { return new byte[0]; } byte[] read = new byte[count]; for (int i = 0; i < count; i++) { read[i] = bytes[i]; } return read; } catch (IOException e) { throw new RuntimeException(e); } } @Override public int read() throws IOException { if (beginIndex < begin.length) { return begin[beginIndex++]; } return super.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { if (beginIndex < begin.length) { int count = 0; for (; count < len && beginIndex < begin.length; beginIndex++) { b[off + count] = begin[beginIndex]; count++; } return count; } return super.read(b, off, len); } public boolean hasBom() { return charset != null; } public String getBomCharsetName() { return charset; } } }
17,742
33.927165
130
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileFinder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * A utility class for finding files within a directory. */ public class FileFinder { private FilenameFilter filter; /** * Searches for files in a given directory. * * @param dir the directory to search files * @param filter the filename filter that can optionally be passed to get files that match this filter * @param recurse search for files recursively or not * @return list of files from the given directory */ public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); return files; } /** * Implements a tail recursive file scanner */ private void scanDirectory(File dir, List<File> list, boolean recurse) { File[] candidates = dir.listFiles(filter); if (candidates == null) { return; } Arrays.sort(candidates, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getPath().compareToIgnoreCase(o2.getPath()); } }); for (File tmp : candidates) { if (tmp.isDirectory()) { if (recurse) { scanDirectory(tmp, list, true); } } else { list.add(tmp); } } } }
1,744
26.265625
107
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/BaseCloseable.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.Closeable; import java.io.IOException; public abstract class BaseCloseable implements Closeable { protected boolean open = true; protected final void ensureOpen() throws IOException { if (!open) { throw new IOException("Closed " + this); } } protected final void ensureOpenIllegalState() throws IllegalStateException { if (!open) { throw new IllegalStateException("Closed " + this); } } /** * Noop if called several times. Thread-safe. */ @Override public void close() throws IOException { if (open) { synchronized (this) { if (open) { open = false; doClose(); } } } } /** Called at most once. */ protected abstract void doClose() throws IOException; }
1,029
21.888889
80
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/ExceptionContextDefaultImpl.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.util.List; import java.util.Set; import org.apache.commons.lang3.exception.ExceptionContext; import org.apache.commons.lang3.tuple.Pair; public interface ExceptionContextDefaultImpl<T extends Throwable & ExceptionContext> extends ExceptionContext { ExceptionContext getExceptionContext(); T getThrowable(); @Override default T addContextValue(String label, Object value) { getExceptionContext().addContextValue(label, value); return getThrowable(); } @Override default ExceptionContext setContextValue(String label, Object value) { return getExceptionContext().addContextValue(label, value); } @Override default List<Object> getContextValues(String label) { return getExceptionContext().getContextValues(label); } @Override default Object getFirstContextValue(String label) { return getExceptionContext().getFirstContextValue(label); } @Override default Set<String> getContextLabels() { return getExceptionContext().getContextLabels(); } @Override default List<Pair<String, Object>> getContextEntries() { return getExceptionContext().getContextEntries(); } @Override default String getFormattedExceptionMessage(String baseMessage) { return getExceptionContext().getFormattedExceptionMessage(baseMessage); } }
1,520
26.654545
111
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; /** * This is a utility class for working with Files. */ public final class FileUtil { private FileUtil() { } /** * Helper method to get a filename without its extension * * @param fileName * String * @return String */ public static String getFileNameWithoutExtension(String fileName) { String name = fileName; int index = fileName.lastIndexOf('.'); if (index != -1) { name = fileName.substring(0, index); } return name; } /** * Normalizes the filename by taking the casing into account, e.g. on * Windows, the filename is changed to lowercase only. * * @param fileName * the file name * @return the normalized file name */ public static String normalizeFilename(String fileName) { if (fileName != null && File.separatorChar == '\\') { // windows return fileName.toLowerCase(Locale.ROOT); } return fileName; } public static @NonNull Path toExistingPath(String root) throws FileNotFoundException { Path file = Paths.get(root); if (!Files.exists(file)) { throw new FileNotFoundException(root); } return file; } /** * Handy method to find a certain pattern into a file. While this method * lives in the FileUtils, it was designed with with unit test in mind (to * check result redirected into a file) * * @param file * @param pattern * @return */ public static boolean findPatternInFile(final File file, final String pattern) { Pattern regexp = Pattern.compile(pattern); Matcher matcher = regexp.matcher(""); try { for (String line : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) { matcher.reset(line); // reset the input if (matcher.find()) { return true; } } } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new RuntimeException(e); } return false; } /** * Reads the file, which contains the filelist. This is used for the * command line arguments --filelist/-filelist for both PMD and CPD. * The separator in the filelist is a comma and/or newlines. * * @param filelist the file which contains the list of path names * * @return a list of file paths * * @throws IOException if the file couldn't be read */ public static List<Path> readFilelistEntries(Path filelist) throws IOException { return Files.readAllLines(filelist).stream() .flatMap(it -> Arrays.stream(it.split(","))) .map(String::trim) .filter(StringUtils::isNotBlank) .map(Paths::get) .collect(Collectors.toList()); } }
3,655
28.015873
91
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileExtensionFilter.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.internal.util; import java.util.Locale; import java.util.function.Predicate; import org.apache.commons.lang3.StringUtils; final class FileExtensionFilter implements Predicate<String> { private final String[] extensions; private final boolean ignoreCase; /** * Matches any files with the given extensions, optionally ignoring case. */ FileExtensionFilter(boolean ignoreCase, String... extensions) { this.extensions = extensions; this.ignoreCase = ignoreCase; if (ignoreCase) { for (int i = 0; i < this.extensions.length; i++) { this.extensions[i] = this.extensions[i].toUpperCase(Locale.ROOT); } } } @Override public boolean test(String path) { boolean accept = extensions == null; if (!accept) { for (String extension : extensions) { boolean matches = ignoreCase ? StringUtils.endsWithIgnoreCase(path, extension) : path.endsWith(extension); if (matches) { accept = true; break; } } } return accept; } }
1,334
27.404255
81
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; 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.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * <p> * A console renderer with optional color support under *nix systems. * </p> * * <pre> * * file: ./src/gilot/Test.java * src: Test.java:12 * rule: AtLeastOneConstructor * msg: Each class should declare at least one constructor * code: public class Test * * * file: ./src/gilot/log/format/LogInterpreter.java * src: LogInterpreter.java:317 * rule: AvoidDuplicateLiterals * msg: The same String literal appears 4 times in this file; the first occurrence is on line 317 * code: logger.error( "missing attribute 'app_arg' in rule '" + ((Element)element.getParent()).getAttributeValue( "name" ) + "'" ); * * src: LogInterpreter.java:317 * rule: AvoidDuplicateLiterals * msg: The same String literal appears 5 times in this file; the first occurrence is on line 317 * code: logger.error( "missing attribute 'app_arg' in rule '" + ((Element)element.getParent()).getAttributeValue( "name" ) + "'" ); * * warnings: 3 * </pre> * <p> * Colorization is turned on by supplying -D<b>pmd.color</b> - any value other * than '0' or 'false', enables color - including an empty value (''). <b>Nota * Bene:</b> colorization is atm only supported under *nix terminals accepting * ansi escape sequences, such as xterm, rxvt et cetera. * </p> */ public class TextColorRenderer extends AbstractAccumulatingRenderer { public static final String NAME = "textcolor"; // What? TODO 7.0.0 Use a boolean property // TODO should the "textcolor" renderer really support "optional" colors? // either use text or textcolor... // This property is really weird, the standard boolean properties // are false unless value is exactly "true", this one is true unless // "false" or "0"... public static final PropertyDescriptor<String> COLOR = PropertyFactory.stringProperty("color").desc("Enables colors with anything other than 'false' or '0'.").defaultValue("yes").build(); private static final String SYSTEM_PROPERTY_PMD_COLOR = "pmd.color"; /** * Directory from where java was invoked. */ private String pwd; private String yellowBold = ""; private String whiteBold = ""; private String redBold = ""; private String red = ""; private String cyan = ""; private String green = ""; private String colorReset = ""; public TextColorRenderer() { // This Renderer was originally submitted by Adrian Papari and was // called the "PapariTextRenderer" pre-PMD 5.0. super(NAME, "Text format, with color support (requires ANSI console support, e.g. xterm, rxvt, etc.)."); definePropertyDescriptor(COLOR); } @Override public String defaultFileExtension() { return "txt"; } /** * Enables colors on *nix systems - not windows. Color support depends on * the pmd.color property, which should be set with the -D option during * execution - a set value other than 'false' or '0' enables color. * <p/> * btw, is it possible to do this on windows (ie; console colors)? */ private void initializeColorsIfSupported() { if (isPropertyEnabled(getProperty(COLOR)) || isPropertyEnabled(System.getProperty(SYSTEM_PROPERTY_PMD_COLOR))) { this.yellowBold = "\u001B[1;33m"; this.whiteBold = "\u001B[1;37m"; this.redBold = "\u001B[1;31m"; this.red = "\u001B[0;31m"; this.green = "\u001B[0;32m"; this.cyan = "\u001B[0;36m"; this.colorReset = "\u001B[0m"; } } private boolean isPropertyEnabled(String property) { return property != null && !("0".equals(property) || "false".equalsIgnoreCase(property)); } @Override public void outputReport(Report report) throws IOException { StringBuilder buf = new StringBuilder(500); buf.append(System.lineSeparator()); initializeColorsIfSupported(); String lastFile = null; int numberOfErrors = 0; int numberOfWarnings = 0; for (RuleViolation rv : report.getViolations()) { buf.setLength(0); numberOfWarnings++; String nextFile = determineFileName(rv.getFileId()); if (!nextFile.equals(lastFile)) { lastFile = nextFile; buf.append(this.yellowBold) .append("*") .append(this.colorReset) .append(" file: ") .append(this.whiteBold) .append(this.getRelativePath(lastFile)) .append(this.colorReset) .append(System.lineSeparator()); } buf.append(this.green) .append(" src: ") .append(this.cyan) .append(lastFile.substring(lastFile.lastIndexOf(File.separator) + 1)) .append(this.colorReset).append(":") .append(this.cyan) .append(rv.getBeginLine()) .append(rv.getEndLine() == -1 ? "" : ":" + rv.getEndLine()) .append(this.colorReset) .append(System.lineSeparator()); buf.append(this.green) .append(" rule: ") .append(this.colorReset) .append(rv.getRule().getName()) .append(System.lineSeparator()); buf.append(this.green) .append(" msg: ") .append(this.colorReset) .append(rv.getDescription()) .append(System.lineSeparator()); buf.append(this.green) .append(" code: ") .append(this.colorReset) .append(this.getLine(lastFile, rv.getBeginLine())) .append(System.lineSeparator()) .append(System.lineSeparator()); writer.write(buf.toString()); } writer.println(); writer.println(); writer.println("Summary:"); writer.println(); for (Map.Entry<String, Integer> entry : getCountSummary(report).entrySet()) { buf.setLength(0); String key = entry.getKey(); buf.append(key).append(" : ").append(entry.getValue()); writer.println(buf); } for (ProcessingError error : report.getProcessingErrors()) { buf.setLength(0); numberOfErrors++; String nextFile = determineFileName(error.getFileId()); if (!nextFile.equals(lastFile)) { lastFile = nextFile; buf.append(this.redBold) .append("*") .append(this.colorReset) .append(" file: ") .append(this.whiteBold) .append(this.getRelativePath(lastFile)) .append(this.colorReset) .append(System.lineSeparator()); } buf.append(this.green) .append(" err: ") .append(this.cyan) .append(error.getMsg()) .append(this.colorReset) .append(System.lineSeparator()) .append(this.red) .append(error.getDetail()) .append(colorReset) .append(System.lineSeparator()); writer.println(buf); } for (ConfigurationError error : report.getConfigurationErrors()) { buf.setLength(0); numberOfErrors++; buf.append(this.redBold) .append("*") .append(this.colorReset) .append(" rule: ") .append(this.whiteBold) .append(error.rule().getName()) .append(this.colorReset) .append(System.lineSeparator()); buf.append(this.green) .append(" err: ") .append(this.cyan) .append(error.issue()) .append(this.colorReset) .append(System.lineSeparator()); writer.println(buf); } // adding error message count, if any if (numberOfErrors > 0) { writer.println(this.redBold + "*" + this.colorReset + " errors: " + this.whiteBold + numberOfErrors + this.colorReset); } writer.println(this.yellowBold + "*" + this.colorReset + " warnings: " + this.whiteBold + numberOfWarnings + this.colorReset); } /** * Calculate a summary of violation counts per fully classified class name. * * @return violations per class name */ private static Map<String, Integer> getCountSummary(Report report) { Map<String, Integer> summary = new HashMap<>(); for (RuleViolation rv : report.getViolations()) { String key = keyFor(rv); if (key.isEmpty()) { continue; } Integer o = summary.get(key); summary.put(key, o == null ? 1 : o + 1); } return summary; } private static String keyFor(RuleViolation rv) { String packageName = rv.getAdditionalInfo().getOrDefault(RuleViolation.PACKAGE_NAME, ""); String className = rv.getAdditionalInfo().getOrDefault(RuleViolation.CLASS_NAME, ""); return StringUtils.isNotBlank(packageName) ? packageName + '.' + className : ""; } /** * Retrieves the requested line from the specified file. * * @param sourceFile * the java or cpp source file * @param line * line number to extract * * @return a trimmed line of source code */ private String getLine(String sourceFile, int line) { String code = null; try (BufferedReader br = new BufferedReader(getReader(sourceFile))) { for (int i = 0; line > i; i++) { String txt = br.readLine(); code = txt == null ? "" : txt.trim(); } } catch (IOException ioErr) { ioErr.printStackTrace(); } return code; } protected Reader getReader(String sourceFile) throws FileNotFoundException { try { return Files.newBufferedReader(new File(sourceFile).toPath(), Charset.defaultCharset()); } catch (IOException e) { FileNotFoundException ex = new FileNotFoundException(sourceFile); ex.initCause(e); throw ex; } } /** * Attempts to determine the relative path to the file. If relative path * cannot be found, the original path is returnedi, ie - the current path * for the supplied file. * * @param fileName * well, the file with its original path. * @return the relative path to the file */ private String getRelativePath(String fileName) { String relativePath; // check if working directory need to be assigned if (pwd == null) { try { this.pwd = new File(".").getCanonicalPath(); } catch (IOException ioErr) { // to avoid further error this.pwd = ""; } } // make sure that strings match before doing any substring-ing if (fileName.indexOf(this.pwd) == 0) { relativePath = "." + fileName.substring(this.pwd.length()); // remove current dir occurring twice - occurs if . was supplied as // path if (relativePath.startsWith("." + File.separator + "." + File.separator)) { relativePath = relativePath.substring(2); } } else { // this happens when pmd's supplied argument deviates from the pwd // 'branch' (god knows this terminology - i hope i make some sense). // for instance, if supplied=/usr/lots/of/src and // pwd=/usr/lots/of/shared/source // TODO: a fix to get relative path? relativePath = fileName; } return relativePath; } }
13,103
37.204082
191
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextPadRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Iterator; import net.sourceforge.pmd.RuleViolation; /** * <p> * A Renderer for running PMD via a TextPad 'tool'. * <a href="http://www.textpad.com">TextPad</a> is a text editor by Helios * Software Solutions. * </p> * <p> * Output lines are in the form: * </p> * <p> * <CODE>pathtojavafile(line#, NameOfRule):&nbsp; Specific rule violation message</CODE> * </p> * <p> * For example: * </p> * <p> * <CODE>D:\java\pmd\src\src\net\sourceforge\pmd\renderers\TextPadRenderer.java(24, AtLeastOneConstructor):&nbsp; Each class should declare at least one constructor * <br>D:\java\pmd\src\src\net\sourceforge\pmd\renderers\TextPadRenderer.java(26, VariableNamingConventionsRule):&nbsp; Variables should start with a lowercase character * <br>D:\java\pmd\src\src\net\sourceforge\pmd\renderers\TextPadRenderer.java(31, ShortVariable):&nbsp; Avoid variables with short names</CODE> * </p> * * @author Jeff Epstein, based upon * <a href="EmacsRenderer.html">EmacsRenderer</a>, Tuesday, September * 23, 2003 */ public class TextPadRenderer extends AbstractIncrementingRenderer { public static final String NAME = "textpad"; public TextPadRenderer() { super(NAME, "TextPad integration."); } @Override public String defaultFileExtension() { return "txt"; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { StringBuilder buf = new StringBuilder(); while (violations.hasNext()) { RuleViolation rv = violations.next(); buf.setLength(0); // Filename buf.append(determineFileName(rv.getFileId())).append("("); // Line number buf.append(rv.getBeginLine()).append(", "); // Name of violated rule buf.append(rv.getRule().getName()).append("): "); // Specific violation message buf.append(rv.getDescription()); writer.println(buf); } } }
2,196
31.308824
169
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractIncrementingRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.document.TextFile; /** * Abstract base class for {@link Renderer} implementations which can produce * output incrementally for {@link RuleViolation}s as source files are * processed. Such {@link Renderer}s are able to produce large reports with * significantly less working memory at any given time. Variations in the * delivery of source file reports are reflected in the output of the * {@link Renderer}, so report output can be different between runs. * * Only processing errors and suppressed violations are accumulated across all * files. These are intended to be processed in the {@link #end()} method. */ public abstract class AbstractIncrementingRenderer extends AbstractRenderer { /** * Accumulated processing errors. */ protected List<Report.ProcessingError> errors = new LinkedList<>(); /** * Accumulated configuration errors. */ protected List<Report.ConfigurationError> configErrors = new LinkedList<>(); /** * Accumulated suppressed violations. */ protected List<Report.SuppressedViolation> suppressed = new LinkedList<>(); public AbstractIncrementingRenderer(String name, String description) { super(name, description); } @Override public void start() throws IOException { // does nothing - override if necessary } @Override public void startFileAnalysis(TextFile dataSource) { // does nothing - override if necessary } @Override public void renderFileReport(Report report) throws IOException { Iterator<RuleViolation> violations = report.getViolations().iterator(); if (violations.hasNext()) { renderFileViolations(violations); getWriter().flush(); } errors.addAll(report.getProcessingErrors()); configErrors.addAll(report.getConfigurationErrors()); if (showSuppressedViolations) { suppressed.addAll(report.getSuppressedViolations()); } } /** * Render a series of {@link RuleViolation}s. * * @param violations * The iterator of violations to render. * @throws IOException */ public abstract void renderFileViolations(Iterator<RuleViolation> violations) throws IOException; @Override public void end() throws IOException { // does nothing - override if necessary } }
2,734
29.730337
101
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/SarifRenderer.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Iterator; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog; import net.sourceforge.pmd.renderers.internal.sarif.SarifLogBuilder; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class SarifRenderer extends AbstractIncrementingRenderer { public static final String NAME = "sarif"; private static final String DEFAULT_DESCRIPTION = "Static Analysis Results Interchange Format (SARIF)"; private static final String DEFAULT_FILE_EXTENSION = "sarif.json"; private final Gson gson = new GsonBuilder() .disableHtmlEscaping() .setPrettyPrinting() .create(); private SarifLogBuilder sarifLogBuilder; public SarifRenderer() { super(NAME, DEFAULT_DESCRIPTION); } @Override public String defaultFileExtension() { return DEFAULT_FILE_EXTENSION; } @Override public void start() throws IOException { sarifLogBuilder = SarifLogBuilder.sarifLogBuilder(); } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { while (violations.hasNext()) { final RuleViolation violation = violations.next(); sarifLogBuilder.add(violation); } } @Override public void end() throws IOException { addErrors(); writeLog(); } private void addErrors() { for (Report.ProcessingError error : this.errors) { sarifLogBuilder.addRunTimeError(error); } for (Report.ConfigurationError error: this.configErrors) { sarifLogBuilder.addConfigurationError(error); } } private void writeLog() throws IOException { final SarifLog sarifLog = sarifLogBuilder.build(); final String json = gson.toJson(sarifLog); writer.write(json); writer.println(); } @Override public void setReportFile(String reportFilename) { this.setWriter(IOUtil.createWriter(StandardCharsets.UTF_8, reportFilename)); } }
2,390
28.158537
107
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmptyRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.lang.document.TextFile; /** * An empty renderer, for when you really don't want a report. */ public class EmptyRenderer extends AbstractRenderer { public static final String NAME = "empty"; public EmptyRenderer() { super(NAME, "Empty, nothing."); } @Override public String defaultFileExtension() { return ""; } @Override public void start() throws IOException { // deliberately does nothing } @Override public void startFileAnalysis(TextFile dataSource) { // deliberately does nothing } @Override public void renderFileReport(Report report) throws IOException { // deliberately does nothing } @Override public void end() throws IOException { // deliberately does nothing } }
1,024
20.808511
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Iterator; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; /** * Renderer to simple text format. */ public class TextRenderer extends AbstractIncrementingRenderer { private static final char SMALL_SEPARATOR = ':'; private static final String MEDIUM_SEPARATOR = ":\t"; private static final String LARGE_SEPARATOR = "\t-\t"; public static final String NAME = "text"; public TextRenderer() { super(NAME, "Text format."); } @Override public String defaultFileExtension() { return "txt"; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { StringBuilder buf = new StringBuilder(); while (violations.hasNext()) { buf.setLength(0); RuleViolation rv = violations.next(); buf.append(determineFileName(rv.getFileId())); buf.append(SMALL_SEPARATOR).append(rv.getBeginLine()); buf.append(MEDIUM_SEPARATOR).append(rv.getRule().getName()); buf.append(MEDIUM_SEPARATOR).append(rv.getDescription()); writer.println(buf); } } @Override public void end() throws IOException { StringBuilder buf = new StringBuilder(500); for (Report.ProcessingError error : errors) { buf.setLength(0); buf.append(determineFileName(error.getFileId())); buf.append(LARGE_SEPARATOR).append(error.getMsg()); writer.println(buf); } for (Report.SuppressedViolation excluded : suppressed) { buf.setLength(0); buf.append(excluded.getRuleViolation().getRule().getName()) .append(" rule violation suppressed by ") .append(excluded.getSuppressor().getId()) .append(" in ") .append(determineFileName(excluded.getRuleViolation().getFileId())); writer.println(buf); } for (Report.ConfigurationError error : configErrors) { buf.setLength(0); buf.append(error.rule().getName()); buf.append(LARGE_SEPARATOR).append(error.issue()); writer.println(buf); } } }
2,405
29.846154
93
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/ColumnDescriptor.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; /** * @author Brian Remedios */ final class ColumnDescriptor<T> { public final String id; public final String title; public final Accessor<T> accessor; public interface Accessor<T> { String get(int idx, T violation, String lineSeparator); } ColumnDescriptor(String theId, String theTitle, Accessor<T> theAccessor) { id = theId; title = theTitle; accessor = theAccessor; } }
569
20.111111
79
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Locale; import javax.xml.XMLConstants; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil; /** * Renderer to XML format. */ public class XMLRenderer extends AbstractIncrementingRenderer { public static final String NAME = "xml"; // TODO 7.0.0 use PropertyDescriptor<String> or something more specialized public static final PropertyDescriptor<String> ENCODING = PropertyFactory.stringProperty("encoding").desc("XML encoding format").defaultValue("UTF-8").build(); private static final String PMD_REPORT_NS_URI = "http://pmd.sourceforge.net/report/2.0.0"; private static final String PMD_REPORT_NS_LOCATION = "http://pmd.sourceforge.net/report_2_0_0.xsd"; private static final String XSI_NS_PREFIX = "xsi"; private XMLStreamWriter xmlWriter; private OutputStream stream; private byte[] lineSeparator; public XMLRenderer() { super(NAME, "XML format."); definePropertyDescriptor(ENCODING); } public XMLRenderer(String encoding) { this(); setProperty(ENCODING, encoding); } @Override public String defaultFileExtension() { return "xml"; } @Override public void start() throws IOException { String encoding = getProperty(ENCODING); String unmarkedEncoding = toUnmarkedEncoding(encoding); lineSeparator = System.lineSeparator().getBytes(unmarkedEncoding); try { xmlWriter.writeStartDocument(encoding, "1.0"); writeNewLine(); xmlWriter.setDefaultNamespace(PMD_REPORT_NS_URI); xmlWriter.writeStartElement(PMD_REPORT_NS_URI, "pmd"); xmlWriter.writeDefaultNamespace(PMD_REPORT_NS_URI); xmlWriter.writeNamespace(XSI_NS_PREFIX, XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); xmlWriter.writeAttribute(XSI_NS_PREFIX, XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation", PMD_REPORT_NS_URI + " " + PMD_REPORT_NS_LOCATION); xmlWriter.writeAttribute("version", PMDVersion.VERSION); xmlWriter.writeAttribute("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(new Date())); // FIXME: elapsed time not available until the end of the processing // xmlWriter.writeAttribute("time_elapsed", ...); } catch (XMLStreamException e) { throw new IOException(e); } } /** * Return a encoding, which doesn't write a BOM (byte order mark). * Only UTF-16 encoders might write a BOM, see {@link Charset}. * * <p>This is needed, so that we don't accidentally add BOMs whenever * we insert a newline. * * @return */ private static String toUnmarkedEncoding(String encoding) { if (StandardCharsets.UTF_16.name().equalsIgnoreCase(encoding)) { return StandardCharsets.UTF_16BE.name(); } // edge case: UTF-16LE with BOM if ("UTF-16LE_BOM".equalsIgnoreCase(encoding)) { return StandardCharsets.UTF_16LE.name(); } return encoding; } /** * Outputs a platform dependent line separator. * * @throws XMLStreamException if XMLStreamWriter couldn't be flushed. * @throws IOException if an I/O error occurs. */ private void writeNewLine() throws XMLStreamException, IOException { /* * Note: we are not using xmlWriter.writeCharacters(PMD.EOL), because some * XMLStreamWriter implementations might do extra encoding for \r and/or \n. * Notably IBM's Java 8 will escape "\r" with "&#xD;" which will render an * invalid XML document. IBM's Java 8 would also output a platform dependent * line separator when writing "\n" which results under Windows, that "\r" * actually is written twice (once escaped, once raw). * * Note2: Before writing the raw bytes to the underlying stream, we need * to flush XMLStreamWriter. Notably IBM's Java 8 might still need to output * data. * * Note3: Before writing the raw bytes, we issue a empty writeCharacters, * so that any open tags are closed and we are ready for writing raw bytes. */ xmlWriter.writeCharacters(""); xmlWriter.flush(); stream.write(lineSeparator); } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { String filename = null; try { // rule violations while (violations.hasNext()) { RuleViolation rv = violations.next(); String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { // Not first file ? xmlWriter.writeEndElement(); } filename = nextFilename; writeNewLine(); xmlWriter.writeStartElement("file"); xmlWriter.writeAttribute("name", filename); writeNewLine(); } xmlWriter.writeStartElement("violation"); xmlWriter.writeAttribute("beginline", String.valueOf(rv.getBeginLine())); xmlWriter.writeAttribute("endline", String.valueOf(rv.getEndLine())); xmlWriter.writeAttribute("begincolumn", String.valueOf(rv.getBeginColumn())); xmlWriter.writeAttribute("endcolumn", String.valueOf(rv.getEndColumn())); xmlWriter.writeAttribute("rule", rv.getRule().getName()); xmlWriter.writeAttribute("ruleset", rv.getRule().getRuleSetName()); maybeAdd("package", rv.getAdditionalInfo().get(RuleViolation.PACKAGE_NAME)); maybeAdd("class", rv.getAdditionalInfo().get(RuleViolation.CLASS_NAME)); maybeAdd("method", rv.getAdditionalInfo().get(RuleViolation.METHOD_NAME)); maybeAdd("variable", rv.getAdditionalInfo().get(RuleViolation.VARIABLE_NAME)); // todo other additional info keys are not rendered maybeAdd("externalInfoUrl", rv.getRule().getExternalInfoUrl()); xmlWriter.writeAttribute("priority", String.valueOf(rv.getRule().getPriority().getPriority())); writeNewLine(); xmlWriter.writeCharacters(StringUtil.removedInvalidXml10Characters(rv.getDescription())); writeNewLine(); xmlWriter.writeEndElement(); writeNewLine(); } if (filename != null) { // Not first file ? xmlWriter.writeEndElement(); } } catch (XMLStreamException e) { throw new IOException(e); } } @Override public void end() throws IOException { try { // errors for (Report.ProcessingError pe : errors) { writeNewLine(); xmlWriter.writeStartElement("error"); xmlWriter.writeAttribute("filename", determineFileName(pe.getFileId())); xmlWriter.writeAttribute("msg", pe.getMsg()); writeNewLine(); xmlWriter.writeCData(pe.getDetail()); writeNewLine(); xmlWriter.writeEndElement(); } // suppressed violations if (showSuppressedViolations) { for (Report.SuppressedViolation s : suppressed) { writeNewLine(); xmlWriter.writeStartElement("suppressedviolation"); xmlWriter.writeAttribute("filename", determineFileName(s.getRuleViolation().getFileId())); xmlWriter.writeAttribute("suppressiontype", s.getSuppressor().getId().toLowerCase(Locale.ROOT)); xmlWriter.writeAttribute("msg", s.getRuleViolation().getDescription()); xmlWriter.writeAttribute("usermsg", s.getUserMessage() == null ? "" : s.getUserMessage()); xmlWriter.writeEndElement(); } } // config errors for (final Report.ConfigurationError ce : configErrors) { writeNewLine(); xmlWriter.writeEmptyElement("configerror"); xmlWriter.writeAttribute("rule", ce.rule().getName()); xmlWriter.writeAttribute("msg", ce.issue()); } writeNewLine(); xmlWriter.writeEndElement(); // </pmd> writeNewLine(); xmlWriter.writeEndDocument(); xmlWriter.flush(); } catch (XMLStreamException e) { throw new IOException(e); } } private void maybeAdd(String attr, String value) throws XMLStreamException { if (value != null && value.length() > 0) { xmlWriter.writeAttribute(attr, value); } } @Override public void setReportFile(String reportFilename) { String encoding = getProperty(ENCODING); try { this.stream = StringUtils.isBlank(reportFilename) ? System.out : Files.newOutputStream(new File(reportFilename).toPath()); XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); this.xmlWriter = outputFactory.createXMLStreamWriter(this.stream, encoding); // for backwards compatibility, also provide a writer. Note: xmlWriter won't use that. super.setWriter(new WrappedOutputStreamWriter(xmlWriter, stream, encoding)); } catch (IOException | XMLStreamException e) { throw new IllegalArgumentException(e); } } @Override public void setWriter(final Writer writer) { String encoding = getProperty(ENCODING); // for backwards compatibility, create a OutputStream that writes to the writer. this.stream = IOUtil.fromWriter(writer, encoding); XMLOutputFactory outputFactory = XMLOutputFactory.newFactory(); try { this.xmlWriter = outputFactory.createXMLStreamWriter(this.stream, encoding); // for backwards compatibility, also provide a writer. // Note: both XMLStreamWriter and this writer will write to this.stream super.setWriter(new WrappedOutputStreamWriter(xmlWriter, stream, encoding)); } catch (XMLStreamException | UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static class WrappedOutputStreamWriter extends OutputStreamWriter { private final XMLStreamWriter xmlWriter; WrappedOutputStreamWriter(XMLStreamWriter xmlWriter, OutputStream out, String charset) throws UnsupportedEncodingException { super(out, charset); this.xmlWriter = xmlWriter; } @Override public void flush() throws IOException { try { xmlWriter.flush(); } catch (XMLStreamException e) { throw new IOException(e); } super.flush(); } @Override public void close() throws IOException { try { xmlWriter.close(); } catch (XMLStreamException e) { throw new IOException(e); } super.close(); } } // FIXME: elapsed time not available until the end of the processing /* * private String createTimeElapsedAttr(Report rpt) { * Report.ReadableDuration d = new * Report.ReadableDuration(rpt.getElapsedTimeInMillis()); return * " elapsedTime=\"" + d.getTime() + "\""; } */ }
12,740
39.836538
132
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Renderer for Code Climate JSON format */ public class CodeClimateRenderer extends AbstractIncrementingRenderer { public static final String NAME = "codeclimate"; public static final String BODY_PLACEHOLDER = "REPLACE_THIS_WITH_MARKDOWN"; public static final int REMEDIATION_POINTS_DEFAULT = 50000; public static final String[] CODECLIMATE_DEFAULT_CATEGORIES = new String[] {"Style"}; // Note: required by https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md protected static final String NULL_CHARACTER = "\u0000"; protected static final List<String> INTERNAL_DEV_PROPERTIES = Arrays.asList("version", "xpath"); private static final String PMD_PROPERTIES_URL = getPmdPropertiesURL(); private Rule rule; public CodeClimateRenderer() { super(NAME, "Code Climate integration."); } private static String getPmdPropertiesURL() { final String BASE_URL = "https://docs.pmd-code.org/"; final String PAGE = "/pmd_userdocs_configuring_rules.html#rule-properties"; final String VERSION_PART = PMDVersion.isUnknown() || PMDVersion.isSnapshot() ? "latest" : "pmd-doc-" + PMDVersion.VERSION; return BASE_URL + VERSION_PART + PAGE; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { Gson gson = new GsonBuilder().disableHtmlEscaping().create(); while (violations.hasNext()) { RuleViolation rv = violations.next(); rule = rv.getRule(); String json = gson.toJson(asIssue(rv)); json = json.replace(BODY_PLACEHOLDER, getBody()); writer.println(json + NULL_CHARACTER); } } /** * Generate a CodeClimateIssue suitable for processing into JSON from the * given RuleViolation. * * @param rv RuleViolation to convert. * * @return The generated issue. */ private CodeClimateIssue asIssue(RuleViolation rv) { CodeClimateIssue issue = new CodeClimateIssue(); issue.check_name = rule.getName(); issue.description = cleaned(rv.getDescription()); issue.content = new CodeClimateIssue.Content(BODY_PLACEHOLDER); issue.location = getLocation(rv); issue.remediation_points = getRemediationPoints(); issue.categories = getCategories(); switch (rule.getPriority()) { case HIGH: issue.severity = "blocker"; break; case MEDIUM_HIGH: issue.severity = "critical"; break; case MEDIUM: issue.severity = "major"; break; case MEDIUM_LOW: issue.severity = "minor"; break; case LOW: default: issue.severity = "info"; break; } return issue; } @Override public String defaultFileExtension() { return "json"; } private CodeClimateIssue.Location getLocation(RuleViolation rv) { String pathWithoutCcRoot = StringUtils.removeStartIgnoreCase(determineFileName(rv.getFileId()), "/code/"); return new CodeClimateIssue.Location(pathWithoutCcRoot, rv.getBeginLine(), rv.getEndLine()); } private int getRemediationPoints() { return REMEDIATION_POINTS_DEFAULT; } private String[] getCategories() { return CODECLIMATE_DEFAULT_CATEGORIES; } private <T> String getBody() { StringBuilder result = new StringBuilder(); result.append("## ") .append(rule.getName()) .append("\\n\\n") .append("Since: PMD ") .append(rule.getSince()) .append("\\n\\n") .append("Priority: ") .append(rule.getPriority()) .append("\\n\\n") .append("[Categories](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#categories): ") .append(Arrays.toString(getCategories()).replaceAll("[\\[\\]]", "")) .append("\\n\\n") .append("[Remediation Points](https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#remediation-points): ") .append(getRemediationPoints()) .append("\\n\\n") .append(cleaned(rule.getDescription())); if (!rule.getExamples().isEmpty()) { result.append("\\n\\n### Example:\\n\\n"); for (String snippet : rule.getExamples()) { String exampleSnippet = snippet.replaceAll("\\n", "\\\\n"); exampleSnippet = exampleSnippet.replaceAll("\\t", "\\\\t"); result.append("```java\\n").append(exampleSnippet).append("\\n``` "); } } if (!rule.getPropertyDescriptors().isEmpty()) { result.append("\\n\\n### [PMD properties](").append(PMD_PROPERTIES_URL).append(")\\n\\n"); result.append("Name | Value | Description\\n"); result.append("--- | --- | ---\\n"); for (PropertyDescriptor<?> property : rule.getPropertyDescriptors()) { String propertyName = property.name().replaceAll("\\_", "\\\\_"); if (INTERNAL_DEV_PROPERTIES.contains(propertyName)) { continue; } @SuppressWarnings("unchecked") PropertyDescriptor<T> typed = (PropertyDescriptor<T>) property; T value = rule.getProperty(typed); String propertyValue = typed.asDelimitedString(value); if (propertyValue == null) { propertyValue = ""; } propertyValue = propertyValue.replaceAll("(\n|\r\n|\r)", "\\\\n"); result.append(propertyName).append(" | ").append(propertyValue).append(" | ").append(property.description()).append("\\n"); } } return cleaned(result.toString()); } private String cleaned(String original) { String result = original.trim(); result = result.replaceAll("\\s+", " "); result = result.replaceAll("\\s*[\\r\\n]+\\s*", ""); result = result.replaceAll("\"", "'"); return result; } }
6,803
36.59116
144
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/VBHTMLRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Iterator; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; /** * Renderer to another HTML format. * * @author Vladimir */ public class VBHTMLRenderer extends AbstractIncrementingRenderer { public static final String NAME = "vbhtml"; public VBHTMLRenderer() { super(NAME, "Vladimir Bossicard HTML format."); } @Override public String defaultFileExtension() { return "vb.html"; } @Override public void start() throws IOException { getWriter().write(header()); } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { if (!violations.hasNext()) { return; } StringBuilder sb = new StringBuilder(500); String filename = null; String lineSep = System.lineSeparator(); boolean colorize = false; while (violations.hasNext()) { sb.setLength(0); RuleViolation rv = violations.next(); String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { sb.append("</table></br>"); colorize = false; } filename = nextFilename; sb.append("<table border=\"0\" width=\"80%\">"); sb.append("<tr id=TableHeader><td colspan=\"2\"><font class=title>&nbsp;").append(filename) .append("</font></tr>"); sb.append(lineSep); } if (colorize) { sb.append("<tr id=RowColor1>"); } else { sb.append("<tr id=RowColor2>"); } colorize = !colorize; sb.append("<td width=\"50\" align=\"right\"><font class=body>").append(rv.getBeginLine()).append("&nbsp;&nbsp;&nbsp;</font></td>"); sb.append("<td><font class=body>").append(rv.getDescription()).append("</font></td>"); sb.append("</tr>"); sb.append(lineSep); writer.write(sb.toString()); } if (filename != null) { writer.write("</table>"); } } @Override public void end() throws IOException { StringBuilder sb = new StringBuilder(); writer.write("<br>"); // output the problems if (!errors.isEmpty()) { sb.setLength(0); sb.append("<table border=\"0\" width=\"80%\">"); sb.append("<tr id=TableHeader><td colspan=\"2\"><font class=title>&nbsp;Problems found</font></td></tr>"); boolean colorize = false; for (Report.ProcessingError error : errors) { if (colorize) { sb.append("<tr id=RowColor1>"); } else { sb.append("<tr id=RowColor2>"); } colorize = !colorize; sb.append("<td><font class=body>").append(determineFileName(error.getFileId())).append("</font></td>"); sb.append("<td><font class=body><pre>").append(error.getDetail()).append("</pre></font></td></tr>"); } sb.append("</table>"); writer.write(sb.toString()); } if (!configErrors.isEmpty()) { sb.setLength(0); sb.append("<table border=\"0\" width=\"80%\">"); sb.append("<tr id=TableHeader><td colspan=\"2\"><font class=title>&nbsp;Configuration problems found</font></td></tr>"); boolean colorize = false; for (Report.ConfigurationError error : configErrors) { if (colorize) { sb.append("<tr id=RowColor1>"); } else { sb.append("<tr id=RowColor2>"); } colorize = !colorize; sb.append("<td><font class=body>").append(error.rule().getName()).append("</font></td>"); sb.append("<td><font class=body>").append(error.issue()).append("</font></td></tr>"); } sb.append("</table>"); writer.write(sb.toString()); } writer.write(footer()); } private String header() { return "<html><head><title>PMD</title></head>" + "<style type=\"text/css\">" + "<!--" + System.lineSeparator() + "body { background-color: white; font-family:verdana, arial, helvetica, geneva; font-size: 16px; font-style: italic; color: black; }" + System.lineSeparator() + ".title { font-family: verdana, arial, helvetica,geneva; font-size: 12px; font-weight:bold; color: white; }" + System.lineSeparator() + ".body { font-family: verdana, arial, helvetica, geneva; font-size: 12px; font-weight:plain; color: black; }" + System.lineSeparator() + "#TableHeader { background-color: #003366; }" + System.lineSeparator() + "#RowColor1 { background-color: #eeeeee; }" + System.lineSeparator() + "#RowColor2 { background-color: white; }" + System.lineSeparator() + "-->" + "</style>" + "<body><center>"; } private String footer() { return "</center></body></html>" + System.lineSeparator(); } }
5,485
36.067568
147
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.properties.PropertySource; import net.sourceforge.pmd.renderers.ColumnDescriptor.Accessor; /** * Renderer the results to a comma-delimited text format. All available columns * are present by default. IDEs can enable/disable columns individually * (cmd-line control to follow eventually) */ public class CSVRenderer extends AbstractIncrementingRenderer { private final String separator; private final String cr; private CSVWriter<RuleViolation> csvWriter; private static final String DEFAULT_SEPARATOR = ","; private static final Map<String, PropertyDescriptor<Boolean>> PROPERTY_DESCRIPTORS_BY_ID = new HashMap<>(); public static final String NAME = "csv"; @SuppressWarnings("unchecked") private final ColumnDescriptor<RuleViolation>[] allColumns = new ColumnDescriptor[] { newColDescriptor("problem", "Problem", (idx, rv, cr) -> Integer.toString(idx)), newColDescriptor("package", "Package", (idx, rv, cr) -> rv.getAdditionalInfo().getOrDefault(RuleViolation.PACKAGE_NAME, "")), newColDescriptor("file", "File", (idx, rv, cr) -> determineFileName(rv.getFileId())), newColDescriptor("priority", "Priority", (idx, rv, cr) -> Integer.toString(rv.getRule().getPriority().getPriority())), newColDescriptor("line", "Line", (idx, rv, cr) -> Integer.toString(rv.getBeginLine())), newColDescriptor("desc", "Description", (idx, rv, cr) -> StringUtils.replaceChars(rv.getDescription(), '\"', '\'')), newColDescriptor("ruleSet", "Rule set", (idx, rv, cr) -> rv.getRule().getRuleSetName()), newColDescriptor("rule", "Rule", (idx, rv, cr) -> rv.getRule().getName()), }; private static @NonNull ColumnDescriptor<RuleViolation> newColDescriptor(String id, String title, Accessor<RuleViolation> accessor) { return new ColumnDescriptor<>(id, title, accessor); } public CSVRenderer(ColumnDescriptor<RuleViolation>[] columns, String theSeparator, String theCR) { super(NAME, "Comma-separated values tabular format."); separator = theSeparator; cr = theCR; for (ColumnDescriptor<RuleViolation> desc : columns) { definePropertyDescriptor(booleanPropertyFor(desc.id, desc.title)); } } public CSVRenderer() { super(NAME, "Comma-separated values tabular format."); separator = DEFAULT_SEPARATOR; cr = System.lineSeparator(); for (ColumnDescriptor<RuleViolation> desc : allColumns) { definePropertyDescriptor(booleanPropertyFor(desc.id, desc.title)); } } private static PropertyDescriptor<Boolean> booleanPropertyFor(String id, String label) { PropertyDescriptor<Boolean> prop = PROPERTY_DESCRIPTORS_BY_ID.get(id); if (prop != null) { return prop; } prop = PropertyFactory.booleanProperty(id).defaultValue(true).desc("Include " + label + " column").build(); PROPERTY_DESCRIPTORS_BY_ID.put(id, prop); return prop; } private List<ColumnDescriptor<RuleViolation>> activeColumns() { List<ColumnDescriptor<RuleViolation>> actives = new ArrayList<>(); for (ColumnDescriptor<RuleViolation> desc : allColumns) { PropertyDescriptor<Boolean> prop = booleanPropertyFor(desc.id, null); if (getProperty(prop)) { actives.add(desc); } } return actives; } private CSVWriter<RuleViolation> csvWriter() { if (csvWriter != null) { return csvWriter; } csvWriter = new CSVWriter<>(activeColumns(), separator, cr); return csvWriter; } @Override public void start() throws IOException { csvWriter().writeTitles(getWriter()); } @Override public String defaultFileExtension() { return "csv"; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { csvWriter().writeData(getWriter(), violations); } /** * We can't show any violations if we don't have any visible columns. * * @see PropertySource#dysfunctionReason() */ @Override public String dysfunctionReason() { return activeColumns().isEmpty() ? "No columns selected" : null; } }
4,884
33.892857
137
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.properties.StringProperty; /** * Renderer to basic HTML format. * * FIXME: this class should just work with the XMLRenderer and then apply an * XSLT transformation + stylesheet. No need to hard-code HTML markup here. */ public class HTMLRenderer extends AbstractIncrementingRenderer { public static final String NAME = "html"; // TODO use PropertyDescriptor<Optional<String>> : we need a "blank" default value public static final StringProperty LINE_PREFIX = new StringProperty("linePrefix", "Prefix for line number anchor in the source file.", null, 1); public static final PropertyDescriptor<String> LINK_PREFIX = PropertyFactory.stringProperty("linkPrefix").desc("Path to HTML source.").defaultValue("").build(); public static final PropertyDescriptor<Boolean> HTML_EXTENSION = PropertyFactory.booleanProperty("htmlExtension") .desc("Replace file extension with .html for the links.") // default value is false - to have the old (pre 6.23.0) behavior, this needs to be set to true. .defaultValue(false) .build(); private String linkPrefix; private String linePrefix; private boolean replaceHtmlExtension; boolean colorize = true; public HTMLRenderer() { super(NAME, "HTML format"); definePropertyDescriptor(LINK_PREFIX); definePropertyDescriptor(LINE_PREFIX); definePropertyDescriptor(HTML_EXTENSION); } @Override public String defaultFileExtension() { return "html"; } /** * Write the body of the main body of the HTML content. */ public void renderBody(PrintWriter writer, Report report) throws IOException { linkPrefix = getProperty(LINK_PREFIX); linePrefix = getProperty(LINE_PREFIX); replaceHtmlExtension = getProperty(HTML_EXTENSION); writer.write("<center><h3>PMD report</h3></center>"); writer.write("<center><h3>Problems found</h3></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); writer.println("<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>"); setWriter(writer); renderFileReport(report); writer.write("</table>"); glomProcessingErrors(writer, errors); if (showSuppressedViolations) { glomSuppressions(writer, suppressed); } glomConfigurationErrors(writer, configErrors); } @Override public void start() throws IOException { linkPrefix = getProperty(LINK_PREFIX); linePrefix = getProperty(LINE_PREFIX); replaceHtmlExtension = getProperty(HTML_EXTENSION); writer.println("<html><head><title>PMD</title></head><body>"); writer.write("<center><h3>PMD report</h3></center>"); writer.write("<center><h3>Problems found</h3></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); writer.println("<th>#</th><th>File</th><th>Line</th><th>Problem</th></tr>"); } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { glomRuleViolations(writer, violations); } @Override public void end() throws IOException { writer.write("</table>"); glomProcessingErrors(writer, errors); if (showSuppressedViolations) { glomSuppressions(writer, suppressed); } glomConfigurationErrors(writer, configErrors); writer.println("</body></html>"); } private void glomRuleViolations(Writer writer, Iterator<RuleViolation> violations) throws IOException { int violationCount = 1; StringBuilder buf = new StringBuilder(500); while (violations.hasNext()) { RuleViolation rv = violations.next(); buf.setLength(0); buf.append("<tr"); if (colorize) { buf.append(" bgcolor=\"lightgrey\""); } colorize = !colorize; buf.append("> ").append(System.lineSeparator()); buf.append("<td align=\"center\">").append(violationCount).append("</td>").append(System.lineSeparator()); buf.append("<td width=\"*%\">") .append(renderFileName(rv.getFileId(), rv.getBeginLine())) .append("</td>") .append(System.lineSeparator()); buf.append("<td align=\"center\" width=\"5%\">").append(rv.getBeginLine()).append("</td>").append(System.lineSeparator()); String d = StringEscapeUtils.escapeHtml4(rv.getDescription()); String infoUrl = rv.getRule().getExternalInfoUrl(); if (StringUtils.isNotBlank(infoUrl)) { d = "<a href=\"" + infoUrl + "\">" + d + "</a>"; } buf.append("<td width=\"*\">") .append(d) .append("</td>") .append(System.lineSeparator()) .append("</tr>") .append(System.lineSeparator()); writer.write(buf.toString()); violationCount++; } } private String renderFileName(FileId fileId, int beginLine) { return maybeWrap(StringEscapeUtils.escapeHtml4(determineFileName(fileId)), linePrefix == null || beginLine < 0 ? "" : linePrefix + beginLine); } private String renderRuleName(Rule rule) { String name = rule.getName(); String infoUrl = rule.getExternalInfoUrl(); if (StringUtils.isNotBlank(infoUrl)) { return "<a href=\"" + infoUrl + "\">" + name + "</a>"; } return name; } private void glomProcessingErrors(PrintWriter writer, List<Report.ProcessingError> errors) throws IOException { if (errors.isEmpty()) { return; } writer.write("<hr/>"); writer.write("<center><h3>Processing errors</h3></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); writer.println("<th>File</th><th>Problem</th></tr>"); StringBuilder buf = new StringBuilder(500); boolean colorize = true; for (Report.ProcessingError pe : errors) { buf.setLength(0); buf.append("<tr"); if (colorize) { buf.append(" bgcolor=\"lightgrey\""); } colorize = !colorize; buf.append("> ").append(System.lineSeparator()); buf.append("<td>").append(renderFileName(pe.getFileId(), -1)).append("</td>").append(System.lineSeparator()); buf.append("<td><pre>").append(pe.getDetail()).append("</pre></td>").append(System.lineSeparator()); buf.append("</tr>").append(System.lineSeparator()); writer.write(buf.toString()); } writer.write("</table>"); } private void glomSuppressions(PrintWriter writer, List<Report.SuppressedViolation> suppressed) throws IOException { if (suppressed.isEmpty()) { return; } writer.write("<hr/>"); writer.write("<center><h3>Suppressed warnings</h3></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); writer.println("<th>File</th><th>Line</th><th>Rule</th><th>NOPMD or Annotation</th><th>Reason</th></tr>"); StringBuilder buf = new StringBuilder(500); boolean colorize = true; for (Report.SuppressedViolation sv : suppressed) { buf.setLength(0); buf.append("<tr"); if (colorize) { buf.append(" bgcolor=\"lightgrey\""); } colorize = !colorize; buf.append("> ").append(System.lineSeparator()); RuleViolation rv = sv.getRuleViolation(); buf.append("<td align=\"left\">").append(renderFileName(rv.getFileId(), rv.getBeginLine())).append("</td>").append(System.lineSeparator()); buf.append("<td align=\"center\">").append(rv.getBeginLine()).append("</td>").append(System.lineSeparator()); buf.append("<td align=\"center\">").append(renderRuleName(rv.getRule())).append("</td>").append(System.lineSeparator()); buf.append("<td align=\"center\">").append(sv.getSuppressor().getId()).append("</td>").append(System.lineSeparator()); buf.append("<td align=\"center\">").append(sv.getUserMessage() == null ? "" : sv.getUserMessage()).append("</td>").append(System.lineSeparator()); buf.append("</tr>").append(System.lineSeparator()); writer.write(buf.toString()); } writer.write("</table>"); } private void glomConfigurationErrors(final PrintWriter writer, final List<ConfigurationError> configErrors) throws IOException { if (configErrors.isEmpty()) { return; } writer.write("<hr/>"); writer.write("<center><h3>Configuration errors</h3></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); writer.println("<th>Rule</th><th>Problem</th></tr>"); StringBuilder buf = new StringBuilder(500); boolean colorize = true; for (Report.ConfigurationError ce : configErrors) { buf.setLength(0); buf.append("<tr"); if (colorize) { buf.append(" bgcolor=\"lightgrey\""); } colorize = !colorize; buf.append("> ").append(System.lineSeparator()); buf.append("<td>").append(renderRuleName(ce.rule())).append("</td>").append(System.lineSeparator()); buf.append("<td>").append(ce.issue()).append("</td>").append(System.lineSeparator()); buf.append("</tr>").append(System.lineSeparator()); writer.write(buf.toString()); } writer.write("</table>"); } private String maybeWrap(String filename, String line) { if (StringUtils.isBlank(linkPrefix)) { return filename; } String newFileName = filename.replace('\\', '/'); if (replaceHtmlExtension) { int index = filename.lastIndexOf('.'); if (index >= 0) { newFileName = filename.substring(0, index); } } return "<a href=\"" + linkPrefix + newFileName + (replaceHtmlExtension ? ".html#" : "#") + line + "\">" + newFileName + "</a>"; } }
11,308
39.826715
158
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractAccumulatingRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Objects; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Report.GlobalReportBuilderListener; 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.document.TextFile; import net.sourceforge.pmd.reporting.FileAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; /** * Abstract base class for {@link Renderer} implementations which only produce * output once all source files are processed. Such {@link Renderer}s use * working memory proportional to the number of violations found, which can be * quite large in some scenarios. Consider using * {@link AbstractIncrementingRenderer} which can use significantly less memory. * * <p>Subclasses should only implement the {@link #end()} method to output the * complete {@link #report}. * * @see AbstractIncrementingRenderer */ public abstract class AbstractAccumulatingRenderer extends AbstractRenderer { public AbstractAccumulatingRenderer(String name, String description) { super(name, description); } @Override public void start() throws IOException { // do nothing } @Override public void end() throws IOException { // do nothing } @Override public void startFileAnalysis(TextFile dataSource) { Objects.requireNonNull(dataSource); } /** * {@inheritDoc} * * @deprecated This is internal API. Do not override when extending {@link AbstractAccumulatingRenderer}. * In PMD7 this method will be made final. */ @Override @InternalApi @Deprecated public final void renderFileReport(Report report) throws IOException { // do nothing, final because it will never be called by the listener Objects.requireNonNull(report); } /** * Output the report, called once at the end of the analysis. * * {@inheritDoc} */ protected abstract void outputReport(Report report) throws IOException; @Override public GlobalAnalysisListener newListener() throws IOException { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { this.start(); } return new GlobalAnalysisListener() { final GlobalReportBuilderListener reportBuilder = new GlobalReportBuilderListener(); @Override public FileAnalysisListener startFileAnalysis(TextFile file) { AbstractAccumulatingRenderer.this.startFileAnalysis(file); return reportBuilder.startFileAnalysis(file); } @Override public void onConfigError(ConfigurationError error) { reportBuilder.onConfigError(error); } @Override public void close() throws Exception { reportBuilder.close(); try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { outputReport(reportBuilder.getResult()); end(); flush(); } } }; } }
3,532
31.412844
109
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/SummaryHTMLRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; /** * Renderer to a summarized HTML format. */ public class SummaryHTMLRenderer extends AbstractAccumulatingRenderer { public static final String NAME = "summaryhtml"; public SummaryHTMLRenderer() { super(NAME, "Summary HTML format."); // Note: we define the same properties as HTML Renderer // we have to copy the values later from this renderer to the HTML // Renderer definePropertyDescriptor(HTMLRenderer.LINK_PREFIX); definePropertyDescriptor(HTMLRenderer.LINE_PREFIX); definePropertyDescriptor(HTMLRenderer.HTML_EXTENSION); } @Override public String defaultFileExtension() { return "html"; } @Override public void outputReport(Report report) throws IOException { writer.println("<html><head><title>PMD</title></head><body>"); renderSummary(report); writer.write("<center><h2>Detail</h2></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>"); HTMLRenderer htmlRenderer = new HTMLRenderer(); htmlRenderer.setProperty(HTMLRenderer.LINK_PREFIX, getProperty(HTMLRenderer.LINK_PREFIX)); htmlRenderer.setProperty(HTMLRenderer.LINE_PREFIX, getProperty(HTMLRenderer.LINE_PREFIX)); htmlRenderer.setProperty(HTMLRenderer.HTML_EXTENSION, getProperty(HTMLRenderer.HTML_EXTENSION)); htmlRenderer.setShowSuppressedViolations(showSuppressedViolations); htmlRenderer.renderBody(writer, report); writer.println("</tr></table></body></html>"); } /** * Write a Summary HTML table. */ private void renderSummary(Report report) throws IOException { writer.println("<center><h2>Summary</h2></center>"); writer.println("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\">"); writer.println("<tr><th>Rule name</th><th>Number of violations</th></tr>"); Map<String, MutableInt> summary = getSummary(report); for (Entry<String, MutableInt> entry : summary.entrySet()) { String ruleName = entry.getKey(); writer.write("<tr><td>"); writer.write(ruleName); writer.write("</td><td align=center>"); writer.write(String.valueOf(entry.getValue().intValue())); writer.println("</td></tr>"); } writer.println("</table>"); } private static Map<String, MutableInt> getSummary(Report report) { Map<String, MutableInt> summary = new HashMap<>(); for (RuleViolation rv : report.getViolations()) { String name = rv.getRule().getName(); MutableInt count = summary.get(name); if (count == null) { count = new MutableInt(0); summary.put(name, count); } count.increment(); } return summary; } }
3,251
34.736264
104
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVWriter.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; /** * A generic writer that formats input items into rows and columns per the * provided column descriptors. * * @author Brian Remedios * @param <T> * @deprecated This is internal API and an implementation detail for {@link CSVRenderer}. */ class CSVWriter<T> { private final String separator; // e.g., the comma private final String lineSeparator; // cr private final List<ColumnDescriptor<T>> columns; CSVWriter(List<ColumnDescriptor<T>> theColumns, String theSeparator, String theLineSeparator) { columns = theColumns; separator = theSeparator; lineSeparator = theLineSeparator; } public void writeTitles(Writer writer) throws IOException { StringBuilder buf = new StringBuilder(300); for (int i = 0; i < columns.size() - 1; i++) { quoteAndCommify(buf, columns.get(i).title); } quote(buf, columns.get(columns.size() - 1).title); buf.append(lineSeparator); writer.write(buf.toString()); } public void writeData(Writer writer, Iterator<T> items) throws IOException { int count = 1; StringBuilder buf = new StringBuilder(300); T rv; final int lastColumnIdx = columns.size() - 1; while (items.hasNext()) { buf.setLength(0); rv = items.next(); for (int i = 0; i < lastColumnIdx; i++) { quoteAndCommify(buf, columns.get(i).accessor.get(count, rv, separator)); } quote(buf, columns.get(lastColumnIdx).accessor.get(count, rv, separator)); buf.append(lineSeparator); writer.write(buf.toString()); count++; } } private void quote(StringBuilder buffer, String s) { if (s == null) { s = ""; } buffer.append('"').append(s).append('"'); } private void quoteAndCommify(StringBuilder buffer, String s) { quote(buffer, s); buffer.append(separator); } }
2,240
26.666667
99
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/RendererFactory.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.util.AssertionUtil; /** * This class handles the creation of Renderers. * * @see Renderer */ public final class RendererFactory { private static final Logger LOG = LoggerFactory.getLogger(RendererFactory.class); private static final Map<String, Class<? extends Renderer>> REPORT_FORMAT_TO_RENDERER; static { Map<String, Class<? extends Renderer>> map = new TreeMap<>(); map.put(CodeClimateRenderer.NAME, CodeClimateRenderer.class); map.put(XMLRenderer.NAME, XMLRenderer.class); map.put(IDEAJRenderer.NAME, IDEAJRenderer.class); map.put(TextColorRenderer.NAME, TextColorRenderer.class); map.put(TextRenderer.NAME, TextRenderer.class); map.put(TextPadRenderer.NAME, TextPadRenderer.class); map.put(EmacsRenderer.NAME, EmacsRenderer.class); map.put(CSVRenderer.NAME, CSVRenderer.class); map.put(HTMLRenderer.NAME, HTMLRenderer.class); map.put(XSLTRenderer.NAME, XSLTRenderer.class); map.put(YAHTMLRenderer.NAME, YAHTMLRenderer.class); map.put(SummaryHTMLRenderer.NAME, SummaryHTMLRenderer.class); map.put(VBHTMLRenderer.NAME, VBHTMLRenderer.class); map.put(EmptyRenderer.NAME, EmptyRenderer.class); map.put(JsonRenderer.NAME, JsonRenderer.class); map.put(SarifRenderer.NAME, SarifRenderer.class); REPORT_FORMAT_TO_RENDERER = Collections.unmodifiableMap(map); } private RendererFactory() { } /** * Retrieves a collection of all supported renderer names. * * @return The set of all supported renderer names. */ public static Set<String> supportedRenderers() { return Collections.unmodifiableSet(REPORT_FORMAT_TO_RENDERER.keySet()); } /** * Construct an instance of a Renderer based on report format name. * * @param reportFormat * The report format name. * @param properties * Initialization properties for the corresponding Renderer. * @return A Renderer instance. */ public static Renderer createRenderer(String reportFormat, Properties properties) { AssertionUtil.requireParamNotNull("reportFormat", reportFormat); Class<? extends Renderer> rendererClass = getRendererClass(reportFormat); Constructor<? extends Renderer> constructor = getRendererConstructor(rendererClass); Renderer renderer; try { if (constructor.getParameterTypes().length > 0) { LOG.warn( "The renderer uses a deprecated mechanism to use the properties. Please define the needed properties with this.definePropertyDescriptor(..)."); renderer = constructor.newInstance(properties); } else { renderer = constructor.newInstance(); for (PropertyDescriptor<?> prop : renderer.getPropertyDescriptors()) { String value = properties.getProperty(prop.name()); if (value != null) { @SuppressWarnings("unchecked") PropertyDescriptor<Object> prop2 = (PropertyDescriptor<Object>) prop; Object valueFrom = prop2.valueFrom(value); renderer.setProperty(prop2, valueFrom); } } } } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException( "Unable to construct report renderer class: " + e.getLocalizedMessage(), e); } catch (InvocationTargetException e) { throw new IllegalArgumentException( "Unable to construct report renderer class: " + e.getTargetException().getLocalizedMessage(), e); } // Warn about legacy report format usages if (REPORT_FORMAT_TO_RENDERER.containsKey(reportFormat) && !reportFormat.equals(renderer.getName())) { LOG.warn("Report format '{}' is deprecated, and has been replaced with '{}'. " + "Future versions of PMD will remove support for this deprecated Report format usage.", reportFormat, renderer.getName()); } return renderer; } @SuppressWarnings("unchecked") private static Class<? extends Renderer> getRendererClass(String reportFormat) { AssertionUtil.requireParamNotNull("reportFormat", reportFormat); Class<? extends Renderer> rendererClass = REPORT_FORMAT_TO_RENDERER.get(reportFormat); // Look up a custom renderer class if (rendererClass == null && !"".equals(reportFormat)) { try { Class<?> clazz = Class.forName(reportFormat); if (!Renderer.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Custom report renderer class does not implement the " + Renderer.class.getName() + " interface."); } else { rendererClass = (Class<? extends Renderer>) clazz; } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Can't find the custom format " + reportFormat + ": " + e); } } return rendererClass; } private static Constructor<? extends Renderer> getRendererConstructor(Class<? extends Renderer> rendererClass) { Constructor<? extends Renderer> constructor = null; // 1) Properties constructor? - deprecated try { constructor = rendererClass.getConstructor(Properties.class); if (!Modifier.isPublic(constructor.getModifiers())) { constructor = null; } } catch (NoSuchMethodException ignored) { // Ignored, we'll check default constructor next } // 2) No-arg constructor? try { constructor = rendererClass.getConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor = null; } } catch (NoSuchMethodException ignored) { // Ignored, we'll eventually throw an exception, if there is no constructor } if (constructor == null) { throw new IllegalArgumentException( "Unable to find either a public java.util.Properties or no-arg constructors for Renderer class: " + rendererClass.getName()); } return constructor; } }
7,064
41.305389
167
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/YAHTMLRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.LinkedList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil; /** * Renderer to another HTML format. */ public class YAHTMLRenderer extends AbstractAccumulatingRenderer { public static final String NAME = "yahtml"; // TODO 7.0.0 use PropertyDescriptor<Optional<File>> with a constraint that the file is an existing directory public static final PropertyDescriptor<String> OUTPUT_DIR = PropertyFactory.stringProperty("outputDir") .desc("Output directory.") .defaultValue(".") .build(); private SortedMap<String, ReportNode> reportNodesByPackage = new TreeMap<>(); public YAHTMLRenderer() { // YA = Yet Another? super(NAME, "Yet Another HTML format."); definePropertyDescriptor(OUTPUT_DIR); } @Override public String defaultFileExtension() { return "html"; } private void addViolation(RuleViolation violation) { String packageName = violation.getAdditionalInfo().getOrDefault(RuleViolation.PACKAGE_NAME, ""); String className = violation.getAdditionalInfo().getOrDefault(RuleViolation.CLASS_NAME, ""); // report each part of the package name: e.g. net.sf.pmd.test will create nodes for // net, net.sf, net.sf.pmd, and net.sf.pmd.test int index = packageName.indexOf('.', 0); while (index > -1) { String currentPackage = packageName.substring(0, index); ReportNode reportNode = reportNodesByPackage.get(currentPackage); if (reportNode == null) { reportNode = new ReportNode(currentPackage); reportNodesByPackage.put(currentPackage, reportNode); } reportNode.incrementViolations(); int oldIndex = index; index = packageName.indexOf('.', index + 1); if (index == -1 && oldIndex != packageName.length()) { index = packageName.length(); } } // add one node per class collecting the actual violations String fqClassName = packageName + "." + className; ReportNode classNode = reportNodesByPackage.get(fqClassName); if (classNode == null) { classNode = new ReportNode(packageName, className); reportNodesByPackage.put(fqClassName, classNode); } classNode.addRuleViolation(violation); // count the overall violations in the root node ReportNode rootNode = reportNodesByPackage.get(ReportNode.ROOT_NODE_NAME); if (rootNode == null) { rootNode = new ReportNode("Aggregate"); reportNodesByPackage.put(ReportNode.ROOT_NODE_NAME, rootNode); } rootNode.incrementViolations(); } @Override public void outputReport(Report report) throws IOException { String outputDir = getProperty(OUTPUT_DIR); for (RuleViolation ruleViolation : report.getViolations()) { addViolation(ruleViolation); } renderIndex(outputDir); renderClasses(outputDir); writer.println("<h3 align=\"center\">The HTML files are located " + (outputDir == null ? "above the project directory" : "in '" + outputDir + '\'') + ".</h3>"); } private void renderIndex(String outputDir) throws IOException { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(new File(outputDir, "index.html").toPath(), StandardCharsets.UTF_8))) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println(" <head>"); out.println(" <meta charset=\"UTF-8\">"); out.println(" <title>PMD</title>"); out.println(" </head>"); out.println(" <body>"); out.println(" <h2>Package View</h2>"); out.println(" <table border=\"1\" align=\"center\" cellspacing=\"0\" cellpadding=\"3\">"); out.println(" <tr><th>Package</th><th>Class</th><th>#</th></tr>"); for (ReportNode node : reportNodesByPackage.values()) { out.print(" <tr><td><b>"); out.print(node.getPackageName()); out.print("</b></td> <td>"); if (node.hasViolations()) { out.print("<a href=\""); out.print(node.getClassName()); out.print(".html"); out.print("\">"); out.print(node.getClassName()); out.print("</a>"); } else { out.print(node.getClassName()); } out.print("</td> <td>"); out.print(node.getViolationCount()); out.print("</td></tr>"); out.println(); } out.println(" </table>"); out.println(" </body>"); out.println("</html>"); } } private void renderClasses(String outputDir) throws IOException { for (ReportNode node : reportNodesByPackage.values()) { if (node.hasViolations()) { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(new File(outputDir, node.getClassName() + ".html").toPath(), StandardCharsets.UTF_8))) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println(" <head>"); out.println(" <meta charset=\"UTF-8\">"); out.print(" <title>PMD - "); out.print(node.getClassName()); out.println("</title>"); out.println(" </head>"); out.println(" <body>"); out.println(" <h2>Class View</h2>"); out.print(" <h3 align=\"center\">Class: "); out.print(node.getClassName()); out.println("</h3>"); out.println(" <table border=\"\" align=\"center\" cellspacing=\"0\" cellpadding=\"3\">"); out.println(" <tr><th>Method</th><th>Violation</th></tr>"); for (RuleViolation violation : node.getViolations()) { out.print(" <tr><td>"); String methodName = violation.getAdditionalInfo().get(RuleViolation.METHOD_NAME); out.print(StringUtil.nullToEmpty(methodName)); out.print("</td><td>"); out.print("<table border=\"0\">"); out.print(renderViolationRow("Rule:", violation.getRule().getName())); out.print(renderViolationRow("Description:", violation.getDescription())); String variableName = violation.getAdditionalInfo().get(RuleViolation.VARIABLE_NAME); if (StringUtils.isNotBlank(variableName)) { out.print(renderViolationRow("Variable:", variableName)); } out.print(renderViolationRow("Line:", violation.getEndLine() > 0 ? violation.getBeginLine() + " and " + violation.getEndLine() : String.valueOf(violation.getBeginLine()))); out.print("</table>"); out.print("</td></tr>"); out.println(); } out.println(" </table>"); out.println(" </body>"); out.println("</html>"); } } } } private String renderViolationRow(String name, String value) { return "<tr><td><b>" + name + "</b></td>" + "<td>" + value + "</td></tr>"; } private static class ReportNode { // deliberately starts with a space, so that it is sorted before the packages private static final String ROOT_NODE_NAME = " <root> "; private final String packageName; private final String className; private int violationCount; private final List<RuleViolation> violations = new LinkedList<>(); ReportNode(String packageName) { this.packageName = packageName; this.className = "-"; } ReportNode(String packageName, String className) { this.packageName = packageName; this.className = className; } public void incrementViolations() { violationCount++; } public void addRuleViolation(RuleViolation violation) { violations.add(violation); } public String getPackageName() { return packageName; } public String getClassName() { return className; } public int getViolationCount() { return violationCount + violations.size(); } public List<RuleViolation> getViolations() { return violations; } public boolean hasViolations() { return !violations.isEmpty(); } @Override public String toString() { return "ReportNode[packageName=" + packageName + ",className=" + className + ",violationCount=" + violationCount + ",violations=" + violations.size() + "]"; } } }
10,190
37.749049
167
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmacsRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.util.Iterator; import net.sourceforge.pmd.RuleViolation; /** * Renderer to GNU Emacs parsable format. */ public class EmacsRenderer extends AbstractIncrementingRenderer { public static final String NAME = "emacs"; protected static final String EOL = System.getProperty("line.separator", "\n"); public EmacsRenderer() { super(NAME, "GNU Emacs integration."); } @Override public String defaultFileExtension() { return "emacs"; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { StringBuilder buf = new StringBuilder(); while (violations.hasNext()) { RuleViolation rv = violations.next(); buf.setLength(0); buf.append(determineFileName(rv.getFileId())); buf.append(':').append(Integer.toString(rv.getBeginLine())); buf.append(": ").append(rv.getDescription()).append(EOL); writer.write(buf.toString()); } } }
1,187
26.627907
93
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.io.Writer; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Report.GlobalReportBuilderListener; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.Report.ReportBuilderListener; import net.sourceforge.pmd.Report.SuppressedViolation; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.benchmark.TimeTracker; import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertySource; import net.sourceforge.pmd.reporting.FileAnalysisListener; import net.sourceforge.pmd.reporting.FileNameRenderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.ListenerInitializer; /** * This is an interface for rendering a Report. When a Renderer is being * invoked, the sequence of method calls is something like the following: * <ol> * <li>Renderer construction/initialization</li> * <li>{@link Renderer#setShowSuppressedViolations(boolean)}</li> * <li>{@link Renderer#setWriter(Writer)}</li> * <li>{@link Renderer#start()}</li> * <li>{@link Renderer#startFileAnalysis(TextFile)} for each source file * processed</li> * <li>{@link Renderer#renderFileReport(Report)} for each Report instance</li> * <li>{@link Renderer#end()}</li> * </ol> * <p> * An implementation of the Renderer interface is expected to have a default * constructor. Properties should be defined using the * {@link #definePropertyDescriptor(PropertyDescriptor)} * method. After the instance is created, the property values are set. This * means, you won't have access to property values in your constructor. */ // TODO Are implementations expected to be thread-safe? public interface Renderer extends PropertySource { /** * Get the name of the Renderer. * * @return The name of the Renderer. */ @Override String getName(); /** * Set the name of the Renderer. * * @param name * The name of the Renderer. */ void setName(String name); /** * Get the description of the Renderer. * * @return The description of the Renderer. */ String getDescription(); /** * Return the default filename extension to use. * * @return String */ String defaultFileExtension(); /** * Set the description of the Renderer. * * @param description * The description of the Renderer. */ void setDescription(String description); /** * Get the indicator for whether to show suppressed violations. * * @return <code>true</code> if suppressed violations should show, * <code>false</code> otherwise. */ boolean isShowSuppressedViolations(); /** * Set the indicator for whether to show suppressed violations. * * @param showSuppressedViolations * Whether to show suppressed violations. */ void setShowSuppressedViolations(boolean showSuppressedViolations); /** * Get the Writer for the Renderer. * * @return The Writer. */ Writer getWriter(); /** * Set the {@link FileNameRenderer} used to render file paths to the report. * Note that this renderer does not have to use the parameter to output paths. * Some report formats require a specific format for paths (eg a URI), and are * allowed to circumvent the provided strategy. * * @param fileNameRenderer a non-null file name renderer */ void setFileNameRenderer(FileNameRenderer fileNameRenderer); /** * Set the Writer for the Renderer. * * @param writer The Writer. */ void setWriter(Writer writer); /** * This method is called before any source files are processed. The Renderer * will have been fully initialized by the time this method is called, so * the Writer and other state will be available. * * @throws IOException */ void start() throws IOException; /** * This method is called each time a source file is processed. It is called * after {@link Renderer#start()}, but before * {@link Renderer#renderFileReport(Report)} and {@link Renderer#end()}. * * This method may be invoked by different threads which are processing * files independently. Therefore, any non-trivial implementation of this * method needs to be thread-safe. * * @param dataSource * The source file. */ void startFileAnalysis(TextFile dataSource); /** * Render the given file Report. There may be multiple Report instances * which need to be rendered if produced by different threads. It is called * after {@link Renderer#start()} and * {@link Renderer#startFileAnalysis(TextFile)}, but before * {@link Renderer#end()}. * * @param report * A file Report. * @throws IOException * * @see Report */ void renderFileReport(Report report) throws IOException; /** * This method is at the very end of the Rendering process, after * {@link Renderer#renderFileReport(Report)}. */ void end() throws IOException; void flush() throws IOException; /** * Sets the filename where the report should be written to. If no filename is provided, * the renderer should write to stdout. * * <p>Implementations must initialize the writer of the renderer. * * <p>See {@link AbstractRenderer#setReportFile(String)} for the default impl. * * @param reportFilename the filename (optional). */ @Experimental void setReportFile(String reportFilename); /** * Returns a new analysis listener, that handles violations by rendering * them in an implementation-defined way. */ // TODO the default implementation matches the current behavior, // ie violations are batched by file and forwarded to the renderer // when the file is done. Many renderers could directly handle // violations as they come though. default GlobalAnalysisListener newListener() throws IOException { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { this.start(); } return new GlobalAnalysisListener() { // guard for the close routine final Object reportMergeLock = new Object(); final GlobalReportBuilderListener configErrorReport = new GlobalReportBuilderListener(); @Override public void onConfigError(ConfigurationError error) { configErrorReport.onConfigError(error); } @Override public ListenerInitializer initializer() { return new ListenerInitializer() { @Override public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { Renderer.this.setFileNameRenderer(fileNameRenderer); } }; } @Override public FileAnalysisListener startFileAnalysis(TextFile file) { Renderer renderer = Renderer.this; renderer.startFileAnalysis(file); // this routine is thread-safe by contract return new FileAnalysisListener() { final ReportBuilderListener reportBuilder = new ReportBuilderListener(); @Override public void onRuleViolation(RuleViolation violation) { reportBuilder.onRuleViolation(violation); } @Override public void onSuppressedRuleViolation(SuppressedViolation violation) { reportBuilder.onSuppressedRuleViolation(violation); } @Override public void onError(ProcessingError error) { reportBuilder.onError(error); } @Override public void close() throws Exception { reportBuilder.close(); synchronized (reportMergeLock) { // TODO renderFileReport should be thread-safe instead try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { renderer.renderFileReport(reportBuilder.getResult()); } } } @Override public String toString() { return "FileRendererListener[" + Renderer.this + "]"; } }; } @Override public void close() throws Exception { configErrorReport.close(); Renderer.this.renderFileReport(configErrorReport.getResult()); try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.REPORTING)) { end(); flush(); } } }; } }
9,676
33.684588
121
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Renderer for IntelliJ IDEA integration. */ public class IDEAJRenderer extends AbstractIncrementingRenderer { private String classAndMethodName; private String fileName; public static final String NAME = "ideaj"; // TODO 7.0.0 use PropertyDescriptor<String> public static final PropertyDescriptor<String> FILE_NAME = PropertyFactory.stringProperty("fileName").desc("File name.").defaultValue("").build(); public static final PropertyDescriptor<String> SOURCE_PATH = PropertyFactory.stringProperty("sourcePath").desc("Source path.").defaultValue("").build(); public static final PropertyDescriptor<String> CLASS_AND_METHOD_NAME = PropertyFactory.stringProperty("classAndMethodName").desc("Class and Method name, pass '.method' when processing a directory.").defaultValue("").build(); private static final String FILE_SEPARATOR = System.getProperty("file.separator"); private static final String PATH_SEPARATOR = System.getProperty("path.separator"); public IDEAJRenderer() { super(NAME, "IntelliJ IDEA integration."); definePropertyDescriptor(FILE_NAME); definePropertyDescriptor(SOURCE_PATH); definePropertyDescriptor(CLASS_AND_METHOD_NAME); } @Override public String defaultFileExtension() { return "txt"; } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { classAndMethodName = getProperty(CLASS_AND_METHOD_NAME); fileName = getProperty(FILE_NAME); if (".method".equals(classAndMethodName)) { // working on a directory tree renderDirectory(writer, violations); } else { // working on one file renderFile(writer, violations); } } private void renderDirectory(PrintWriter writer, Iterator<RuleViolation> violations) throws IOException { SourcePath sourcePath = new SourcePath(getProperty(SOURCE_PATH)); StringBuilder buf = new StringBuilder(); while (violations.hasNext()) { buf.setLength(0); RuleViolation rv = violations.next(); buf.append(rv.getDescription()).append(System.lineSeparator()); // todo is this the right thing? vvvvvvvvvvvvvvvv buf.append(" at ").append(getFullyQualifiedClassName(rv.getFileId().getAbsolutePath(), sourcePath)).append(".method("); buf.append(rv.getFileId().getFileName()).append(':').append(rv.getBeginLine()).append(')'); writer.println(buf); } } private void renderFile(PrintWriter writer, Iterator<RuleViolation> violations) throws IOException { StringBuilder buf = new StringBuilder(); while (violations.hasNext()) { buf.setLength(0); RuleViolation rv = violations.next(); buf.append(rv.getDescription()).append(System.lineSeparator()); buf.append(" at ").append(classAndMethodName).append('(').append(fileName).append(':') .append(rv.getBeginLine()).append(')'); writer.println(buf); } } private String getFullyQualifiedClassName(String fileName, SourcePath sourcePath) { String classNameWithSlashes = sourcePath.clipPath(fileName); String className = classNameWithSlashes.replace(FILE_SEPARATOR.charAt(0), '.'); return className.substring(0, className.length() - ".java".length()); } private static class SourcePath { private Set<String> paths = new HashSet<>(); SourcePath(String sourcePathString) { for (StringTokenizer st = new StringTokenizer(sourcePathString, PATH_SEPARATOR); st.hasMoreTokens();) { paths.add(st.nextToken()); } } public String clipPath(String fullFilename) { for (String path : paths) { if (fullFilename.startsWith(path)) { return fullFilename.substring(path.length() + 1); } } throw new RuntimeException("Couldn't find src path for " + fullFilename); } } }
4,643
38.692308
161
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.PrintWriter; import java.io.Writer; import java.util.Objects; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.properties.AbstractPropertySource; import net.sourceforge.pmd.reporting.FileNameRenderer; /** * Abstract base class for {@link Renderer} implementations. */ public abstract class AbstractRenderer extends AbstractPropertySource implements Renderer { protected String name; protected String description; protected boolean showSuppressedViolations = true; protected PrintWriter writer; private FileNameRenderer fileNameRenderer = fileId -> fileId.getOriginalPath(); public AbstractRenderer(String name, String description) { this.name = name; this.description = description; } @Override protected String getPropertySourceType() { return "renderer"; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public boolean isShowSuppressedViolations() { return showSuppressedViolations; } @Override public void setShowSuppressedViolations(boolean showSuppressedViolations) { this.showSuppressedViolations = showSuppressedViolations; } @Override public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { this.fileNameRenderer = Objects.requireNonNull(fileNameRenderer); } /** * Determines the filename that should be used in the report for the * given ID. This uses the {@link FileNameRenderer} of this renderer. * In the PMD CLI, the file name renderer respects the {@link PMDConfiguration#getRelativizeRoots()} * relativize roots to output relative paths. * * <p>A renderer does not have to use this method to output paths. * Some report formats require a specific format for paths, eg URIs. * They can implement this ad-hoc. */ protected final String determineFileName(FileId fileId) { return fileNameRenderer.getDisplayName(fileId); } @Override public void setWriter(Writer writer) { this.writer = new PrintWriter(writer); } @Override public Writer getWriter() { return writer; } @Override public void flush() { if (writer == null) { // might happen, if no writer is set. E.g. in maven-pmd-plugin's PmdCollectingRenderer return; } try { this.writer.flush(); } finally { IOUtil.closeQuietly(writer); } } /** * {@inheritDoc} * * <p>This default implementation always uses the system default charset for the writer. * Overwrite in specific renderers to support other charsets. */ @Experimental @Override public void setReportFile(String reportFilename) { this.setWriter(IOUtil.createWriter(reportFilename)); } }
3,457
26.887097
104
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateIssue.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; /** * Structure for the Code Climate Issue spec * (https://github.com/codeclimate/spec/blob/master/SPEC.md#issues) */ public class CodeClimateIssue { public String type; public String check_name; // SUPPRESS CHECKSTYLE underscore is required per codeclimate format public String description; public Content content; public String[] categories; public Location location; public String severity; public int remediation_points; // SUPPRESS CHECKSTYLE underscore is required per codeclimate format public CodeClimateIssue() { type = "issue"; // the default type for PMD violations when reporting as code climate } /** * Location structure */ public static class Location { public String path; public Lines lines; private static final class Lines { public int begin; public int end; } public Location(String path, int beginLine, int endLine) { this.path = path; this.lines = new Lines(); lines.begin = beginLine; lines.end = endLine; } } /** * Content structure */ public static class Content { public String body; /** * Strip out all newlines from the body * * @param body The text to compose the content from */ public Content(String body) { this.body = body.replace(System.lineSeparator(), " "); } } }
1,630
25.737705
103
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XSLTRenderer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.nio.file.Files; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Renderer to XML format with a XSL Transformation applied. * * @author Romain Pelisse, belaran@gmail.com */ public class XSLTRenderer extends XMLRenderer { public static final String NAME = "xslt"; // TODO 7.0.0 use PropertyDescriptor<Optional<File>> public static final PropertyDescriptor<String> XSLT_FILENAME = PropertyFactory.stringProperty("xsltFilename").desc("The XSLT file name.").defaultValue("").build(); private Transformer transformer; private String xsltFilename = "/pmd-nicerhtml.xsl"; private Writer outputWriter; private StringWriter stringWriter; public XSLTRenderer() { super(); setName(NAME); setDescription("XML with a XSL Transformation applied."); definePropertyDescriptor(XSLT_FILENAME); } @Override public String defaultFileExtension() { return "xsl"; } @Override public void start() throws IOException { String xsltFilenameProperty = getProperty(XSLT_FILENAME); if (StringUtils.isNotBlank(xsltFilenameProperty)) { File file = new File(xsltFilenameProperty); if (file.exists() && file.canRead()) { this.xsltFilename = xsltFilenameProperty; } } // We keep the inital writer to put the final html output this.outputWriter = getWriter(); // We use a new one to store the XML... this.stringWriter = new StringWriter(); setWriter(stringWriter); // If don't find the xsl no need to bother doing the all report, // so we check this here... InputStream xslt = null; File file = new File(this.xsltFilename); if (file.exists() && file.canRead()) { xslt = Files.newInputStream(file.toPath()); } else { xslt = this.getClass().getResourceAsStream(this.xsltFilename); } if (xslt == null) { throw new FileNotFoundException("Can't find XSLT file: " + this.xsltFilename); } try (InputStream stream = xslt) { this.prepareTransformer(stream); } // Now we build the XML file super.start(); } /** * Prepare the transformer, doing the proper "building"... * * @param xslt * The stylesheet provided as an InputStream */ private void prepareTransformer(InputStream xslt) { try { // Get a TransformerFactory object TransformerFactory factory = TransformerFactory.newInstance(); StreamSource src = new StreamSource(xslt); // Get an XSL Transformer object this.transformer = factory.newTransformer(src); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } } @Override public void end() throws IOException { // First we finish the XML report super.end(); // Now we transform it using XSLT Document doc = this.getDocument(stringWriter.toString()); this.transform(doc); } private void transform(Document doc) { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(this.outputWriter); try { transformer.transform(source, result); } catch (TransformerException e) { throw new RuntimeException(e); } } private Document getDocument(String xml) { try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return parser.parse(new InputSource(new StringReader(xml))); } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } } }
4,865
32.791667
167
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/JsonRenderer.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.ViolationSuppressor; import com.google.gson.stream.JsonWriter; public class JsonRenderer extends AbstractIncrementingRenderer { public static final String NAME = "json"; // TODO do we make this public? It would make it possible to write eg // if (jsonObject.getInt("formatVersion") > JsonRenderer.FORMAT_VERSION) // /* handle unsupported version */ // because the JsonRenderer.FORMAT_VERSION would be hardcoded by the compiler private static final int FORMAT_VERSION = 0; private static final Map<String, String> SUPPRESSION_TYPE_FORMAT_0 = new HashMap<>(); static { SUPPRESSION_TYPE_FORMAT_0.put(ViolationSuppressor.NOPMD_COMMENT_SUPPRESSOR.getId(), "nopmd"); // Java and Apex Suppression Types // see net.sourceforge.pmd.lang.java.rule.internal.JavaRuleViolationFactory.JAVA_ANNOT_SUPPRESSOR // see net.sourceforge.pmd.lang.apex.rule.internal.ApexRuleViolationFactory.APEX_ANNOT_SUPPRESSOR SUPPRESSION_TYPE_FORMAT_0.put("@SuppressWarnings", "annotation"); } private JsonWriter jsonWriter; public JsonRenderer() { super(NAME, "JSON format."); } @Override public String defaultFileExtension() { return "json"; } @Override public void start() throws IOException { jsonWriter = new JsonWriter(writer); jsonWriter.setHtmlSafe(true); jsonWriter.setIndent(" "); jsonWriter.beginObject(); jsonWriter.name("formatVersion").value(FORMAT_VERSION); jsonWriter.name("pmdVersion").value(PMDVersion.VERSION); jsonWriter.name("timestamp").value(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(new Date())); jsonWriter.name("files").beginArray(); } @Override public void renderFileViolations(Iterator<RuleViolation> violations) throws IOException { String filename = null; while (violations.hasNext()) { RuleViolation rv = violations.next(); String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { // Not first file ? jsonWriter.endArray(); // violations jsonWriter.endObject(); // file object } filename = nextFilename; jsonWriter.beginObject(); jsonWriter.name("filename").value(filename); jsonWriter.name("violations").beginArray(); } renderSingleViolation(rv); } jsonWriter.endArray(); // violations jsonWriter.endObject(); // file object } private void renderSingleViolation(RuleViolation rv) throws IOException { renderSingleViolation(rv, null, null); } private void renderSingleViolation(RuleViolation rv, String suppressionType, String userMsg) throws IOException { jsonWriter.beginObject(); jsonWriter.name("beginline").value(rv.getBeginLine()); jsonWriter.name("begincolumn").value(rv.getBeginColumn()); jsonWriter.name("endline").value(rv.getEndLine()); jsonWriter.name("endcolumn").value(rv.getEndColumn()); jsonWriter.name("description").value(rv.getDescription()); jsonWriter.name("rule").value(rv.getRule().getName()); jsonWriter.name("ruleset").value(rv.getRule().getRuleSetName()); jsonWriter.name("priority").value(rv.getRule().getPriority().getPriority()); if (StringUtils.isNotBlank(rv.getRule().getExternalInfoUrl())) { jsonWriter.name("externalInfoUrl").value(rv.getRule().getExternalInfoUrl()); } if (StringUtils.isNotBlank(suppressionType)) { jsonWriter.name("suppressiontype").value(suppressionType); } if (StringUtils.isNotBlank(userMsg)) { jsonWriter.name("usermsg").value(userMsg); } jsonWriter.endObject(); } private String getSuppressionType(ViolationSuppressor suppressor) { return SUPPRESSION_TYPE_FORMAT_0.getOrDefault(suppressor.getId(), suppressor.getId()); } @Override public void end() throws IOException { jsonWriter.endArray(); // files jsonWriter.name("suppressedViolations").beginArray(); String filename = null; if (!this.suppressed.isEmpty()) { for (Report.SuppressedViolation s : this.suppressed) { RuleViolation rv = s.getRuleViolation(); String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { // Not first file ? jsonWriter.endArray(); // violations jsonWriter.endObject(); // file object } filename = nextFilename; jsonWriter.beginObject(); jsonWriter.name("filename").value(filename); jsonWriter.name("violations").beginArray(); } renderSingleViolation(rv, getSuppressionType(s.getSuppressor()), s.getUserMessage()); } jsonWriter.endArray(); // violations jsonWriter.endObject(); // file object } jsonWriter.endArray(); jsonWriter.name("processingErrors").beginArray(); for (Report.ProcessingError error : this.errors) { jsonWriter.beginObject(); jsonWriter.name("filename").value(determineFileName(error.getFileId())); jsonWriter.name("message").value(error.getMsg()); jsonWriter.name("detail").value(error.getDetail()); jsonWriter.endObject(); } jsonWriter.endArray(); jsonWriter.name("configurationErrors").beginArray(); for (Report.ConfigurationError error : this.configErrors) { jsonWriter.beginObject(); jsonWriter.name("rule").value(error.rule().getName()); jsonWriter.name("ruleset").value(error.rule().getRuleSetName()); jsonWriter.name("message").value(error.issue()); jsonWriter.endObject(); } jsonWriter.endArray(); jsonWriter.endObject(); jsonWriter.flush(); } }
6,859
37.977273
117
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLog.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers.internal.sarif; import java.util.List; import java.util.Set; import com.google.gson.annotations.SerializedName; // Generated by delombok at Mon Jan 25 09:12:45 CET 2021 // CPD-OFF public class SarifLog { /** * The URI of the JSON schema corresponding to the version. */ @SerializedName("$schema") private String schema; /** * The SARIF format version of this log file. */ private String version; /** * The set of runs contained in this log file. */ private List<Run> runs; /** * A location within a programming artifact. */ public static class Location { /** * Value that distinguishes this location from all other locations within a single result object. */ private Integer id; /** * Identifies the artifact and region. */ private PhysicalLocation physicalLocation; @java.lang.SuppressWarnings("all") Location(final Integer id, final PhysicalLocation physicalLocation) { this.id = id; this.physicalLocation = physicalLocation; } @java.lang.SuppressWarnings("all") public static class LocationBuilder { @java.lang.SuppressWarnings("all") private Integer id; @java.lang.SuppressWarnings("all") private PhysicalLocation physicalLocation; @java.lang.SuppressWarnings("all") LocationBuilder() { } /** * Value that distinguishes this location from all other locations within a single result object. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Location.LocationBuilder id(final Integer id) { this.id = id; return this; } /** * Identifies the artifact and region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Location.LocationBuilder physicalLocation(final PhysicalLocation physicalLocation) { this.physicalLocation = physicalLocation; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Location build() { return new SarifLog.Location(this.id, this.physicalLocation); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Location.LocationBuilder(id=" + this.id + ", physicalLocation=" + this.physicalLocation + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Location.LocationBuilder builder() { return new SarifLog.Location.LocationBuilder(); } /** * Value that distinguishes this location from all other locations within a single result object. */ @java.lang.SuppressWarnings("all") public Integer getId() { return this.id; } /** * Identifies the artifact and region. */ @java.lang.SuppressWarnings("all") public PhysicalLocation getPhysicalLocation() { return this.physicalLocation; } /** * Value that distinguishes this location from all other locations within a single result object. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Location setId(final Integer id) { this.id = id; return this; } /** * Identifies the artifact and region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Location setPhysicalLocation(final PhysicalLocation physicalLocation) { this.physicalLocation = physicalLocation; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Location)) { return false; } final SarifLog.Location other = (SarifLog.Location) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$id = this.getId(); final java.lang.Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) { return false; } final java.lang.Object this$physicalLocation = this.getPhysicalLocation(); final java.lang.Object other$physicalLocation = other.getPhysicalLocation(); if (this$physicalLocation == null ? other$physicalLocation != null : !this$physicalLocation.equals(other$physicalLocation)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Location; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $id = this.getId(); result = result * PRIME + ($id == null ? 43 : $id.hashCode()); final java.lang.Object $physicalLocation = this.getPhysicalLocation(); result = result * PRIME + ($physicalLocation == null ? 43 : $physicalLocation.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Location(id=" + this.getId() + ", physicalLocation=" + this.getPhysicalLocation() + ")"; } } /** * Specifies the location of an artifact. */ public static class ArtifactLocation { /** * A string containing a valid relative or absolute URI. */ private String uri; /** * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property * is interpreted. */ private String uriBaseId; /** * The index within the run artifacts array of the artifact object associated with the artifact location. */ private Integer index; @java.lang.SuppressWarnings("all") ArtifactLocation(final String uri, final String uriBaseId, final Integer index) { this.uri = uri; this.uriBaseId = uriBaseId; this.index = index; } @java.lang.SuppressWarnings("all") public static class ArtifactLocationBuilder { @java.lang.SuppressWarnings("all") private String uri; @java.lang.SuppressWarnings("all") private String uriBaseId; @java.lang.SuppressWarnings("all") private Integer index; @java.lang.SuppressWarnings("all") ArtifactLocationBuilder() { } /** * A string containing a valid relative or absolute URI. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation.ArtifactLocationBuilder uri(final String uri) { this.uri = uri; return this; } /** * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property * is interpreted. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation.ArtifactLocationBuilder uriBaseId(final String uriBaseId) { this.uriBaseId = uriBaseId; return this; } /** * The index within the run artifacts array of the artifact object associated with the artifact location. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation.ArtifactLocationBuilder index(final Integer index) { this.index = index; return this; } @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation build() { return new SarifLog.ArtifactLocation(this.uri, this.uriBaseId, this.index); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ArtifactLocation.ArtifactLocationBuilder(uri=" + this.uri + ", uriBaseId=" + this.uriBaseId + ", index=" + this.index + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.ArtifactLocation.ArtifactLocationBuilder builder() { return new SarifLog.ArtifactLocation.ArtifactLocationBuilder(); } /** * A string containing a valid relative or absolute URI. */ @java.lang.SuppressWarnings("all") public String getUri() { return this.uri; } /** * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property * is interpreted. */ @java.lang.SuppressWarnings("all") public String getUriBaseId() { return this.uriBaseId; } /** * The index within the run artifacts array of the artifact object associated with the artifact location. */ @java.lang.SuppressWarnings("all") public Integer getIndex() { return this.index; } /** * A string containing a valid relative or absolute URI. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation setUri(final String uri) { this.uri = uri; return this; } /** * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property * is interpreted. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation setUriBaseId(final String uriBaseId) { this.uriBaseId = uriBaseId; return this; } /** * The index within the run artifacts array of the artifact object associated with the artifact location. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ArtifactLocation setIndex(final Integer index) { this.index = index; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.ArtifactLocation)) { return false; } final SarifLog.ArtifactLocation other = (SarifLog.ArtifactLocation) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$uri = this.getUri(); final java.lang.Object other$uri = other.getUri(); if (this$uri == null ? other$uri != null : !this$uri.equals(other$uri)) { return false; } final java.lang.Object this$uriBaseId = this.getUriBaseId(); final java.lang.Object other$uriBaseId = other.getUriBaseId(); if (this$uriBaseId == null ? other$uriBaseId != null : !this$uriBaseId.equals(other$uriBaseId)) { return false; } final java.lang.Object this$index = this.getIndex(); final java.lang.Object other$index = other.getIndex(); if (this$index == null ? other$index != null : !this$index.equals(other$index)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.ArtifactLocation; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $uri = this.getUri(); result = result * PRIME + ($uri == null ? 43 : $uri.hashCode()); final java.lang.Object $uriBaseId = this.getUriBaseId(); result = result * PRIME + ($uriBaseId == null ? 43 : $uriBaseId.hashCode()); final java.lang.Object $index = this.getIndex(); result = result * PRIME + ($index == null ? 43 : $index.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ArtifactLocation(uri=" + this.getUri() + ", uriBaseId=" + this.getUriBaseId() + ", index=" + this.getIndex() + ")"; } } /** * A physical location relevant to a result. Specifies a reference to a programming artifact together with a range * of bytes or characters within that artifact. */ public static class PhysicalLocation { /** * The location of the artifact. */ private ArtifactLocation artifactLocation; /** * Specifies a portion of the artifact. */ private Region region; @java.lang.SuppressWarnings("all") PhysicalLocation(final ArtifactLocation artifactLocation, final Region region) { this.artifactLocation = artifactLocation; this.region = region; } @java.lang.SuppressWarnings("all") public static class PhysicalLocationBuilder { @java.lang.SuppressWarnings("all") private ArtifactLocation artifactLocation; @java.lang.SuppressWarnings("all") private Region region; @java.lang.SuppressWarnings("all") PhysicalLocationBuilder() { } /** * The location of the artifact. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PhysicalLocation.PhysicalLocationBuilder artifactLocation(final ArtifactLocation artifactLocation) { this.artifactLocation = artifactLocation; return this; } /** * Specifies a portion of the artifact. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PhysicalLocation.PhysicalLocationBuilder region(final Region region) { this.region = region; return this; } @java.lang.SuppressWarnings("all") public SarifLog.PhysicalLocation build() { return new SarifLog.PhysicalLocation(this.artifactLocation, this.region); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.PhysicalLocation.PhysicalLocationBuilder(artifactLocation=" + this.artifactLocation + ", region=" + this.region + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.PhysicalLocation.PhysicalLocationBuilder builder() { return new SarifLog.PhysicalLocation.PhysicalLocationBuilder(); } /** * The location of the artifact. */ @java.lang.SuppressWarnings("all") public ArtifactLocation getArtifactLocation() { return this.artifactLocation; } /** * Specifies a portion of the artifact. */ @java.lang.SuppressWarnings("all") public Region getRegion() { return this.region; } /** * The location of the artifact. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PhysicalLocation setArtifactLocation(final ArtifactLocation artifactLocation) { this.artifactLocation = artifactLocation; return this; } /** * Specifies a portion of the artifact. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PhysicalLocation setRegion(final Region region) { this.region = region; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.PhysicalLocation)) { return false; } final SarifLog.PhysicalLocation other = (SarifLog.PhysicalLocation) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$artifactLocation = this.getArtifactLocation(); final java.lang.Object other$artifactLocation = other.getArtifactLocation(); if (this$artifactLocation == null ? other$artifactLocation != null : !this$artifactLocation.equals(other$artifactLocation)) { return false; } final java.lang.Object this$region = this.getRegion(); final java.lang.Object other$region = other.getRegion(); if (this$region == null ? other$region != null : !this$region.equals(other$region)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.PhysicalLocation; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $artifactLocation = this.getArtifactLocation(); result = result * PRIME + ($artifactLocation == null ? 43 : $artifactLocation.hashCode()); final java.lang.Object $region = this.getRegion(); result = result * PRIME + ($region == null ? 43 : $region.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.PhysicalLocation(artifactLocation=" + this.getArtifactLocation() + ", region=" + this.getRegion() + ")"; } } /** * Key/value pairs that provide additional information about the object. */ public static class PropertyBag { /** * The name of the rule set. */ private String ruleset; /** * The pmd priority of the rule. */ private Integer priority; /** * A set of distinct strings that provide additional information. This is SARIF 2.1.0 Schema. */ private Set<String> tags; @java.lang.SuppressWarnings("all") PropertyBag(final String ruleset, final Integer priority, final Set<String> tags) { this.ruleset = ruleset; this.priority = priority; this.tags = tags; } @java.lang.SuppressWarnings("all") public static class PropertyBagBuilder { @java.lang.SuppressWarnings("all") private String ruleset; @java.lang.SuppressWarnings("all") private Integer priority; @java.lang.SuppressWarnings("all") private Set<String> tags; @java.lang.SuppressWarnings("all") PropertyBagBuilder() { } /** * The name of the rule set. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag.PropertyBagBuilder ruleset(final String ruleset) { this.ruleset = ruleset; return this; } /** * The pmd priority of the rule. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag.PropertyBagBuilder priority(final Integer priority) { this.priority = priority; return this; } /** * A set of distinct strings that provide additional information. This is SARIF 2.1.0 Schema. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag.PropertyBagBuilder tags(final Set<String> tags) { this.tags = tags; return this; } @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag build() { return new SarifLog.PropertyBag(this.ruleset, this.priority, this.tags); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.PropertyBag.PropertyBagBuilder(ruleset=" + this.ruleset + ", priority=" + this.priority + ", tags=" + this.tags + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.PropertyBag.PropertyBagBuilder builder() { return new SarifLog.PropertyBag.PropertyBagBuilder(); } /** * The name of the rule set. */ @java.lang.SuppressWarnings("all") public String getRuleset() { return this.ruleset; } /** * The pmd priority of the rule. */ @java.lang.SuppressWarnings("all") public Integer getPriority() { return this.priority; } /** * A set of distinct strings that provide additional information. This is SARIF 2.1.0 Schema. */ @java.lang.SuppressWarnings("all") public Set<String> getTags() { return this.tags; } /** * The name of the rule set. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag setRuleset(final String ruleset) { this.ruleset = ruleset; return this; } /** * The pmd priority of the rule. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag setPriority(final Integer priority) { this.priority = priority; return this; } /** * The set of distinct strings that provide additional information. This is SARIF 2.1.0 Schema. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.PropertyBag setTags(final Set<String> tags) { this.tags = tags; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.PropertyBag)) { return false; } final SarifLog.PropertyBag other = (SarifLog.PropertyBag) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$ruleset = this.getRuleset(); final java.lang.Object other$ruleset = other.getRuleset(); if (this$ruleset == null ? other$ruleset != null : !this$ruleset.equals(other$ruleset)) { return false; } final java.lang.Object this$priority = this.getPriority(); final java.lang.Object other$priority = other.getPriority(); if (this$priority == null ? other$priority != null : !this$priority.equals(other$priority)) { return false; } final java.lang.Object this$tags = this.getTags(); final java.lang.Object other$tags = other.getTags(); if (this$tags == null ? other$tags != null : !this$tags.equals(other$tags)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.PropertyBag; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $ruleset = this.getRuleset(); result = result * PRIME + ($ruleset == null ? 43 : $ruleset.hashCode()); final java.lang.Object $priority = this.getPriority(); result = result * PRIME + ($priority == null ? 43 : $priority.hashCode()); final java.lang.Object $tags = this.getTags(); result = result * PRIME + ($tags == null ? 43 : $tags.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.PropertyBag(ruleset=" + this.getRuleset() + ", priority=" + this.getPriority() + ", tags=" + this.getTags() + ")"; } } /** * A region within an artifact where a result was detected. */ public static class Region { /** * The line number of the first character in the region. */ private Integer startLine; /** * The column number of the first character in the region. */ private Integer startColumn; /** * The line number of the last character in the region. */ private Integer endLine; /** * The column number of the character following the end of the region. */ private Integer endColumn; @java.lang.SuppressWarnings("all") Region(final Integer startLine, final Integer startColumn, final Integer endLine, final Integer endColumn) { this.startLine = startLine; this.startColumn = startColumn; this.endLine = endLine; this.endColumn = endColumn; } @java.lang.SuppressWarnings("all") public static class RegionBuilder { @java.lang.SuppressWarnings("all") private Integer startLine; @java.lang.SuppressWarnings("all") private Integer startColumn; @java.lang.SuppressWarnings("all") private Integer endLine; @java.lang.SuppressWarnings("all") private Integer endColumn; @java.lang.SuppressWarnings("all") RegionBuilder() { } /** * The line number of the first character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region.RegionBuilder startLine(final Integer startLine) { this.startLine = startLine; return this; } /** * The column number of the first character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region.RegionBuilder startColumn(final Integer startColumn) { this.startColumn = startColumn; return this; } /** * The line number of the last character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region.RegionBuilder endLine(final Integer endLine) { this.endLine = endLine; return this; } /** * The column number of the character following the end of the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region.RegionBuilder endColumn(final Integer endColumn) { this.endColumn = endColumn; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Region build() { return new SarifLog.Region(this.startLine, this.startColumn, this.endLine, this.endColumn); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Region.RegionBuilder(startLine=" + this.startLine + ", startColumn=" + this.startColumn + ", endLine=" + this.endLine + ", endColumn=" + this.endColumn + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Region.RegionBuilder builder() { return new SarifLog.Region.RegionBuilder(); } /** * The line number of the first character in the region. */ @java.lang.SuppressWarnings("all") public Integer getStartLine() { return this.startLine; } /** * The column number of the first character in the region. */ @java.lang.SuppressWarnings("all") public Integer getStartColumn() { return this.startColumn; } /** * The line number of the last character in the region. */ @java.lang.SuppressWarnings("all") public Integer getEndLine() { return this.endLine; } /** * The column number of the character following the end of the region. */ @java.lang.SuppressWarnings("all") public Integer getEndColumn() { return this.endColumn; } /** * The line number of the first character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region setStartLine(final Integer startLine) { this.startLine = startLine; return this; } /** * The column number of the first character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region setStartColumn(final Integer startColumn) { this.startColumn = startColumn; return this; } /** * The line number of the last character in the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region setEndLine(final Integer endLine) { this.endLine = endLine; return this; } /** * The column number of the character following the end of the region. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Region setEndColumn(final Integer endColumn) { this.endColumn = endColumn; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Region)) { return false; } final SarifLog.Region other = (SarifLog.Region) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$startLine = this.getStartLine(); final java.lang.Object other$startLine = other.getStartLine(); if (this$startLine == null ? other$startLine != null : !this$startLine.equals(other$startLine)) { return false; } final java.lang.Object this$startColumn = this.getStartColumn(); final java.lang.Object other$startColumn = other.getStartColumn(); if (this$startColumn == null ? other$startColumn != null : !this$startColumn.equals(other$startColumn)) { return false; } final java.lang.Object this$endLine = this.getEndLine(); final java.lang.Object other$endLine = other.getEndLine(); if (this$endLine == null ? other$endLine != null : !this$endLine.equals(other$endLine)) { return false; } final java.lang.Object this$endColumn = this.getEndColumn(); final java.lang.Object other$endColumn = other.getEndColumn(); if (this$endColumn == null ? other$endColumn != null : !this$endColumn.equals(other$endColumn)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Region; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $startLine = this.getStartLine(); result = result * PRIME + ($startLine == null ? 43 : $startLine.hashCode()); final java.lang.Object $startColumn = this.getStartColumn(); result = result * PRIME + ($startColumn == null ? 43 : $startColumn.hashCode()); final java.lang.Object $endLine = this.getEndLine(); result = result * PRIME + ($endLine == null ? 43 : $endLine.hashCode()); final java.lang.Object $endColumn = this.getEndColumn(); result = result * PRIME + ($endColumn == null ? 43 : $endColumn.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Region(startLine=" + this.getStartLine() + ", startColumn=" + this.getStartColumn() + ", endLine=" + this.getEndLine() + ", endColumn=" + this.getEndColumn() + ")"; } } /** * A result produced by an analysis tool. */ public static class Result { /** * The stable, unique identifier of the rule, if any, to which this result is relevant. */ private String ruleId; /** * The index link the rule, if any, to which this result is relevant. */ private Integer ruleIndex; /** * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. */ private Message message; /** * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. */ private List<Location> locations; /** * Key/value pairs that provide additional information about the address. */ private PropertyBag properties; @java.lang.SuppressWarnings("all") Result(final String ruleId, final Integer ruleIndex, final Message message, final List<Location> locations, final PropertyBag properties) { this.ruleId = ruleId; this.ruleIndex = ruleIndex; this.message = message; this.locations = locations; this.properties = properties; } @java.lang.SuppressWarnings("all") public static class ResultBuilder { @java.lang.SuppressWarnings("all") private String ruleId; @java.lang.SuppressWarnings("all") private Integer ruleIndex; @java.lang.SuppressWarnings("all") private Message message; @java.lang.SuppressWarnings("all") private List<Location> locations; @java.lang.SuppressWarnings("all") private PropertyBag properties; @java.lang.SuppressWarnings("all") ResultBuilder() { } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result.ResultBuilder ruleId(final String ruleId) { this.ruleId = ruleId; return this; } /** * The index link the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result.ResultBuilder ruleIndex(final Integer ruleIndex) { this.ruleIndex = ruleIndex; return this; } /** * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result.ResultBuilder message(final Message message) { this.message = message; return this; } /** * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result.ResultBuilder locations(final List<Location> locations) { this.locations = locations; return this; } /** * Key/value pairs that provide additional information about the address. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result.ResultBuilder properties(final PropertyBag properties) { this.properties = properties; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Result build() { return new SarifLog.Result(this.ruleId, this.ruleIndex, this.message, this.locations, this.properties); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Result.ResultBuilder(ruleId=" + this.ruleId + ", ruleIndex=" + this.ruleIndex + ", message=" + this.message + ", locations=" + this.locations + ", properties=" + this.properties + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Result.ResultBuilder builder() { return new SarifLog.Result.ResultBuilder(); } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. */ @java.lang.SuppressWarnings("all") public String getRuleId() { return this.ruleId; } /** * The index link the rule, if any, to which this result is relevant. */ @java.lang.SuppressWarnings("all") public Integer getRuleIndex() { return this.ruleIndex; } /** * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. */ @java.lang.SuppressWarnings("all") public Message getMessage() { return this.message; } /** * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. */ @java.lang.SuppressWarnings("all") public List<Location> getLocations() { return this.locations; } /** * Key/value pairs that provide additional information about the address. */ @java.lang.SuppressWarnings("all") public PropertyBag getProperties() { return this.properties; } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result setRuleId(final String ruleId) { this.ruleId = ruleId; return this; } /** * The index link the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result setRuleIndex(final Integer ruleIndex) { this.ruleIndex = ruleIndex; return this; } /** * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result setMessage(final Message message) { this.message = message; return this; } /** * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result setLocations(final List<Location> locations) { this.locations = locations; return this; } /** * Key/value pairs that provide additional information about the address. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Result setProperties(final PropertyBag properties) { this.properties = properties; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Result)) { return false; } final SarifLog.Result other = (SarifLog.Result) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$ruleId = this.getRuleId(); final java.lang.Object other$ruleId = other.getRuleId(); if (this$ruleId == null ? other$ruleId != null : !this$ruleId.equals(other$ruleId)) { return false; } final java.lang.Object this$ruleIndex = this.getRuleIndex(); final java.lang.Object other$ruleIndex = other.getRuleIndex(); if (this$ruleIndex == null ? other$ruleIndex != null : !this$ruleIndex.equals(other$ruleIndex)) { return false; } final java.lang.Object this$message = this.getMessage(); final java.lang.Object other$message = other.getMessage(); if (this$message == null ? other$message != null : !this$message.equals(other$message)) { return false; } final java.lang.Object this$locations = this.getLocations(); final java.lang.Object other$locations = other.getLocations(); if (this$locations == null ? other$locations != null : !this$locations.equals(other$locations)) { return false; } final java.lang.Object this$properties = this.getProperties(); final java.lang.Object other$properties = other.getProperties(); if (this$properties == null ? other$properties != null : !this$properties.equals(other$properties)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Result; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $ruleId = this.getRuleId(); result = result * PRIME + ($ruleId == null ? 43 : $ruleId.hashCode()); final java.lang.Object $ruleIndex = this.getRuleIndex(); result = result * PRIME + ($ruleIndex == null ? 43 : $ruleIndex.hashCode()); final java.lang.Object $message = this.getMessage(); result = result * PRIME + ($message == null ? 43 : $message.hashCode()); final java.lang.Object $locations = this.getLocations(); result = result * PRIME + ($locations == null ? 43 : $locations.hashCode()); final java.lang.Object $properties = this.getProperties(); result = result * PRIME + ($properties == null ? 43 : $properties.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Result(ruleId=" + this.getRuleId() + ", ruleIndex=" + this.getRuleIndex() + ", message=" + this.getMessage() + ", locations=" + this.getLocations() + ", properties=" + this.getProperties() + ")"; } } /** * Encapsulates a message intended to be read by the end user. */ public static class Message { /** * A plain text message string. */ private String text; /** * A Markdown message string. */ private String markdown; /** * The identifier for this message. */ private String id; @java.lang.SuppressWarnings("all") Message(final String text, final String markdown, final String id) { this.text = text; this.markdown = markdown; this.id = id; } @java.lang.SuppressWarnings("all") public static class MessageBuilder { @java.lang.SuppressWarnings("all") private String text; @java.lang.SuppressWarnings("all") private String markdown; @java.lang.SuppressWarnings("all") private String id; @java.lang.SuppressWarnings("all") MessageBuilder() { } /** * A plain text message string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message.MessageBuilder text(final String text) { this.text = text; return this; } /** * A Markdown message string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message.MessageBuilder markdown(final String markdown) { this.markdown = markdown; return this; } /** * The identifier for this message. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message.MessageBuilder id(final String id) { this.id = id; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Message build() { return new SarifLog.Message(this.text, this.markdown, this.id); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Message.MessageBuilder(text=" + this.text + ", markdown=" + this.markdown + ", id=" + this.id + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Message.MessageBuilder builder() { return new SarifLog.Message.MessageBuilder(); } /** * A plain text message string. */ @java.lang.SuppressWarnings("all") public String getText() { return this.text; } /** * A Markdown message string. */ @java.lang.SuppressWarnings("all") public String getMarkdown() { return this.markdown; } /** * The identifier for this message. */ @java.lang.SuppressWarnings("all") public String getId() { return this.id; } /** * A plain text message string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message setText(final String text) { this.text = text; return this; } /** * A Markdown message string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message setMarkdown(final String markdown) { this.markdown = markdown; return this; } /** * The identifier for this message. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Message setId(final String id) { this.id = id; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Message)) { return false; } final SarifLog.Message other = (SarifLog.Message) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$text = this.getText(); final java.lang.Object other$text = other.getText(); if (this$text == null ? other$text != null : !this$text.equals(other$text)) { return false; } final java.lang.Object this$markdown = this.getMarkdown(); final java.lang.Object other$markdown = other.getMarkdown(); if (this$markdown == null ? other$markdown != null : !this$markdown.equals(other$markdown)) { return false; } final java.lang.Object this$id = this.getId(); final java.lang.Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Message; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $text = this.getText(); result = result * PRIME + ($text == null ? 43 : $text.hashCode()); final java.lang.Object $markdown = this.getMarkdown(); result = result * PRIME + ($markdown == null ? 43 : $markdown.hashCode()); final java.lang.Object $id = this.getId(); result = result * PRIME + ($id == null ? 43 : $id.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Message(text=" + this.getText() + ", markdown=" + this.getMarkdown() + ", id=" + this.getId() + ")"; } } /** * Describes a single run of an analysis tool, and contains the reported output of that run. */ public static class Run { /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long * as context around the tool run (tool command-line arguments and the like) is identical for all aggregated files. */ private Tool tool; /** * The set of results contained in an SARIF log. The results array can be omitted when a run is solely exporting * rules metadata. It must be present (but may be empty) if a log file represents an actual scan. */ private List<Result> results; /** * The set of invocations providing information about the tool execution such as configuration errors or runtime * exceptions */ private List<Invocation> invocations; @java.lang.SuppressWarnings("all") Run(final Tool tool, final List<Result> results, final List<Invocation> invocations) { this.tool = tool; this.results = results; this.invocations = invocations; } @java.lang.SuppressWarnings("all") public static class RunBuilder { @java.lang.SuppressWarnings("all") private Tool tool; @java.lang.SuppressWarnings("all") private java.util.ArrayList<Result> results; @java.lang.SuppressWarnings("all") private List<Invocation> invocations; @java.lang.SuppressWarnings("all") RunBuilder() { } /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long * as context around the tool run (tool command-line arguments and the like) is identical for all aggregated files. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Run.RunBuilder tool(final Tool tool) { this.tool = tool; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Run.RunBuilder result(final Result result) { if (this.results == null) { this.results = new java.util.ArrayList<Result>(); } this.results.add(result); return this; } @java.lang.SuppressWarnings("all") public SarifLog.Run.RunBuilder results(final java.util.Collection<? extends Result> results) { if (results == null) { throw new java.lang.NullPointerException("results cannot be null"); } if (this.results == null) { this.results = new java.util.ArrayList<Result>(); } this.results.addAll(results); return this; } @java.lang.SuppressWarnings("all") public SarifLog.Run.RunBuilder clearResults() { if (this.results != null) { this.results.clear(); } return this; } /** * The set of invocations providing information about the tool execution such as configuration errors or runtime * exceptions * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Run.RunBuilder invocations(final List<Invocation> invocations) { this.invocations = invocations; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Run build() { java.util.List<Result> results; switch (this.results == null ? 0 : this.results.size()) { case 0: results = java.util.Collections.emptyList(); break; case 1: results = java.util.Collections.singletonList(this.results.get(0)); break; default: results = java.util.Collections.unmodifiableList(new java.util.ArrayList<Result>(this.results)); } return new SarifLog.Run(this.tool, results, this.invocations); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Run.RunBuilder(tool=" + this.tool + ", results=" + this.results + ", invocations=" + this.invocations + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Run.RunBuilder builder() { return new SarifLog.Run.RunBuilder(); } /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long * as context around the tool run (tool command-line arguments and the like) is identical for all aggregated files. */ @java.lang.SuppressWarnings("all") public Tool getTool() { return this.tool; } /** * The set of results contained in an SARIF log. The results array can be omitted when a run is solely exporting * rules metadata. It must be present (but may be empty) if a log file represents an actual scan. */ @java.lang.SuppressWarnings("all") public List<Result> getResults() { return this.results; } /** * The set of invocations providing information about the tool execution such as configuration errors or runtime * exceptions */ @java.lang.SuppressWarnings("all") public List<Invocation> getInvocations() { return this.invocations; } /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long * as context around the tool run (tool command-line arguments and the like) is identical for all aggregated files. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Run setTool(final Tool tool) { this.tool = tool; return this; } /** * The set of results contained in an SARIF log. The results array can be omitted when a run is solely exporting * rules metadata. It must be present (but may be empty) if a log file represents an actual scan. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Run setResults(final List<Result> results) { this.results = results; return this; } /** * The set of invocations providing information about the tool execution such as configuration errors or runtime * exceptions * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Run setInvocations(final List<Invocation> invocations) { this.invocations = invocations; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Run)) { return false; } final SarifLog.Run other = (SarifLog.Run) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$tool = this.getTool(); final java.lang.Object other$tool = other.getTool(); if (this$tool == null ? other$tool != null : !this$tool.equals(other$tool)) { return false; } final java.lang.Object this$results = this.getResults(); final java.lang.Object other$results = other.getResults(); if (this$results == null ? other$results != null : !this$results.equals(other$results)) { return false; } final java.lang.Object this$invocations = this.getInvocations(); final java.lang.Object other$invocations = other.getInvocations(); if (this$invocations == null ? other$invocations != null : !this$invocations.equals(other$invocations)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Run; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $tool = this.getTool(); result = result * PRIME + ($tool == null ? 43 : $tool.hashCode()); final java.lang.Object $results = this.getResults(); result = result * PRIME + ($results == null ? 43 : $results.hashCode()); final java.lang.Object $invocations = this.getInvocations(); result = result * PRIME + ($invocations == null ? 43 : $invocations.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Run(tool=" + this.getTool() + ", results=" + this.getResults() + ", invocations=" + this.getInvocations() + ")"; } } /** * The analysis tool that was run. */ public static class Tool { /** * The analysis tool that was run. */ private Component driver; @java.lang.SuppressWarnings("all") Tool(final Component driver) { this.driver = driver; } @java.lang.SuppressWarnings("all") public static class ToolBuilder { @java.lang.SuppressWarnings("all") private Component driver; @java.lang.SuppressWarnings("all") ToolBuilder() { } /** * The analysis tool that was run. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Tool.ToolBuilder driver(final Component driver) { this.driver = driver; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Tool build() { return new SarifLog.Tool(this.driver); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Tool.ToolBuilder(driver=" + this.driver + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Tool.ToolBuilder builder() { return new SarifLog.Tool.ToolBuilder(); } /** * The analysis tool that was run. */ @java.lang.SuppressWarnings("all") public Component getDriver() { return this.driver; } /** * The analysis tool that was run. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Tool setDriver(final Component driver) { this.driver = driver; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Tool)) { return false; } final SarifLog.Tool other = (SarifLog.Tool) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$driver = this.getDriver(); final java.lang.Object other$driver = other.getDriver(); if (this$driver == null ? other$driver != null : !this$driver.equals(other$driver)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Tool; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $driver = this.getDriver(); result = result * PRIME + ($driver == null ? 43 : $driver.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Tool(driver=" + this.getDriver() + ")"; } } /** * A component, such as a plug-in or the driver, of the analysis tool that was run. */ public static class Component { /** * The name of the tool component. */ private String name; /** * The tool component version, in whatever format the component natively provides. */ private String version; /** * The absolute URI at which information about this version of the tool component can be found. */ private String informationUri; /** * An array of reportingDescriptor objects relevant to the analysis performed by the tool component. */ private List<ReportingDescriptor> rules; @java.lang.SuppressWarnings("all") Component(final String name, final String version, final String informationUri, final List<ReportingDescriptor> rules) { this.name = name; this.version = version; this.informationUri = informationUri; this.rules = rules; } @java.lang.SuppressWarnings("all") public static class ComponentBuilder { @java.lang.SuppressWarnings("all") private String name; @java.lang.SuppressWarnings("all") private String version; @java.lang.SuppressWarnings("all") private String informationUri; @java.lang.SuppressWarnings("all") private List<ReportingDescriptor> rules; @java.lang.SuppressWarnings("all") ComponentBuilder() { } /** * The name of the tool component. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component.ComponentBuilder name(final String name) { this.name = name; return this; } /** * The tool component version, in whatever format the component natively provides. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component.ComponentBuilder version(final String version) { this.version = version; return this; } /** * The absolute URI at which information about this version of the tool component can be found. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component.ComponentBuilder informationUri(final String informationUri) { this.informationUri = informationUri; return this; } /** * An array of reportingDescriptor objects relevant to the analysis performed by the tool component. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component.ComponentBuilder rules(final List<ReportingDescriptor> rules) { this.rules = rules; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Component build() { return new SarifLog.Component(this.name, this.version, this.informationUri, this.rules); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Component.ComponentBuilder(name=" + this.name + ", version=" + this.version + ", informationUri=" + this.informationUri + ", rules=" + this.rules + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Component.ComponentBuilder builder() { return new SarifLog.Component.ComponentBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.Component.ComponentBuilder toBuilder() { return new SarifLog.Component.ComponentBuilder().name(this.name).version(this.version).informationUri(this.informationUri).rules(this.rules); } /** * The name of the tool component. */ @java.lang.SuppressWarnings("all") public String getName() { return this.name; } /** * The tool component version, in whatever format the component natively provides. */ @java.lang.SuppressWarnings("all") public String getVersion() { return this.version; } /** * The absolute URI at which information about this version of the tool component can be found. */ @java.lang.SuppressWarnings("all") public String getInformationUri() { return this.informationUri; } /** * An array of reportingDescriptor objects relevant to the analysis performed by the tool component. */ @java.lang.SuppressWarnings("all") public List<ReportingDescriptor> getRules() { return this.rules; } /** * The name of the tool component. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component setName(final String name) { this.name = name; return this; } /** * The tool component version, in whatever format the component natively provides. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component setVersion(final String version) { this.version = version; return this; } /** * The absolute URI at which information about this version of the tool component can be found. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component setInformationUri(final String informationUri) { this.informationUri = informationUri; return this; } /** * An array of reportingDescriptor objects relevant to the analysis performed by the tool component. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Component setRules(final List<ReportingDescriptor> rules) { this.rules = rules; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Component)) { return false; } final SarifLog.Component other = (SarifLog.Component) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) { return false; } final java.lang.Object this$version = this.getVersion(); final java.lang.Object other$version = other.getVersion(); if (this$version == null ? other$version != null : !this$version.equals(other$version)) { return false; } final java.lang.Object this$informationUri = this.getInformationUri(); final java.lang.Object other$informationUri = other.getInformationUri(); if (this$informationUri == null ? other$informationUri != null : !this$informationUri.equals(other$informationUri)) { return false; } final java.lang.Object this$rules = this.getRules(); final java.lang.Object other$rules = other.getRules(); if (this$rules == null ? other$rules != null : !this$rules.equals(other$rules)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Component; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final java.lang.Object $version = this.getVersion(); result = result * PRIME + ($version == null ? 43 : $version.hashCode()); final java.lang.Object $informationUri = this.getInformationUri(); result = result * PRIME + ($informationUri == null ? 43 : $informationUri.hashCode()); final java.lang.Object $rules = this.getRules(); result = result * PRIME + ($rules == null ? 43 : $rules.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Component(name=" + this.getName() + ", version=" + this.getVersion() + ", informationUri=" + this.getInformationUri() + ", rules=" + this.getRules() + ")"; } } /** * Metadata that describes a specific report produced by the tool, as part of the analysis it provides or its runtime * reporting. */ public static class ReportingDescriptor { /** * A stable, opaque identifier for the report. */ private String id; /** * A report identifier that is understandable to an end user. */ private String name; /** * A concise description of the report. Should be a single sentence that is understandable when visible space is * limited to a single line of text. */ private MultiformatMessage shortDescription; /** * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. */ private MultiformatMessage fullDescription; /** * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds * message strings in plain text and (optionally) Markdown format. The strings can include placeholders, which can * be used to construct a message in combination with an arbitrary number of additional string arguments. */ private MultiformatMessage messageStrings; /** * A URI where the primary documentation for the report can be found. */ private String helpUri; /** * Provides the primary documentation for the report, useful when there is no online documentation. */ private MultiformatMessage help; /** * Key/value pairs that provide additional information about the report. */ private PropertyBag properties; @java.lang.SuppressWarnings("all") ReportingDescriptor(final String id, final String name, final MultiformatMessage shortDescription, final MultiformatMessage fullDescription, final MultiformatMessage messageStrings, final String helpUri, final MultiformatMessage help, final PropertyBag properties) { this.id = id; this.name = name; this.shortDescription = shortDescription; this.fullDescription = fullDescription; this.messageStrings = messageStrings; this.helpUri = helpUri; this.help = help; this.properties = properties; } @java.lang.SuppressWarnings("all") public static class ReportingDescriptorBuilder { @java.lang.SuppressWarnings("all") private String id; @java.lang.SuppressWarnings("all") private String name; @java.lang.SuppressWarnings("all") private MultiformatMessage shortDescription; @java.lang.SuppressWarnings("all") private MultiformatMessage fullDescription; @java.lang.SuppressWarnings("all") private MultiformatMessage messageStrings; @java.lang.SuppressWarnings("all") private String helpUri; @java.lang.SuppressWarnings("all") private MultiformatMessage help; @java.lang.SuppressWarnings("all") private PropertyBag properties; @java.lang.SuppressWarnings("all") ReportingDescriptorBuilder() { } /** * A stable, opaque identifier for the report. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder id(final String id) { this.id = id; return this; } /** * A report identifier that is understandable to an end user. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder name(final String name) { this.name = name; return this; } /** * A concise description of the report. Should be a single sentence that is understandable when visible space is * limited to a single line of text. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder shortDescription(final MultiformatMessage shortDescription) { this.shortDescription = shortDescription; return this; } /** * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder fullDescription(final MultiformatMessage fullDescription) { this.fullDescription = fullDescription; return this; } /** * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds * message strings in plain text and (optionally) Markdown format. The strings can include placeholders, which can * be used to construct a message in combination with an arbitrary number of additional string arguments. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder messageStrings(final MultiformatMessage messageStrings) { this.messageStrings = messageStrings; return this; } /** * A URI where the primary documentation for the report can be found. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder helpUri(final String helpUri) { this.helpUri = helpUri; return this; } /** * Provides the primary documentation for the report, useful when there is no online documentation. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder help(final MultiformatMessage help) { this.help = help; return this; } /** * Key/value pairs that provide additional information about the report. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor.ReportingDescriptorBuilder properties(final PropertyBag properties) { this.properties = properties; return this; } @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor build() { return new SarifLog.ReportingDescriptor(this.id, this.name, this.shortDescription, this.fullDescription, this.messageStrings, this.helpUri, this.help, this.properties); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ReportingDescriptor.ReportingDescriptorBuilder(id=" + this.id + ", name=" + this.name + ", shortDescription=" + this.shortDescription + ", fullDescription=" + this.fullDescription + ", messageStrings=" + this.messageStrings + ", helpUri=" + this.helpUri + ", help=" + this.help + ", properties=" + this.properties + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.ReportingDescriptor.ReportingDescriptorBuilder builder() { return new SarifLog.ReportingDescriptor.ReportingDescriptorBuilder(); } /** * A stable, opaque identifier for the report. */ @java.lang.SuppressWarnings("all") public String getId() { return this.id; } /** * A report identifier that is understandable to an end user. */ @java.lang.SuppressWarnings("all") public String getName() { return this.name; } /** * A concise description of the report. Should be a single sentence that is understandable when visible space is * limited to a single line of text. */ @java.lang.SuppressWarnings("all") public MultiformatMessage getShortDescription() { return this.shortDescription; } /** * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. */ @java.lang.SuppressWarnings("all") public MultiformatMessage getFullDescription() { return this.fullDescription; } /** * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds * message strings in plain text and (optionally) Markdown format. The strings can include placeholders, which can * be used to construct a message in combination with an arbitrary number of additional string arguments. */ @java.lang.SuppressWarnings("all") public MultiformatMessage getMessageStrings() { return this.messageStrings; } /** * A URI where the primary documentation for the report can be found. */ @java.lang.SuppressWarnings("all") public String getHelpUri() { return this.helpUri; } /** * Provides the primary documentation for the report, useful when there is no online documentation. */ @java.lang.SuppressWarnings("all") public MultiformatMessage getHelp() { return this.help; } /** * Key/value pairs that provide additional information about the report. */ @java.lang.SuppressWarnings("all") public PropertyBag getProperties() { return this.properties; } /** * A stable, opaque identifier for the report. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setId(final String id) { this.id = id; return this; } /** * A report identifier that is understandable to an end user. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setName(final String name) { this.name = name; return this; } /** * A concise description of the report. Should be a single sentence that is understandable when visible space is * limited to a single line of text. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setShortDescription(final MultiformatMessage shortDescription) { this.shortDescription = shortDescription; return this; } /** * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setFullDescription(final MultiformatMessage fullDescription) { this.fullDescription = fullDescription; return this; } /** * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds * message strings in plain text and (optionally) Markdown format. The strings can include placeholders, which can * be used to construct a message in combination with an arbitrary number of additional string arguments. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setMessageStrings(final MultiformatMessage messageStrings) { this.messageStrings = messageStrings; return this; } /** * A URI where the primary documentation for the report can be found. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setHelpUri(final String helpUri) { this.helpUri = helpUri; return this; } /** * Provides the primary documentation for the report, useful when there is no online documentation. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setHelp(final MultiformatMessage help) { this.help = help; return this; } /** * Key/value pairs that provide additional information about the report. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ReportingDescriptor setProperties(final PropertyBag properties) { this.properties = properties; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.ReportingDescriptor)) { return false; } final SarifLog.ReportingDescriptor other = (SarifLog.ReportingDescriptor) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$id = this.getId(); final java.lang.Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) { return false; } final java.lang.Object this$name = this.getName(); final java.lang.Object other$name = other.getName(); if (this$name == null ? other$name != null : !this$name.equals(other$name)) { return false; } final java.lang.Object this$shortDescription = this.getShortDescription(); final java.lang.Object other$shortDescription = other.getShortDescription(); if (this$shortDescription == null ? other$shortDescription != null : !this$shortDescription.equals(other$shortDescription)) { return false; } final java.lang.Object this$fullDescription = this.getFullDescription(); final java.lang.Object other$fullDescription = other.getFullDescription(); if (this$fullDescription == null ? other$fullDescription != null : !this$fullDescription.equals(other$fullDescription)) { return false; } final java.lang.Object this$messageStrings = this.getMessageStrings(); final java.lang.Object other$messageStrings = other.getMessageStrings(); if (this$messageStrings == null ? other$messageStrings != null : !this$messageStrings.equals(other$messageStrings)) { return false; } final java.lang.Object this$helpUri = this.getHelpUri(); final java.lang.Object other$helpUri = other.getHelpUri(); if (this$helpUri == null ? other$helpUri != null : !this$helpUri.equals(other$helpUri)) { return false; } final java.lang.Object this$help = this.getHelp(); final java.lang.Object other$help = other.getHelp(); if (this$help == null ? other$help != null : !this$help.equals(other$help)) { return false; } final java.lang.Object this$properties = this.getProperties(); final java.lang.Object other$properties = other.getProperties(); if (this$properties == null ? other$properties != null : !this$properties.equals(other$properties)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.ReportingDescriptor; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $id = this.getId(); result = result * PRIME + ($id == null ? 43 : $id.hashCode()); final java.lang.Object $name = this.getName(); result = result * PRIME + ($name == null ? 43 : $name.hashCode()); final java.lang.Object $shortDescription = this.getShortDescription(); result = result * PRIME + ($shortDescription == null ? 43 : $shortDescription.hashCode()); final java.lang.Object $fullDescription = this.getFullDescription(); result = result * PRIME + ($fullDescription == null ? 43 : $fullDescription.hashCode()); final java.lang.Object $messageStrings = this.getMessageStrings(); result = result * PRIME + ($messageStrings == null ? 43 : $messageStrings.hashCode()); final java.lang.Object $helpUri = this.getHelpUri(); result = result * PRIME + ($helpUri == null ? 43 : $helpUri.hashCode()); final java.lang.Object $help = this.getHelp(); result = result * PRIME + ($help == null ? 43 : $help.hashCode()); final java.lang.Object $properties = this.getProperties(); result = result * PRIME + ($properties == null ? 43 : $properties.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ReportingDescriptor(id=" + this.getId() + ", name=" + this.getName() + ", shortDescription=" + this.getShortDescription() + ", fullDescription=" + this.getFullDescription() + ", messageStrings=" + this.getMessageStrings() + ", helpUri=" + this.getHelpUri() + ", help=" + this.getHelp() + ", properties=" + this.getProperties() + ")"; } } /** * A message string or message format string rendered in multiple formats. */ public static class MultiformatMessage { /** * A plain text message string or format string. */ private String text; /** * A Markdown message string or format string. */ private String markdown; public MultiformatMessage(String text) { this.text = text; } @java.lang.SuppressWarnings("all") public static class MultiformatMessageBuilder { @java.lang.SuppressWarnings("all") private String text; @java.lang.SuppressWarnings("all") private String markdown; @java.lang.SuppressWarnings("all") MultiformatMessageBuilder() { } /** * A plain text message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.MultiformatMessage.MultiformatMessageBuilder text(final String text) { this.text = text; return this; } /** * A Markdown message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.MultiformatMessage.MultiformatMessageBuilder markdown(final String markdown) { this.markdown = markdown; return this; } @java.lang.SuppressWarnings("all") public SarifLog.MultiformatMessage build() { return new SarifLog.MultiformatMessage(this.text, this.markdown); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.MultiformatMessage.MultiformatMessageBuilder(text=" + this.text + ", markdown=" + this.markdown + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.MultiformatMessage.MultiformatMessageBuilder builder() { return new SarifLog.MultiformatMessage.MultiformatMessageBuilder(); } /** * A plain text message string or format string. */ @java.lang.SuppressWarnings("all") public String getText() { return this.text; } /** * A Markdown message string or format string. */ @java.lang.SuppressWarnings("all") public String getMarkdown() { return this.markdown; } /** * A plain text message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.MultiformatMessage setText(final String text) { this.text = text; return this; } /** * A Markdown message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.MultiformatMessage setMarkdown(final String markdown) { this.markdown = markdown; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.MultiformatMessage)) { return false; } final SarifLog.MultiformatMessage other = (SarifLog.MultiformatMessage) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$text = this.getText(); final java.lang.Object other$text = other.getText(); if (this$text == null ? other$text != null : !this$text.equals(other$text)) { return false; } final java.lang.Object this$markdown = this.getMarkdown(); final java.lang.Object other$markdown = other.getMarkdown(); if (this$markdown == null ? other$markdown != null : !this$markdown.equals(other$markdown)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.MultiformatMessage; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $text = this.getText(); result = result * PRIME + ($text == null ? 43 : $text.hashCode()); final java.lang.Object $markdown = this.getMarkdown(); result = result * PRIME + ($markdown == null ? 43 : $markdown.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.MultiformatMessage(text=" + this.getText() + ", markdown=" + this.getMarkdown() + ")"; } @java.lang.SuppressWarnings("all") public MultiformatMessage() { } @java.lang.SuppressWarnings("all") public MultiformatMessage(final String text, final String markdown) { this.text = text; this.markdown = markdown; } } /** * A exception information object, for the tool runtime errors. */ public static class Exception { /** * A plain text message string or format string. */ private String message; @java.lang.SuppressWarnings("all") Exception(final String message) { this.message = message; } @java.lang.SuppressWarnings("all") public static class ExceptionBuilder { @java.lang.SuppressWarnings("all") private String message; @java.lang.SuppressWarnings("all") ExceptionBuilder() { } /** * A plain text message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Exception.ExceptionBuilder message(final String message) { this.message = message; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Exception build() { return new SarifLog.Exception(this.message); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Exception.ExceptionBuilder(message=" + this.message + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Exception.ExceptionBuilder builder() { return new SarifLog.Exception.ExceptionBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.Exception.ExceptionBuilder toBuilder() { return new SarifLog.Exception.ExceptionBuilder().message(this.message); } /** * A plain text message string or format string. */ @java.lang.SuppressWarnings("all") public String getMessage() { return this.message; } /** * A plain text message string or format string. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.Exception setMessage(final String message) { this.message = message; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Exception)) { return false; } final SarifLog.Exception other = (SarifLog.Exception) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$message = this.getMessage(); final java.lang.Object other$message = other.getMessage(); if (this$message == null ? other$message != null : !this$message.equals(other$message)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Exception; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $message = this.getMessage(); result = result * PRIME + ($message == null ? 43 : $message.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Exception(message=" + this.getMessage() + ")"; } } /** * A associated rule to the toolConfigurationNotification. */ public static class AssociatedRule { /** * The stable, unique identifier of the rule, if any, to which this result is relevant. */ private String id; @java.lang.SuppressWarnings("all") AssociatedRule(final String id) { this.id = id; } @java.lang.SuppressWarnings("all") public static class AssociatedRuleBuilder { @java.lang.SuppressWarnings("all") private String id; @java.lang.SuppressWarnings("all") AssociatedRuleBuilder() { } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.AssociatedRule.AssociatedRuleBuilder id(final String id) { this.id = id; return this; } @java.lang.SuppressWarnings("all") public SarifLog.AssociatedRule build() { return new SarifLog.AssociatedRule(this.id); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.AssociatedRule.AssociatedRuleBuilder(id=" + this.id + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.AssociatedRule.AssociatedRuleBuilder builder() { return new SarifLog.AssociatedRule.AssociatedRuleBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.AssociatedRule.AssociatedRuleBuilder toBuilder() { return new SarifLog.AssociatedRule.AssociatedRuleBuilder().id(this.id); } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. */ @java.lang.SuppressWarnings("all") public String getId() { return this.id; } /** * The stable, unique identifier of the rule, if any, to which this result is relevant. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.AssociatedRule setId(final String id) { this.id = id; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.AssociatedRule)) { return false; } final SarifLog.AssociatedRule other = (SarifLog.AssociatedRule) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$id = this.getId(); final java.lang.Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.AssociatedRule; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $id = this.getId(); result = result * PRIME + ($id == null ? 43 : $id.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.AssociatedRule(id=" + this.getId() + ")"; } } /** * An invocation property to specify tool configuration errors. */ public static class ToolConfigurationNotification { /** * An associated rule */ private AssociatedRule associatedRule; /** * A message component to detail the configuration error */ private Message message; @java.lang.SuppressWarnings("all") ToolConfigurationNotification(final AssociatedRule associatedRule, final Message message) { this.associatedRule = associatedRule; this.message = message; } @java.lang.SuppressWarnings("all") public static class ToolConfigurationNotificationBuilder { @java.lang.SuppressWarnings("all") private AssociatedRule associatedRule; @java.lang.SuppressWarnings("all") private Message message; @java.lang.SuppressWarnings("all") ToolConfigurationNotificationBuilder() { } /** * An associated rule * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder associatedRule(final AssociatedRule associatedRule) { this.associatedRule = associatedRule; return this; } /** * A message component to detail the configuration error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder message(final Message message) { this.message = message; return this; } @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification build() { return new SarifLog.ToolConfigurationNotification(this.associatedRule, this.message); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder(associatedRule=" + this.associatedRule + ", message=" + this.message + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder builder() { return new SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder toBuilder() { return new SarifLog.ToolConfigurationNotification.ToolConfigurationNotificationBuilder().associatedRule(this.associatedRule).message(this.message); } /** * An associated rule */ @java.lang.SuppressWarnings("all") public AssociatedRule getAssociatedRule() { return this.associatedRule; } /** * A message component to detail the configuration error */ @java.lang.SuppressWarnings("all") public Message getMessage() { return this.message; } /** * An associated rule * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification setAssociatedRule(final AssociatedRule associatedRule) { this.associatedRule = associatedRule; return this; } /** * A message component to detail the configuration error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolConfigurationNotification setMessage(final Message message) { this.message = message; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.ToolConfigurationNotification)) { return false; } final SarifLog.ToolConfigurationNotification other = (SarifLog.ToolConfigurationNotification) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$associatedRule = this.getAssociatedRule(); final java.lang.Object other$associatedRule = other.getAssociatedRule(); if (this$associatedRule == null ? other$associatedRule != null : !this$associatedRule.equals(other$associatedRule)) { return false; } final java.lang.Object this$message = this.getMessage(); final java.lang.Object other$message = other.getMessage(); if (this$message == null ? other$message != null : !this$message.equals(other$message)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.ToolConfigurationNotification; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $associatedRule = this.getAssociatedRule(); result = result * PRIME + ($associatedRule == null ? 43 : $associatedRule.hashCode()); final java.lang.Object $message = this.getMessage(); result = result * PRIME + ($message == null ? 43 : $message.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ToolConfigurationNotification(associatedRule=" + this.getAssociatedRule() + ", message=" + this.getMessage() + ")"; } } /** * An invocation property to specify tool runtime errors. */ public static class ToolExecutionNotification { /** * A list of related locations to the error */ private List<Location> locations; /** * A message component to detail the runtime error */ private Message message; /** * A exception component to detail the tool exception */ private Exception exception; @java.lang.SuppressWarnings("all") ToolExecutionNotification(final List<Location> locations, final Message message, final Exception exception) { this.locations = locations; this.message = message; this.exception = exception; } @java.lang.SuppressWarnings("all") public static class ToolExecutionNotificationBuilder { @java.lang.SuppressWarnings("all") private List<Location> locations; @java.lang.SuppressWarnings("all") private Message message; @java.lang.SuppressWarnings("all") private Exception exception; @java.lang.SuppressWarnings("all") ToolExecutionNotificationBuilder() { } /** * A list of related locations to the error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder locations(final List<Location> locations) { this.locations = locations; return this; } /** * A message component to detail the runtime error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder message(final Message message) { this.message = message; return this; } /** * A exception component to detail the tool exception * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder exception(final Exception exception) { this.exception = exception; return this; } @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification build() { return new SarifLog.ToolExecutionNotification(this.locations, this.message, this.exception); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder(locations=" + this.locations + ", message=" + this.message + ", exception=" + this.exception + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder builder() { return new SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder toBuilder() { return new SarifLog.ToolExecutionNotification.ToolExecutionNotificationBuilder().locations(this.locations).message(this.message).exception(this.exception); } /** * A list of related locations to the error */ @java.lang.SuppressWarnings("all") public List<Location> getLocations() { return this.locations; } /** * A message component to detail the runtime error */ @java.lang.SuppressWarnings("all") public Message getMessage() { return this.message; } /** * A exception component to detail the tool exception */ @java.lang.SuppressWarnings("all") public Exception getException() { return this.exception; } /** * A list of related locations to the error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification setLocations(final List<Location> locations) { this.locations = locations; return this; } /** * A message component to detail the runtime error * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification setMessage(final Message message) { this.message = message; return this; } /** * A exception component to detail the tool exception * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.ToolExecutionNotification setException(final Exception exception) { this.exception = exception; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.ToolExecutionNotification)) { return false; } final SarifLog.ToolExecutionNotification other = (SarifLog.ToolExecutionNotification) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$locations = this.getLocations(); final java.lang.Object other$locations = other.getLocations(); if (this$locations == null ? other$locations != null : !this$locations.equals(other$locations)) { return false; } final java.lang.Object this$message = this.getMessage(); final java.lang.Object other$message = other.getMessage(); if (this$message == null ? other$message != null : !this$message.equals(other$message)) { return false; } final java.lang.Object this$exception = this.getException(); final java.lang.Object other$exception = other.getException(); if (this$exception == null ? other$exception != null : !this$exception.equals(other$exception)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.ToolExecutionNotification; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $locations = this.getLocations(); result = result * PRIME + ($locations == null ? 43 : $locations.hashCode()); final java.lang.Object $message = this.getMessage(); result = result * PRIME + ($message == null ? 43 : $message.hashCode()); final java.lang.Object $exception = this.getException(); result = result * PRIME + ($exception == null ? 43 : $exception.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.ToolExecutionNotification(locations=" + this.getLocations() + ", message=" + this.getMessage() + ", exception=" + this.getException() + ")"; } } /** * An invocation component to specify tool invocation details/errors. */ public static class Invocation { /** * An indicator of execution status */ private Boolean executionSuccessful; /** * A list of associated tool configuration errors */ private List<ToolConfigurationNotification> toolConfigurationNotifications; /** * A list of associated tool runtime errors */ private List<ToolExecutionNotification> toolExecutionNotifications; @java.lang.SuppressWarnings("all") Invocation(final Boolean executionSuccessful, final List<ToolConfigurationNotification> toolConfigurationNotifications, final List<ToolExecutionNotification> toolExecutionNotifications) { this.executionSuccessful = executionSuccessful; this.toolConfigurationNotifications = toolConfigurationNotifications; this.toolExecutionNotifications = toolExecutionNotifications; } @java.lang.SuppressWarnings("all") public static class InvocationBuilder { @java.lang.SuppressWarnings("all") private Boolean executionSuccessful; @java.lang.SuppressWarnings("all") private List<ToolConfigurationNotification> toolConfigurationNotifications; @java.lang.SuppressWarnings("all") private List<ToolExecutionNotification> toolExecutionNotifications; @java.lang.SuppressWarnings("all") InvocationBuilder() { } @java.lang.SuppressWarnings("all") public SarifLog.Invocation.InvocationBuilder executionSuccessful(final Boolean executionSuccessful) { this.executionSuccessful = executionSuccessful; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation.InvocationBuilder toolConfigurationNotifications(final List<ToolConfigurationNotification> toolConfigurationNotifications) { this.toolConfigurationNotifications = toolConfigurationNotifications; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation.InvocationBuilder toolExecutionNotifications(final List<ToolExecutionNotification> toolExecutionNotifications) { this.toolExecutionNotifications = toolExecutionNotifications; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation build() { return new SarifLog.Invocation(this.executionSuccessful, this.toolConfigurationNotifications, this.toolExecutionNotifications); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Invocation.InvocationBuilder(executionSuccessful=" + this.executionSuccessful + ", toolConfigurationNotifications=" + this.toolConfigurationNotifications + ", toolExecutionNotifications=" + this.toolExecutionNotifications + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.Invocation.InvocationBuilder builder() { return new SarifLog.Invocation.InvocationBuilder(); } @java.lang.SuppressWarnings("all") public SarifLog.Invocation.InvocationBuilder toBuilder() { return new SarifLog.Invocation.InvocationBuilder().executionSuccessful(this.executionSuccessful).toolConfigurationNotifications(this.toolConfigurationNotifications).toolExecutionNotifications(this.toolExecutionNotifications); } @java.lang.SuppressWarnings("all") public Boolean getExecutionSuccessful() { return this.executionSuccessful; } @java.lang.SuppressWarnings("all") public List<ToolConfigurationNotification> getToolConfigurationNotifications() { return this.toolConfigurationNotifications; } @java.lang.SuppressWarnings("all") public List<ToolExecutionNotification> getToolExecutionNotifications() { return this.toolExecutionNotifications; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation setExecutionSuccessful(final Boolean executionSuccessful) { this.executionSuccessful = executionSuccessful; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation setToolConfigurationNotifications(final List<ToolConfigurationNotification> toolConfigurationNotifications) { this.toolConfigurationNotifications = toolConfigurationNotifications; return this; } @java.lang.SuppressWarnings("all") public SarifLog.Invocation setToolExecutionNotifications(final List<ToolExecutionNotification> toolExecutionNotifications) { this.toolExecutionNotifications = toolExecutionNotifications; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog.Invocation)) { return false; } final SarifLog.Invocation other = (SarifLog.Invocation) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$executionSuccessful = this.getExecutionSuccessful(); final java.lang.Object other$executionSuccessful = other.getExecutionSuccessful(); if (this$executionSuccessful == null ? other$executionSuccessful != null : !this$executionSuccessful.equals(other$executionSuccessful)) { return false; } final java.lang.Object this$toolConfigurationNotifications = this.getToolConfigurationNotifications(); final java.lang.Object other$toolConfigurationNotifications = other.getToolConfigurationNotifications(); if (this$toolConfigurationNotifications == null ? other$toolConfigurationNotifications != null : !this$toolConfigurationNotifications.equals(other$toolConfigurationNotifications)) { return false; } final java.lang.Object this$toolExecutionNotifications = this.getToolExecutionNotifications(); final java.lang.Object other$toolExecutionNotifications = other.getToolExecutionNotifications(); if (this$toolExecutionNotifications == null ? other$toolExecutionNotifications != null : !this$toolExecutionNotifications.equals(other$toolExecutionNotifications)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog.Invocation; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $executionSuccessful = this.getExecutionSuccessful(); result = result * PRIME + ($executionSuccessful == null ? 43 : $executionSuccessful.hashCode()); final java.lang.Object $toolConfigurationNotifications = this.getToolConfigurationNotifications(); result = result * PRIME + ($toolConfigurationNotifications == null ? 43 : $toolConfigurationNotifications.hashCode()); final java.lang.Object $toolExecutionNotifications = this.getToolExecutionNotifications(); result = result * PRIME + ($toolExecutionNotifications == null ? 43 : $toolExecutionNotifications.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.Invocation(executionSuccessful=" + this.getExecutionSuccessful() + ", toolConfigurationNotifications=" + this.getToolConfigurationNotifications() + ", toolExecutionNotifications=" + this.getToolExecutionNotifications() + ")"; } } @java.lang.SuppressWarnings("all") private static String defaultSchema() { return "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json"; } @java.lang.SuppressWarnings("all") private static String defaultVersion() { return "2.1.0"; } @java.lang.SuppressWarnings("all") SarifLog(final String schema, final String version, final List<Run> runs) { this.schema = schema; this.version = version; this.runs = runs; } @java.lang.SuppressWarnings("all") public static class SarifLogBuilder { @java.lang.SuppressWarnings("all") private boolean schemaSet; @java.lang.SuppressWarnings("all") private String schemaValue; @java.lang.SuppressWarnings("all") private boolean versionSet; @java.lang.SuppressWarnings("all") private String versionValue; @java.lang.SuppressWarnings("all") private List<Run> runs; @java.lang.SuppressWarnings("all") SarifLogBuilder() { } /** * The URI of the JSON schema corresponding to the version. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.SarifLogBuilder schema(final String schema) { this.schemaValue = schema; schemaSet = true; return this; } /** * The SARIF format version of this log file. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.SarifLogBuilder version(final String version) { this.versionValue = version; versionSet = true; return this; } /** * The set of runs contained in this log file. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog.SarifLogBuilder runs(final List<Run> runs) { this.runs = runs; return this; } @java.lang.SuppressWarnings("all") public SarifLog build() { String schemaValue = this.schemaValue; if (!this.schemaSet) { schemaValue = SarifLog.defaultSchema(); } String versionValue = this.versionValue; if (!this.versionSet) { versionValue = SarifLog.defaultVersion(); } return new SarifLog(schemaValue, versionValue, this.runs); } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog.SarifLogBuilder(schema$value=" + this.schemaValue + ", version$value=" + this.versionValue + ", runs=" + this.runs + ")"; } } @java.lang.SuppressWarnings("all") public static SarifLog.SarifLogBuilder builder() { return new SarifLog.SarifLogBuilder(); } /** * The URI of the JSON schema corresponding to the version. */ @java.lang.SuppressWarnings("all") public String getSchema() { return this.schema; } /** * The SARIF format version of this log file. */ @java.lang.SuppressWarnings("all") public String getVersion() { return this.version; } /** * The set of runs contained in this log file. */ @java.lang.SuppressWarnings("all") public List<Run> getRuns() { return this.runs; } /** * The URI of the JSON schema corresponding to the version. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog setSchema(final String schema) { this.schema = schema; return this; } /** * The SARIF format version of this log file. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog setVersion(final String version) { this.version = version; return this; } /** * The set of runs contained in this log file. * @return {@code this}. */ @java.lang.SuppressWarnings("all") public SarifLog setRuns(final List<Run> runs) { this.runs = runs; return this; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) { return true; } if (!(o instanceof SarifLog)) { return false; } final SarifLog other = (SarifLog) o; if (!other.canEqual((java.lang.Object) this)) { return false; } final java.lang.Object this$schema = this.getSchema(); final java.lang.Object other$schema = other.getSchema(); if (this$schema == null ? other$schema != null : !this$schema.equals(other$schema)) { return false; } final java.lang.Object this$version = this.getVersion(); final java.lang.Object other$version = other.getVersion(); if (this$version == null ? other$version != null : !this$version.equals(other$version)) { return false; } final java.lang.Object this$runs = this.getRuns(); final java.lang.Object other$runs = other.getRuns(); if (this$runs == null ? other$runs != null : !this$runs.equals(other$runs)) { return false; } return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SarifLog; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; final java.lang.Object $schema = this.getSchema(); result = result * PRIME + ($schema == null ? 43 : $schema.hashCode()); final java.lang.Object $version = this.getVersion(); result = result * PRIME + ($version == null ? 43 : $version.hashCode()); final java.lang.Object $runs = this.getRuns(); result = result * PRIME + ($runs == null ? 43 : $runs.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SarifLog(schema=" + this.getSchema() + ", version=" + this.getVersion() + ", runs=" + this.getRuns() + ")"; } } // CPD-ON
137,262
36.928433
362
java
pmd
pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLogBuilder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers.internal.sarif; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.ArtifactLocation; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.AssociatedRule; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Component; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Exception; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Invocation; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Location; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Message; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.MultiformatMessage; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.PhysicalLocation; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.PropertyBag; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Region; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.ReportingDescriptor; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Result; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Run; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.Tool; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.ToolConfigurationNotification; import net.sourceforge.pmd.renderers.internal.sarif.SarifLog.ToolExecutionNotification; public class SarifLogBuilder { private final List<ReportingDescriptor> rules = new ArrayList<>(); private final List<Result> results = new ArrayList<>(); private final List<ToolConfigurationNotification> toolConfigurationNotifications = new ArrayList<>(); private final List<ToolExecutionNotification> toolExecutionNotifications = new ArrayList<>(); public static SarifLogBuilder sarifLogBuilder() { return new SarifLogBuilder(); } public SarifLogBuilder add(RuleViolation violation) { final ReportingDescriptor ruleDescriptor = getReportingDescriptor(violation); int ruleIndex = rules.indexOf(ruleDescriptor); if (ruleIndex == -1) { rules.add(ruleDescriptor); ruleIndex = rules.size() - 1; } final Location location = getRuleViolationLocation(violation); final Result result = resultFrom(ruleDescriptor, ruleIndex, location); results.add(result); return this; } public SarifLogBuilder addRunTimeError(Report.ProcessingError error) { ArtifactLocation artifactLocation = ArtifactLocation.builder() .uri(error.getFileId().getUriString()) .build(); PhysicalLocation physicalLocation = PhysicalLocation.builder() .artifactLocation(artifactLocation) .build(); Location location = Location .builder() .physicalLocation(physicalLocation) .build(); Message message = Message.builder() .text(error.getMsg()) .build(); Exception exception = Exception.builder() .message(error.getDetail()) .build(); ToolExecutionNotification toolExecutionNotification = ToolExecutionNotification.builder() .locations(Collections.singletonList(location)) .message(message) .exception(exception) .build(); toolExecutionNotifications.add(toolExecutionNotification); return this; } public SarifLogBuilder addConfigurationError(Report.ConfigurationError error) { AssociatedRule associatedRule = AssociatedRule.builder() .id(error.rule().getName()) .build(); Message message = Message.builder().text(error.issue()).build(); ToolConfigurationNotification toolConfigurationNotification = ToolConfigurationNotification.builder() .associatedRule(associatedRule) .message(message) .build(); toolConfigurationNotifications.add(toolConfigurationNotification); return this; } public SarifLog build() { final Component driver = getDriverComponent().toBuilder().rules(rules).build(); final Tool tool = Tool.builder().driver(driver).build(); final Invocation invocation = Invocation.builder() .toolExecutionNotifications(toolExecutionNotifications) .toolConfigurationNotifications(toolConfigurationNotifications) .executionSuccessful(isExecutionSuccessful()) .build(); final Run run = Run.builder() .tool(tool) .results(results) .invocations(Collections.singletonList(invocation)) .build(); List<Run> runs = Collections.singletonList(run); return SarifLog.builder().runs(runs).build(); } private boolean isExecutionSuccessful() { return toolExecutionNotifications.isEmpty() && toolConfigurationNotifications.isEmpty(); } private Result resultFrom(ReportingDescriptor rule, Integer ruleIndex, Location location) { final Result result = Result.builder() .ruleId(rule.getId()) .ruleIndex(ruleIndex) .build(); final Message message = Message.builder() .text(rule.getShortDescription().getText()) .build(); result.setMessage(message); result.setLocations(Collections.singletonList(location)); return result; } private Location getRuleViolationLocation(RuleViolation rv) { ArtifactLocation artifactLocation = ArtifactLocation.builder() .uri(rv.getFileId().getUriString()) .build(); Region region = Region.builder() .startLine(rv.getBeginLine()) .endLine(rv.getEndLine()) .startColumn(rv.getBeginColumn()) .endColumn(rv.getEndColumn()) .build(); PhysicalLocation physicalLocation = PhysicalLocation.builder() .artifactLocation(artifactLocation) .region(region) .build(); return Location.builder() .physicalLocation(physicalLocation) .build(); } private ReportingDescriptor getReportingDescriptor(RuleViolation rv) { return ReportingDescriptor.builder() .id(rv.getRule().getName()) .shortDescription(new MultiformatMessage(rv.getDescription())) .fullDescription(new MultiformatMessage(rv.getRule().getDescription())) .helpUri(rv.getRule().getExternalInfoUrl()) .help(new MultiformatMessage(rv.getRule().getDescription())) .properties(getRuleProperties(rv)) .build(); } private PropertyBag getRuleProperties(RuleViolation rv) { return PropertyBag.builder() .ruleset(rv.getRule().getRuleSetName()) .priority(rv.getRule().getPriority().getPriority()) .tags(new HashSet<>(Arrays.asList(rv.getRule().getRuleSetName()))) .build(); } private Component getDriverComponent() { return Component.builder() .name("PMD") .version(PMDVersion.VERSION) .informationUri("https://docs.pmd-code.org/latest/") .build(); } }
7,718
38.182741
109
java
pmd
pmd-master/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.testframework; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.test.schema.RuleTestDescriptor; class RuleTstTest { private final LanguageVersion dummyLanguage = DummyLanguageModule.getInstance().getDefaultVersion(); private final Rule rule = mock(Rule.class); private final RuleTst ruleTester = spy(RuleTst.class); @Test void shouldCallStartAndEnd() { when(rule.getLanguage()).thenReturn(dummyLanguage.getLanguage()); when(rule.getName()).thenReturn("test rule"); when(rule.getTargetSelector()).thenReturn(RuleTargetSelector.forRootOnly()); when(rule.deepCopy()).thenReturn(rule); ruleTester.runTestFromString("the code", rule, dummyLanguage); verify(rule).initialize(any(LanguageProcessor.class)); verify(rule).start(any(RuleContext.class)); verify(rule).end(any(RuleContext.class)); verify(rule, atLeastOnce()).getLanguage(); verify(rule, atLeastOnce()).getTargetSelector(); verify(rule, atLeastOnce()).getMinimumLanguageVersion(); verify(rule, atLeastOnce()).getMaximumLanguageVersion(); verify(rule).apply(any(Node.class), any(RuleContext.class)); verify(rule, atLeastOnce()).getName(); verify(rule).getPropertiesByPropertyDescriptor(); } @Test void shouldAssertLinenumbersSorted() { when(rule.getLanguage()).thenReturn(dummyLanguage.getLanguage()); when(rule.getName()).thenReturn("test rule"); when(rule.getMessage()).thenReturn("test rule"); when(rule.getTargetSelector()).thenReturn(RuleTargetSelector.forRootOnly()); when(rule.deepCopy()).thenReturn(rule); final String code = "(a)(b)\n(c)"; Mockito.doAnswer(invocation -> { RuleContext context = invocation.getArgument(1, RuleContext.class); DummyRootNode node = invocation.getArgument(0, DummyRootNode.class); assertEquals(3, node.getNumChildren()); // the violations are reported out of order // line 2 context.addViolation(node.getChild(2)); // line 1 context.addViolation(node.getChild(1)); return null; }).when(rule).apply(any(Node.class), Mockito.any(RuleContext.class)); RuleTestDescriptor testDescriptor = new RuleTestDescriptor(0, rule); testDescriptor.setLanguageVersion(dummyLanguage); testDescriptor.setCode(code); testDescriptor.setDescription("sample test"); testDescriptor.recordExpectedViolations(2, Arrays.asList(1, 2), Collections.emptyList()); ruleTester.runTest(testDescriptor); } }
3,571
38.688889
104
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd; 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 static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Pattern; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Base test class to verify the language's rulesets. This class should be * subclassed for each language. */ public abstract class AbstractRuleSetFactoryTest { private static ValidateDefaultHandler validateDefaultHandler; private static SAXParser saxParser; protected Set<String> validXPathClassNames = new HashSet<>(); private final Set<String> languagesToSkip = new HashSet<>(); public AbstractRuleSetFactoryTest() { this(new String[0]); } /** * Constructor used when a module that depends on another module wants to filter out the dependee's rulesets. * * @param languagesToSkip {@link Language}s terse names that appear in the classpath via a dependency, but should be * skipped because they aren't the primary language which the concrete instance of this class is testing. */ public AbstractRuleSetFactoryTest(String... languagesToSkip) { this.languagesToSkip.add("dummy"); this.languagesToSkip.addAll(Arrays.asList(languagesToSkip)); validXPathClassNames.add(XPathRule.class.getName()); } /** * Setups the XML parser with validation. * * @throws Exception * any error */ @BeforeAll static void init() throws Exception { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); saxParserFactory.setNamespaceAware(true); // Hope we're using Xerces, or this may not work! // Note: Features are listed here // http://xerces.apache.org/xerces2-j/features.html saxParserFactory.setFeature("http://xml.org/sax/features/validation", true); saxParserFactory.setFeature("http://apache.org/xml/features/validation/schema", true); saxParserFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); validateDefaultHandler = new ValidateDefaultHandler(); saxParser = saxParserFactory.newSAXParser(); } /** * Checks all rulesets of all languages on the classpath and verifies that * all required attributes for all rules are specified. * * @throws Exception * any error */ @Test void testAllPMDBuiltInRulesMeetConventions() throws Exception { int invalidSinceAttributes = 0; int invalidExternalInfoURL = 0; int invalidClassName = 0; int invalidRegexSuppress = 0; int invalidXPathSuppress = 0; StringBuilder messages = new StringBuilder(); List<String> ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { RuleSet ruleSet = loadRuleSetByFileName(fileName); for (Rule rule : ruleSet.getRules()) { // Skip references if (rule instanceof RuleReference) { continue; } Language language = rule.getLanguage(); String group = fileName.substring(fileName.lastIndexOf('/') + 1); group = group.substring(0, group.indexOf(".xml")); if (group.indexOf('-') >= 0) { group = group.substring(0, group.indexOf('-')); } // Is since missing ? if (rule.getSince() == null) { invalidSinceAttributes++; messages.append("Rule ") .append(fileName) .append("/") .append(rule.getName()) .append(" is missing 'since' attribute\n"); } // Is URL valid ? if (rule.getExternalInfoUrl() == null || "".equalsIgnoreCase(rule.getExternalInfoUrl())) { invalidExternalInfoURL++; messages.append("Rule ") .append(fileName) .append("/") .append(rule.getName()) .append(" is missing 'externalInfoURL' attribute\n"); } else { String expectedExternalInfoURL = "https://docs.pmd-code.org/.+/pmd_rules_" + language.getTerseName() + "_" + IOUtil.getFilenameBase(fileName) + ".html#" + rule.getName().toLowerCase(Locale.ROOT); if (rule.getExternalInfoUrl() == null || !rule.getExternalInfoUrl().matches(expectedExternalInfoURL)) { invalidExternalInfoURL++; messages.append("Rule ") .append(fileName) .append("/") .append(rule.getName()) .append(" seems to have an invalid 'externalInfoURL' value (") .append(rule.getExternalInfoUrl()) .append("), it should be:") .append(expectedExternalInfoURL) .append('\n'); } } // Proper class name/packaging? String expectedClassName = "net.sourceforge.pmd.lang." + language.getTerseName() + ".rule." + group + "." + rule.getName() + "Rule"; if (!rule.getRuleClass().equals(expectedClassName) && !validXPathClassNames.contains(rule.getRuleClass())) { invalidClassName++; messages.append("Rule ") .append(fileName) .append("/") .append(rule.getName()) .append(" seems to have an invalid 'class' value (") .append(rule.getRuleClass()) .append("), it should be:") .append(expectedClassName) .append('\n'); } // Should not have violation suppress regex property if (rule.getProperty(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR) != null) { invalidRegexSuppress++; messages.append("Rule ") .append(fileName) .append("/") .append(rule.getName()) .append(" should not have '") .append(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR.name()) .append("', this is intended for end user customization only.\n"); } // Should not have violation suppress xpath property if (rule.getProperty(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR) != null) { invalidXPathSuppress++; messages.append("Rule ").append(fileName).append("/").append(rule.getName()).append(" should not have '").append(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR.name()).append("', this is intended for end user customization only.").append(System.lineSeparator()); } } } // We do this at the end to ensure we test ALL the rules before failing // the test if (invalidSinceAttributes > 0 || invalidExternalInfoURL > 0 || invalidClassName > 0 || invalidRegexSuppress > 0 || invalidXPathSuppress > 0) { fail("All built-in PMD rules need 'since' attribute (" + invalidSinceAttributes + " are missing), a proper ExternalURLInfo (" + invalidExternalInfoURL + " are invalid), a class name meeting conventions (" + invalidClassName + " are invalid), no '" + Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR.name() + "' property (" + invalidRegexSuppress + " are invalid), and no '" + Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR.name() + "' property (" + invalidXPathSuppress + " are invalid)\n" + messages); } } /** * Verifies that all rulesets are valid XML according to the xsd schema. * * @throws Exception * any error */ @Test void testXmlSchema() throws Exception { boolean allValid = true; List<String> ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { boolean valid = validateAgainstSchema(fileName); allValid = allValid && valid; } assertTrue(allValid, "All XML must parse without producing validation messages."); } /** * Verifies that all rulesets are valid XML according to the DTD. * * @throws Exception * any error */ @Test void testDtd() throws Exception { boolean allValid = true; List<String> ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { boolean valid = validateAgainstDtd(fileName); allValid = allValid && valid; } assertTrue(allValid, "All XML must parse without producing validation messages."); } /** * Reads and writes the rulesets to make sure, that no data is lost if the * rulests are processed. * * @throws Exception * any error */ @Test void testReadWriteRoundTrip() throws Exception { List<String> ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { testRuleSet(fileName); } } // Gets all test PMD Ruleset XML files private List<String> getRuleSetFileNames() throws IOException { List<String> result = new ArrayList<>(); for (Language language : LanguageRegistry.PMD.getLanguages()) { if (this.languagesToSkip.contains(language.getTerseName())) { continue; } result.addAll(getRuleSetFileNames(language.getTerseName())); } return result; } private List<String> getRuleSetFileNames(String language) throws IOException { List<String> ruleSetFileNames = new ArrayList<>(); ruleSetFileNames.addAll(getRuleSetFileNames(language, "rulesets/" + language + "/rulesets.properties")); ruleSetFileNames.addAll(getRuleSetFileNames(language, "category/" + language + "/categories.properties")); return ruleSetFileNames; } private List<String> getRuleSetFileNames(String language, String propertiesPath) throws IOException { List<String> ruleSetFileNames = new ArrayList<>(); Properties properties = new Properties(); @SuppressWarnings("PMD.CloseResource") InputStream input = loadResourceAsStream(propertiesPath); if (input == null) { // this might happen if a language is only support by CPD, but not // by PMD System.err.println("No ruleset found for language " + language); return Collections.emptyList(); } try (InputStream is = input) { properties.load(is); } String fileNames = properties.getProperty("rulesets.filenames"); StringTokenizer st = new StringTokenizer(fileNames, ","); while (st.hasMoreTokens()) { ruleSetFileNames.add(st.nextToken()); } return ruleSetFileNames; } private RuleSet loadRuleSetByFileName(String ruleSetFileName) { return new RuleSetLoader().loadFromResource(ruleSetFileName); } private boolean validateAgainstSchema(String fileName) throws IOException, SAXException { try (InputStream inputStream = loadResourceAsStream(fileName)) { boolean valid = validateAgainstSchema(inputStream); if (!valid) { System.err.println("Validation against XML Schema failed for: " + fileName); } return valid; } } private boolean validateAgainstSchema(InputStream inputStream) throws IOException, SAXException { saxParser.parse(inputStream, validateDefaultHandler.resetValid()); inputStream.close(); return validateDefaultHandler.isValid(); } private boolean validateAgainstDtd(String fileName) throws IOException, SAXException { try (InputStream inputStream = loadResourceAsStream(fileName)) { boolean valid = validateAgainstDtd(inputStream); if (!valid) { System.err.println("Validation against DTD failed for: " + fileName); } return valid; } } private boolean validateAgainstDtd(InputStream inputStream) throws IOException, SAXException { // Read file into memory String file = readFullyToString(inputStream); inputStream.close(); String rulesetNamespace = RuleSetWriter.RULESET_2_0_0_NS_URI; // Remove XML Schema stuff, replace with DTD file = file.replaceAll("<\\?xml [ a-zA-Z0-9=\".-]*\\?>", ""); file = file.replaceAll("xmlns=\"" + rulesetNamespace + "\"", ""); file = file.replaceAll("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", ""); file = file.replaceAll("xsi:schemaLocation=\"" + rulesetNamespace + " https://pmd.sourceforge.io/ruleset_\\d_0_0.xsd\"", ""); if (RuleSetWriter.RULESET_2_0_0_NS_URI.equals(rulesetNamespace)) { file = "<?xml version=\"1.0\"?>" + System.lineSeparator() + "<!DOCTYPE ruleset SYSTEM \"https://pmd.sourceforge.io/ruleset_2_0_0.dtd\">" + System.lineSeparator() + file; } else { file = "<?xml version=\"1.0\"?>" + System.lineSeparator() + "<!DOCTYPE ruleset>" + System.lineSeparator() + file; } try (InputStream modifiedStream = new ByteArrayInputStream(file.getBytes())) { saxParser.parse(modifiedStream, validateDefaultHandler.resetValid()); } return validateDefaultHandler.isValid(); } private String readFullyToString(InputStream inputStream) throws IOException { StringBuilder buf = new StringBuilder(64 * 1024); try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { buf.append(line); buf.append(System.lineSeparator()); } return buf.toString(); } } private InputStream loadResourceAsStream(String resource) { return getClass().getClassLoader().getResourceAsStream(resource); } private void testRuleSet(String fileName) throws IOException, SAXException { // Load original XML // String xml1 = // readFullyToString(ResourceLoader.loadResourceAsStream(fileName)); // System.out.println("xml1: " + xml1); // Load the original RuleSet RuleSet ruleSet1 = loadRuleSetByFileName(fileName); // Write to XML, first time ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); RuleSetWriter writer1 = new RuleSetWriter(outputStream1); writer1.write(ruleSet1); writer1.close(); String xml2 = new String(outputStream1.toByteArray()); // System.out.println("xml2: " + xml2); // Read RuleSet from XML, first time RuleSetLoader loader = new RuleSetLoader(); RuleSet ruleSet2 = loader.loadFromString("", xml2); // Do write/read a 2nd time, just to be sure // Write to XML, second time ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); RuleSetWriter writer2 = new RuleSetWriter(outputStream2); writer2.write(ruleSet2); writer2.close(); String xml3 = new String(outputStream2.toByteArray()); // System.out.println("xml3: " + xml3); // Read RuleSet from XML, second time RuleSet ruleSet3 = loader.loadFromString("", xml3); // The 2 written XMLs should all be valid w.r.t Schema/DTD assertTrue(validateAgainstSchema(new ByteArrayInputStream(xml2.getBytes())), "1st roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")"); assertTrue(validateAgainstSchema(new ByteArrayInputStream(xml3.getBytes())), "2nd roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")"); assertTrue(validateAgainstDtd(new ByteArrayInputStream(xml2.getBytes())), "1st roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")"); assertTrue(validateAgainstDtd(new ByteArrayInputStream(xml3.getBytes())), "2nd roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")"); // All 3 versions of the RuleSet should be the same assertEqualsRuleSet("Original RuleSet and 1st roundtrip Ruleset not the same (filename: " + fileName + ")", ruleSet1, ruleSet2); assertEqualsRuleSet("1st roundtrip Ruleset and 2nd roundtrip RuleSet not the same (filename: " + fileName + ")", ruleSet2, ruleSet3); // It's hard to compare the XML DOMs. At least the roundtrip ones should // textually be the same. assertEquals(xml2, xml3, "1st roundtrip RuleSet XML and 2nd roundtrip RuleSet XML (filename: " + fileName + ")"); } private void assertEqualsRuleSet(String message, RuleSet ruleSet1, RuleSet ruleSet2) { assertEquals(ruleSet1.getName(), ruleSet2.getName(), message + ", RuleSet name"); assertEquals(ruleSet1.getDescription(), ruleSet2.getDescription(), message + ", RuleSet description"); assertEquals(ruleSet1.getFileExclusions(), ruleSet2.getFileExclusions(), message + ", RuleSet exclude patterns"); assertEquals(ruleSet1.getFileInclusions(), ruleSet2.getFileInclusions(), message + ", RuleSet include patterns"); assertEquals(ruleSet1.getRules().size(), ruleSet2.getRules().size(), message + ", RuleSet rule count"); for (int i = 0; i < ruleSet1.getRules().size(); i++) { Rule rule1 = ((List<Rule>) ruleSet1.getRules()).get(i); Rule rule2 = ((List<Rule>) ruleSet2.getRules()).get(i); assertFalse(rule1 instanceof RuleReference != rule2 instanceof RuleReference, message + ", Different RuleReference"); if (rule1 instanceof RuleReference) { RuleReference ruleReference1 = (RuleReference) rule1; RuleReference ruleReference2 = (RuleReference) rule2; assertEquals(ruleReference1.getOverriddenMinimumLanguageVersion(), ruleReference2.getOverriddenMinimumLanguageVersion(), message + ", RuleReference overridden minimum language version"); assertEquals(ruleReference1.getOverriddenMaximumLanguageVersion(), ruleReference2.getOverriddenMaximumLanguageVersion(), message + ", RuleReference overridden maximum language version"); assertEquals(ruleReference1.isOverriddenDeprecated(), ruleReference2.isOverriddenDeprecated(), message + ", RuleReference overridden deprecated"); assertEquals(ruleReference1.getOverriddenName(), ruleReference2.getOverriddenName(), message + ", RuleReference overridden name"); assertEquals(ruleReference1.getOverriddenDescription(), ruleReference2.getOverriddenDescription(), message + ", RuleReference overridden description"); assertEquals(ruleReference1.getOverriddenMessage(), ruleReference2.getOverriddenMessage(), message + ", RuleReference overridden message"); assertEquals(ruleReference1.getOverriddenExternalInfoUrl(), ruleReference2.getOverriddenExternalInfoUrl(), message + ", RuleReference overridden external info url"); assertEquals(ruleReference1.getOverriddenPriority(), ruleReference2.getOverriddenPriority(), message + ", RuleReference overridden priority"); assertEquals(ruleReference1.getOverriddenExamples(), ruleReference2.getOverriddenExamples(), message + ", RuleReference overridden examples"); } assertEquals(rule1.getName(), rule2.getName(), message + ", Rule name"); assertEquals(rule1.getRuleClass(), rule2.getRuleClass(), message + ", Rule class"); assertEquals(rule1.getDescription(), rule2.getDescription(), message + ", Rule description " + rule1.getName()); assertEquals(rule1.getMessage(), rule2.getMessage(), message + ", Rule message"); assertEquals(rule1.getExternalInfoUrl(), rule2.getExternalInfoUrl(), message + ", Rule external info url"); assertEquals(rule1.getPriority(), rule2.getPriority(), message + ", Rule priority"); assertEquals(rule1.getExamples(), rule2.getExamples(), message + ", Rule examples"); List<PropertyDescriptor<?>> propertyDescriptors1 = rule1.getPropertyDescriptors(); List<PropertyDescriptor<?>> propertyDescriptors2 = rule2.getPropertyDescriptors(); assertEquals(propertyDescriptors1, propertyDescriptors2, message + ", Rule property descriptor "); for (int j = 0; j < propertyDescriptors1.size(); j++) { Object value1 = rule1.getProperty(propertyDescriptors1.get(j)); Object value2 = rule2.getProperty(propertyDescriptors2.get(j)); // special case for Pattern, there is no equals method if (propertyDescriptors1.get(j).type() == Pattern.class) { value1 = ((Pattern) value1).pattern(); value2 = ((Pattern) value2).pattern(); } assertEquals(value1, value2, message + ", Rule property value " + j); } assertEquals(propertyDescriptors1.size(), propertyDescriptors2.size(), message + ", Rule property descriptor count"); } } /** * Validator for the SAX parser */ private static class ValidateDefaultHandler extends DefaultHandler { private boolean valid = true; private final Map<String, String> schemaMapping; ValidateDefaultHandler() { schemaMapping = new HashMap<>(); schemaMapping.put("https://pmd.sourceforge.io/ruleset_2_0_0.xsd", "ruleset_2_0_0.xsd"); schemaMapping.put("https://pmd.sourceforge.io/ruleset_2_0_0.dtd", "ruleset_2_0_0.dtd"); } public ValidateDefaultHandler resetValid() { valid = true; return this; } public boolean isValid() { return valid; } @Override public void error(SAXParseException e) { log("Error", e); } @Override public void fatalError(SAXParseException e) { log("FatalError", e); } @Override public void warning(SAXParseException e) { log("Warning", e); } private void log(String prefix, SAXParseException e) { String message = prefix + " at (" + e.getLineNumber() + ", " + e.getColumnNumber() + "): " + e.getMessage(); System.err.println(message); valid = false; } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException { String resource = schemaMapping.get(systemId); if (resource != null) { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resource); if (inputStream == null) { throw new FileNotFoundException(resource); } return new InputSource(inputStream); } throw new IllegalArgumentException( "No clue how to handle: publicId=" + publicId + ", systemId=" + systemId); } } }
25,968
44.321117
276
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import net.sourceforge.pmd.ant.SourceLanguage; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; /** * Base test class for {@link LanguageVersion} implementations. <br> * Each language implementation should subclass this and provide a method called {@code data}. * * <pre> * static Collection&lt;TestDescriptor&gt; data() { * return Arrays.asList( * new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.1", * LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.1")), * new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.2", * LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.2")), * * // doesn't exist * new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.3", null) * }; * </pre> * * <p>For the parameters, see the constructor * {@link TestDescriptor#TestDescriptor(String, String, String, LanguageVersion)}.</p> */ public abstract class AbstractLanguageVersionTest { public static class TestDescriptor { private final String name; private final String version; private final String simpleTerseName; private final LanguageVersion expected; /** * Creates a new {@link TestDescriptor} * * @param name * the name under which the language module is registered * @param terseName * the terse name under which the language module is registered * @param version * the specific version of the language version * @param expected * the expected {@link LanguageVersion} instance */ public TestDescriptor(String name, String terseName, String version, LanguageVersion expected) { this.name = name; this.version = version; this.simpleTerseName = terseName; this.expected = expected; } public String getName() { return name; } public String getVersion() { return version; } public String getSimpleTerseName() { return simpleTerseName; } public LanguageVersion getExpected() { return expected; } } protected static Language getLanguage(String name) { return LanguageRegistry.PMD.getLanguageByFullName(name); } /** * Checks that the expected {@link LanguageVersion} can be found via * {@link TestDescriptor#name} and {@link TestDescriptor#version}. */ @ParameterizedTest @MethodSource("data") void testFindVersionsForLanguageNameAndVersion(TestDescriptor testDescriptor) { SourceLanguage sourceLanguage = new SourceLanguage(); sourceLanguage.setName(testDescriptor.getName()); sourceLanguage.setVersion(testDescriptor.getVersion()); Language language = getLanguage(sourceLanguage.getName()); LanguageVersion languageVersion = null; if (language != null) { languageVersion = language.getVersion(sourceLanguage.getVersion()); } assertEquals(testDescriptor.getExpected(), languageVersion); } /** * Makes sure, that for each language a "categories.properties" file exists. * * @throws Exception * any error */ @ParameterizedTest @MethodSource("data") void testRegisteredRulesets(TestDescriptor testDescriptor) throws Exception { if (testDescriptor.getExpected() == null) { return; } Properties props = new Properties(); String rulesetsProperties = "/category/" + testDescriptor.getSimpleTerseName() + "/categories.properties"; try (InputStream inputStream = getClass().getResourceAsStream(rulesetsProperties)) { if (inputStream == null) { throw new IOException(); } props.load(inputStream); } assertRulesetsAndCategoriesProperties(props); } /** * If a rulesets.properties file still exists, test it as well. * * @throws Exception * any error */ @ParameterizedTest @MethodSource("data") void testOldRegisteredRulesets(TestDescriptor testDescriptor) throws Exception { // only check for languages, that support rules if (testDescriptor.getExpected() == null) { return; } Properties props = new Properties(); String rulesetsProperties = "/rulesets/" + testDescriptor.getSimpleTerseName() + "/rulesets.properties"; InputStream inputStream = getClass().getResourceAsStream(rulesetsProperties); if (inputStream != null) { // rulesets.properties file exists try (InputStream in = inputStream) { props.load(in); } assertRulesetsAndCategoriesProperties(props); } } @ParameterizedTest @MethodSource("data") void testVersionsAreDistinct(TestDescriptor testDescriptor) { LanguageVersion expected = testDescriptor.getExpected(); if (expected == null) { return; } Language lang = expected.getLanguage(); int count = 0; for (LanguageVersion lv : lang.getVersions()) { if (lv.equals(expected)) { count++; } } assertEquals(1, count, "Expected exactly one occurrence of " + expected + " in the language versions of its language"); } private void assertRulesetsAndCategoriesProperties(Properties props) throws IOException { String rulesetFilenames = props.getProperty("rulesets.filenames"); assertNotNull(rulesetFilenames); RuleSetLoader rulesetLoader = new RuleSetLoader(); if (rulesetFilenames.trim().isEmpty()) { return; } String[] rulesets = rulesetFilenames.split(","); for (String r : rulesets) { RuleSet ruleset = rulesetLoader.loadFromResource(r); assertNotNull(ruleset); } } }
6,758
32.964824
114
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/ant/AbstractAntTestHelper.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.ant; import static java.io.File.separator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration; import com.github.stefanbirkner.systemlambda.Statement; import com.github.stefanbirkner.systemlambda.SystemLambda; /** * Base test class for ant tests. * * <p>Usage template: * * <pre> * {@code * class MyPMDTaskTest extends AbstractAntTestHelper { * MyPMDTaskTest() { * antTestScriptFilename = "mypmdtasktest.xml"; * } * * @Test * void myTest() { * executeTarget("testMyTarget"); * assertOutputContaining("Expected Violation Message"); * } * } * } * </pre> * * @author Romain Pelisse &lt;belaran@gmail.com&gt; * */ public abstract class AbstractAntTestHelper { @TempDir private Path tempFolder; protected String pathToTestScript; protected String antTestScriptFilename; private Project antProject; private StringBuilder log = new StringBuilder(); private String output; public AbstractAntTestHelper() { pathToTestScript = "target/test-classes/net/sourceforge/pmd/ant/xml"; } @BeforeEach public void setUp() throws IOException { validatePostConstruct(); // initialize Ant antProject = new Project(); antProject.init(); antProject.addBuildListener(new AntBuildListener()); ProjectHelper.configureProject(antProject, new File(pathToTestScript + separator + antTestScriptFilename)); // Each test case gets one temp file name, accessible with property ${tmpfile} Path tmpFile = Files.createTempFile(tempFolder, "pmd-ant-tests", null); // we delete the tmpfile again, since we only wanted to have a unique temp filename // the tmpfile is used for creating reports. Files.deleteIfExists(tmpFile); antProject.setProperty("tmpfile", tmpFile.toAbsolutePath().toString()); } @AfterAll static void resetLogging() { Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null); } /** * Returns the current temporary file. Replaced by a fresh (inexistent) * file before each test. */ public File currentTempFile() { String tmpname = antProject.getProperty("tmpfile"); return tmpname == null ? null : new File(tmpname); } private void validatePostConstruct() { if (pathToTestScript == null || "".equals(pathToTestScript) || antTestScriptFilename == null || "".equals(antTestScriptFilename)) { throw new IllegalStateException("Unit tests for Ant script badly initialized"); } } public String executeTarget(String target) { try { restoreLocale(() -> { // restoring system properties: Test might change file.encoding or might change logging properties // See Slf4jSimpleConfigurationForAnt and resetLogging SystemLambda.restoreSystemProperties(() -> { output = tapSystemOut(() -> { antProject.executeTarget(target); }); }); }); return output; } catch (Exception e) { throw new RuntimeException(e); } } protected String getLog() { return log.toString(); } public void assertOutputContaining(String text) { assertThat(output, containsString(text)); } public void assertContains(String text, String toFind) { assertThat(text, containsString(toFind)); } public void assertDoesntContain(String text, String toFind) { assertThat(text, not(containsString(toFind))); } private static void restoreLocale(Statement statement) throws Exception { Locale originalLocale = Locale.getDefault(); try { statement.execute(); } finally { Locale.setDefault(originalLocale); } } /** * This is similar to {@link SystemLambda#tapSystemOut(Statement)}. But this * method doesn't use the platform default charset as it was when the JVM started. * Instead, it uses the current system property {@code file.encoding}. This allows * tests to change the encoding. * * @param statement an arbitrary piece of code. * @return text that is written to stdout. Lineendings are normalized to {@code \n}. * @throws Exception any exception thrown by the statement */ private static String tapSystemOut(Statement statement) throws Exception { @SuppressWarnings("PMD.CloseResource") // we don't want to close System.out PrintStream originalOut = System.out; ByteArrayOutputStream text = new ByteArrayOutputStream(); String currentDefaultCharset = System.getProperty("file.encoding"); try { PrintStream replacement = new PrintStream(text, true, currentDefaultCharset); System.setOut(replacement); statement.execute(); } finally { System.setOut(originalOut); } String result = text.toString(currentDefaultCharset); return result.replace(System.lineSeparator(), "\n"); } private final class AntBuildListener extends DefaultLogger { private AntBuildListener() { msgOutputLevel = Project.MSG_INFO; } @Override protected void printMessage(String message, PrintStream stream, int priority) { log.append(message); } @Override public void messageLogged(BuildEvent buildEvent) { if (buildEvent.getPriority() <= Project.MSG_INFO) { log.append(buildEvent.getMessage()); } } } }
6,463
31.32
115
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PmdRuleTst.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.testframework; import java.util.Collections; import java.util.List; import net.sourceforge.pmd.Rule; public class PmdRuleTst extends RuleTst { @Override protected void setUp() { // empty, nothing to do } @Override protected List<Rule> getRules() { String[] packages = getClass().getPackage().getName().split("\\."); String categoryName = packages[packages.length - 1]; String language = packages[packages.length - 3]; String rulesetXml = "category/" + language + "/" + categoryName + ".xml"; Rule rule = findRule(rulesetXml, getClass().getSimpleName().replaceFirst("Test$", "")); return Collections.singletonList(rule); } }
827
26.6
95
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.testframework; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.xml.sax.InputSource; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetLoadException; import net.sourceforge.pmd.RuleSetLoader; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.renderers.TextRenderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.test.schema.RuleTestCollection; import net.sourceforge.pmd.test.schema.RuleTestDescriptor; import net.sourceforge.pmd.test.schema.TestSchemaParser; /** * Advanced methods for test cases */ public abstract class RuleTst { protected void setUp() { // This method is intended to be overridden by subclasses. } protected List<Rule> getRules() { return Collections.emptyList(); } /** * Find a rule in a certain ruleset by name. */ public static Rule findRule(String ruleSet, String ruleName) { try { RuleSet parsedRset = new RuleSetLoader().warnDeprecated(false).loadFromResource(ruleSet); Rule rule = parsedRset.getRuleByName(ruleName); if (rule == null) { fail("Rule " + ruleName + " not found in ruleset " + ruleSet); } else { rule.setRuleSetName(ruleSet); } return rule; } catch (RuleSetLoadException e) { e.printStackTrace(); fail("Couldn't find ruleset " + ruleSet); return null; } } /** * Run the rule on the given code, and check the expected number of violations. */ void runTest(RuleTestDescriptor test) { Rule rule = test.getRule(); // always reinitialize the rule, regardless of test.getReinitializeRule() (#3976 / #3302) rule = reinitializeRule(rule); Map<PropertyDescriptor<?>, Object> oldProperties = rule.getPropertiesByPropertyDescriptor(); try { int res; Report report; try { // Set test specific properties onto the Rule if (test.getProperties() != null) { for (Map.Entry<Object, Object> entry : test.getProperties().entrySet()) { String propertyName = (String) entry.getKey(); PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(propertyName); if (propertyDescriptor == null) { throw new IllegalArgumentException( "No such property '" + propertyName + "' on Rule " + rule.getName()); } Object value = propertyDescriptor.valueFrom((String) entry.getValue()); rule.setProperty(propertyDescriptor, value); } } String dysfunctionReason = rule.dysfunctionReason(); if (StringUtils.isNotBlank(dysfunctionReason)) { throw new RuntimeException("Rule is not configured correctly: " + dysfunctionReason); } report = processUsingStringReader(test, rule); res = report.getViolations().size(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException('"' + test.getDescription() + "\" failed", e); } if (test.getExpectedProblems() != res) { printReport(test, report); } assertEquals(test.getExpectedProblems(), res, '"' + test.getDescription() + "\" resulted in wrong number of failures,"); assertMessages(report, test); assertLineNumbers(report, test); } finally { // Restore old properties for (Map.Entry<PropertyDescriptor<?>, Object> entry : oldProperties.entrySet()) { rule.setProperty((PropertyDescriptor) entry.getKey(), entry.getValue()); } } } /** * Code to be executed if the rule is reinitialised. * * @param rule The rule to reinitialise * * @return The rule once it has been reinitialised */ private Rule reinitializeRule(Rule rule) { return rule.deepCopy(); } private void assertMessages(Report report, RuleTestDescriptor test) { if (report == null || test.getExpectedMessages().isEmpty()) { return; } List<String> expectedMessages = test.getExpectedMessages(); if (report.getViolations().size() != expectedMessages.size()) { throw new RuntimeException("Test setup error: number of expected messages doesn't match " + "number of violations for test case '" + test.getDescription() + "'"); } int index = 0; for (RuleViolation violation : report.getViolations()) { String actual = violation.getDescription(); if (!expectedMessages.get(index).equals(actual)) { printReport(test, report); } assertEquals(expectedMessages.get(index), actual, '"' + test.getDescription() + "\" produced wrong message on violation number " + (index + 1) + "."); index++; } } private void assertLineNumbers(Report report, RuleTestDescriptor test) { if (report == null || test.getExpectedLineNumbers().isEmpty()) { return; } List<Integer> expected = test.getExpectedLineNumbers(); if (report.getViolations().size() != expected.size()) { throw new RuntimeException("Test setup error: number of expected line numbers " + expected.size() + " doesn't match number of violations " + report.getViolations().size() + " for test case '" + test.getDescription() + "'"); } int index = 0; for (RuleViolation violation : report.getViolations()) { Integer actual = violation.getBeginLine(); if (expected.get(index) != actual.intValue()) { printReport(test, report); } assertEquals(expected.get(index), actual, '"' + test.getDescription() + "\" violation on wrong line number: violation number " + (index + 1) + "."); index++; } } private void printReport(RuleTestDescriptor test, Report report) { System.out.println("--------------------------------------------------------------"); System.out.println("Test Failure: " + test.getDescription()); System.out.println( " -> Expected " + test.getExpectedProblems() + " problem(s), " + report.getViolations().size() + " problem(s) found."); System.out.println(" -> Expected messages: " + test.getExpectedMessages()); System.out.println(" -> Expected line numbers: " + test.getExpectedLineNumbers()); System.out.println(); StringWriter reportOutput = new StringWriter(); TextRenderer renderer = new TextRenderer(); renderer.setWriter(reportOutput); try { renderer.start(); renderer.renderFileReport(report); renderer.end(); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(reportOutput); System.out.println("--------------------------------------------------------------"); } private Report processUsingStringReader(RuleTestDescriptor test, Rule rule) { return runTestFromString(test.getCode(), rule, test.getLanguageVersion()); } /** * Run the rule on the given code and put the violations in the report. */ Report runTestFromString(String code, Rule rule, LanguageVersion languageVersion) { PMDConfiguration configuration = new PMDConfiguration(); configuration.setIgnoreIncrementalAnalysis(true); configuration.setDefaultLanguageVersion(languageVersion); configuration.setThreads(0); // don't use separate threads configuration.prependAuxClasspath("."); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { pmd.files().addFile(TextFile.forCharSeq(code, FileId.fromPathLikeString("file"), languageVersion)); pmd.addRuleSet(RuleSet.forSingleRule(rule)); pmd.addListener(GlobalAnalysisListener.exceptionThrower()); return pmd.performAnalysisAndCollectReport(); } } /** * getResourceAsStream tries to find the XML file in weird locations if the * ruleName includes the package, so we strip it here. */ private String getCleanRuleName(Rule rule) { String fullClassName = rule.getClass().getName(); if (fullClassName.equals(rule.getName())) { // We got the full class name, so we'll use the stripped name // instead String packageName = rule.getClass().getPackage().getName(); return fullClassName.substring(packageName.length() + 1); } else { return rule.getName(); // Test is using findRule, smart! } } /** * Extract a set of tests from an XML file. The file should be * ./xml/RuleName.xml relative to the test class. The format is defined in * rule-tests_1_0_0.xsd in pmd-test-schema. */ RuleTestCollection parseTestCollection(Rule rule) { String testsFileName = getCleanRuleName(rule); return parseTestCollection(rule, testsFileName); } private RuleTestCollection parseTestCollection(Rule rule, String testsFileName) { return parseTestXml(rule, testsFileName, "xml/"); } /** * Extract a set of tests from an XML file with the given name. The file * should be ./xml/[testsFileName].xml relative to the test class. The * format is defined in test-data.xsd. */ private RuleTestCollection parseTestXml(Rule rule, String testsFileName, String baseDirectory) { String testXmlFileName = baseDirectory + testsFileName + ".xml"; String absoluteUriToTestXmlFile = new File(".").getAbsoluteFile().toURI() + "/src/test/resources/" + this.getClass().getPackage().getName().replaceAll("\\.", "/") + "/" + testXmlFileName; try (InputStream inputStream = getClass().getResourceAsStream(testXmlFileName)) { if (inputStream == null) { throw new RuntimeException("Couldn't find " + testXmlFileName); } InputSource source = new InputSource(); source.setByteStream(inputStream); source.setSystemId(testXmlFileName); TestSchemaParser parser = new TestSchemaParser(); RuleTestCollection ruleTestCollection = parser.parse(rule, source); ruleTestCollection.setAbsoluteUriToTestXmlFile(absoluteUriToTestXmlFile); return ruleTestCollection; } catch (Exception e) { throw new RuntimeException("Couldn't parse " + testXmlFileName + ", due to: " + e, e); } } /** * Run a set of tests defined in an XML test-data file for a rule. The file * should be ./xml/RuleName.xml relative to the test-class. The format is * defined in test-data.xsd. */ public void runTests(Rule rule) { runTests(parseTestCollection(rule)); } /** * Run a set of tests defined in a XML test-data file. The file should be * ./xml/[testsFileName].xml relative to the test-class. The format is * defined in test-data.xsd. */ public void runTests(Rule rule, String testsFileName) { runTests(parseTestCollection(rule, testsFileName)); } private void runTests(RuleTestCollection tests) { for (RuleTestDescriptor test : tests.getTests()) { runTest(test); } } @TestFactory Collection<DynamicTest> ruleTests() { setUp(); final List<Rule> rules = new ArrayList<>(getRules()); rules.sort(Comparator.comparing(Rule::getName)); List<DynamicTest> tests = new ArrayList<>(); for (Rule r : rules) { RuleTestCollection ruleTests = parseTestCollection(r); RuleTestDescriptor focused = ruleTests.getFocusedTestOrNull(); for (RuleTestDescriptor t : ruleTests.getTests()) { if (focused != null && !focused.equals(t)) { t.setDisabled(true); // disable it } tests.add(toDynamicTest(ruleTests, t)); } } return tests; } private DynamicTest toDynamicTest(RuleTestCollection collection, RuleTestDescriptor testDescriptor) { URI testSourceUri = URI.create( collection.getAbsoluteUriToTestXmlFile() + "?line=" + testDescriptor.getLineNumber()); if (testDescriptor.isDisabled()) { return DynamicTest.dynamicTest("[IGNORED] " + testDescriptor.getDescription(), testSourceUri, () -> { }); } return DynamicTest.dynamicTest(testDescriptor.getDescription(), testSourceUri, () -> runTest(testDescriptor)); } }
14,505
39.861972
117
java
pmd
pmd-master/pmd-test/src/main/java/net/sourceforge/pmd/testframework/SimpleAggregatorTst.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.testframework; import java.util.ArrayList; import java.util.List; import net.sourceforge.pmd.Rule; /** * Simple setup for a rule unit test, * capable of testing multiple rules. * * <p>Override {@link #setUp()} to register the * rules, that should be tested via calls to * {@link #addRule(String, String)}. */ public abstract class SimpleAggregatorTst extends RuleTst { private final List<Rule> rules = new ArrayList<>(); /** * Configure the rule tests to be executed. Override this method in * subclasses by calling addRule, e.g. * * <pre>addRule("path/myruleset.xml", "CustomRule");</pre> * * @see #addRule(String, String) */ @Override protected void setUp() { // empty, to be overridden. } /** * Add new XML tests associated with the rule to the test suite. This should * be called from the setup method. */ protected void addRule(String ruleSet, String ruleName) { rules.add(findRule(ruleSet, ruleName)); } /** * Gets all configured rules. * * @return all configured rules. */ @Override protected List<Rule> getRules() { return rules; } }
1,315
22.927273
80
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/LanguageVersionDiscovererTest.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; import net.sourceforge.pmd.lang.jsp.ast.AbstractJspNodesTst; class LanguageVersionDiscovererTest extends AbstractJspNodesTst { @Test void testParseJsp() { testLanguageIsJsp("sample.jsp"); testLanguageIsJsp("sample.jspx"); } @Test void testTag() { testLanguageIsJsp("sample.tag"); } private void testLanguageIsJsp(String first) { assertEquals(jsp.getLanguage().getDefaultVersion(), getLanguageVersion(Paths.get(first))); } @Test void testParseWrong() { assertNotEquals(jsp.getLanguage().getDefaultVersion(), getLanguageVersion(Paths.get("sample.xxx"))); } private LanguageVersion getLanguageVersion(Path jspFile) { LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD); return discoverer.getDefaultLanguageVersionForFile(jspFile.toFile()); } }
1,453
28.08
99
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/RuleSetFactoryTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; /** * Test jsp's rulesets */ class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { // no additional tests yet }
310
19.733333
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/LanguageVersionTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp; import java.util.Arrays; import java.util.Collection; import net.sourceforge.pmd.AbstractLanguageVersionTest; class LanguageVersionTest extends AbstractLanguageVersionTest { static Collection<TestDescriptor> data() { return Arrays.asList(new TestDescriptor(JspLanguageModule.NAME, JspLanguageModule.TERSE_NAME, "3", getLanguage(JspLanguageModule.NAME).getDefaultVersion())); } }
542
27.578947
106
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/JspParserTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.jsp.ast.AbstractJspNodesTst; /** * Unit test for JSP parsing. * */ class JspParserTest extends AbstractJspNodesTst { /** * Verifies bug #939 Jsp parser fails on $ */ @Test void testParseDollar() { jsp.parse("<span class=\"CostUnit\">$</span><span class=\"CostMain\">129</span><span class=\"CostFrac\">.00</span>"); } @Test void testParseELAttribute() { jsp.parse("<div ${something ? 'class=\"red\"' : ''}> Div content here.</div>"); } @Test void testParseELAttributeValue() { jsp.parse("<div class=\"${something == 0 ? 'zero_something' : something == 1 ? 'one_something' : 'other_something'}\">Div content here.</div>"); } /** * Verifies bug #311 Jsp parser fails on boolean attribute */ @Test void testParseBooleanAttribute() { jsp.parse("<label><input type='checkbox' checked name=cheese disabled=''> Cheese</label>"); } }
1,137
25.465116
152
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/JspParsingHelper.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper; import net.sourceforge.pmd.lang.jsp.JspLanguageModule; public final class JspParsingHelper extends BaseParsingHelper<JspParsingHelper, ASTCompilationUnit> { public static final JspParsingHelper DEFAULT = new JspParsingHelper(Params.getDefault()); private JspParsingHelper(Params params) { super(JspLanguageModule.NAME, ASTCompilationUnit.class, params); } @Override protected JspParsingHelper clone(Params params) { return new JspParsingHelper(params); } }
693
29.173913
101
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/JspPageStyleTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; class JspPageStyleTest extends AbstractJspNodesTst { /** * Test parsing of a JSP comment. */ @Test void testComment() { List<ASTJspComment> comments = jsp.getNodes(ASTJspComment.class, JSP_COMMENT); assertEquals(1, comments.size(), "One comment expected!"); ASTJspComment comment = comments.iterator().next(); assertEquals("some comment", comment.getImage(), "Correct comment content expected!"); } /** * Test parsing a JSP directive. */ @Test void testDirective() { ASTCompilationUnit root = jsp.parse(JSP_DIRECTIVE); List<ASTJspDirective> directives = root.findDescendantsOfType(ASTJspDirective.class); assertEquals(1, directives.size(), "One directive expected!"); ASTJspDirective directive = directives.iterator().next(); assertEquals("page", directive.getName(), "Correct directive name expected!"); List<ASTJspDirectiveAttribute> directiveAttrs = root.findDescendantsOfType(ASTJspDirectiveAttribute.class); assertEquals(2, directiveAttrs.size(), "Two directive attributes expected!"); ASTJspDirectiveAttribute attr = directiveAttrs.get(0); assertEquals("language", attr.getName(), "Correct directive attribute name expected!"); assertEquals("java", attr.getValue(), "Correct directive attribute value expected!"); attr = directiveAttrs.get(1); assertEquals("session", attr.getName(), "Correct directive attribute name expected!"); assertEquals("true", attr.getValue(), "Correct directive attribute value expected!"); } /** * Test parsing of a JSP declaration. */ @Test void testDeclaration() { List<ASTJspDeclaration> declarations = jsp.getNodes(ASTJspDeclaration.class, JSP_DECLARATION); assertEquals(1, declarations.size(), "One declaration expected!"); ASTJspDeclaration declaration = declarations.iterator().next(); assertEquals("String someString = \"s\";", declaration.getImage(), "Correct declaration content expected!"); } /** * Test parsing of a JSP scriptlet. */ @Test void testScriptlet() { List<ASTJspScriptlet> scriptlets = jsp.getNodes(ASTJspScriptlet.class, JSP_SCRIPTLET); assertEquals(1, scriptlets.size(), "One scriptlet expected!"); ASTJspScriptlet scriptlet = scriptlets.iterator().next(); assertEquals("someString = someString + \"suffix\";", scriptlet.getImage(), "Correct scriptlet content expected!"); } /** * Test parsing of a JSP expression. */ @Test void testExpression() { List<ASTJspExpression> expressions = jsp.getNodes(ASTJspExpression.class, JSP_EXPRESSION); assertEquals(1, expressions.size(), "One expression expected!"); ASTJspExpression expression = expressions.iterator().next(); assertEquals("someString", expression.getImage(), "Correct expression content expected!"); } /** * Test parsing of a JSP expression in an attribute. */ @Test void testExpressionInAttribute() { List<ASTJspExpressionInAttribute> expressions = jsp.getNodes(ASTJspExpressionInAttribute.class, JSP_EXPRESSION_IN_ATTRIBUTE); assertEquals(1, expressions.size(), "One expression expected!"); ASTJspExpressionInAttribute expression = expressions.iterator().next(); assertEquals("style.getClass()", expression.getImage(), "Correct expression content expected!"); } /** * Test parsing of a EL expression. */ @Test void testElExpression() { List<ASTElExpression> expressions = jsp.getNodes(ASTElExpression.class, JSP_EL_EXPRESSION); assertEquals(1, expressions.size(), "One expression expected!"); ASTElExpression expression = expressions.iterator().next(); assertEquals("myBean.get(\"${ World }\")", expression.getImage(), "Correct expression content expected!"); } /** * Test parsing of a EL expression in an attribute. */ @Test void testElExpressionInAttribute() { List<ASTElExpression> expressions = jsp.getNodes(ASTElExpression.class, JSP_EL_EXPRESSION_IN_ATTRIBUTE); assertEquals(1, expressions.size(), "One expression expected!"); ASTElExpression expression = expressions.iterator().next(); assertEquals("myValidator.find(\"'jsp'\")", expression.getImage(), "Correct expression content expected!"); } /** * Test parsing of a EL expression in an attribute. */ @Test void testJsfValueBinding() { List<ASTValueBinding> valueBindings = jsp.getNodes(ASTValueBinding.class, JSF_VALUE_BINDING); assertEquals(1, valueBindings.size(), "One value binding expected!"); ASTValueBinding valueBinding = valueBindings.iterator().next(); assertEquals("myValidator.find(\"'jsf'\")", valueBinding.getImage(), "Correct expression content expected!"); } private static final String JSP_COMMENT = "<html> <%-- some comment --%> </html>"; private static final String JSP_DIRECTIVE = "<html> <%@ page language=\"java\" session='true'%> </html>"; private static final String JSP_DECLARATION = "<html><%! String someString = \"s\"; %></html>"; private static final String JSP_SCRIPTLET = "<html> <% someString = someString + \"suffix\"; %> </html>"; private static final String JSP_EXPRESSION = "<html><head><title> <%= someString %> </title></head></html>"; private static final String JSP_EXPRESSION_IN_ATTRIBUTE = "<html> <body> <p class='<%= style.getClass() %>'> Hello </p> </body> </html>"; private static final String JSP_EL_EXPRESSION = "<html><title>Hello ${myBean.get(\"${ World }\") } .jsp</title></html>"; private static final String JSP_EL_EXPRESSION_IN_ATTRIBUTE = "<html> <f:validator type=\"get('type').${myValidator.find(\"'jsp'\")}\" /> </html>"; private static final String JSF_VALUE_BINDING = "<html> <body> <p class='#{myValidator.find(\"'jsf'\")}'> Hello </p> </body> </html>"; }
6,319
41.993197
150
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/OpenTagRegisterTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class OpenTagRegisterTest { private OpenTagRegister tagList; private int elmId = 0; @BeforeEach public void newRegister() { tagList = new OpenTagRegister(); } /** * &lt;a&gt; &lt;b&gt; &lt;/a&gt; */ @Test void testSimpleNesting() { ASTElement elm = element("a"); ASTElement elm2 = element("b"); tagList.openTag(elm); tagList.openTag(elm2); tagList.closeTag(elm); assertFalse(elm.isUnclosed()); assertTrue(elm2.isUnclosed()); } /** * &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/a&gt; */ @Test void doubleNesting() { ASTElement elm = element("a"); ASTElement elm2 = element("b"); ASTElement elm3 = element("b"); tagList.openTag(elm); tagList.openTag(elm2); tagList.openTag(elm3); tagList.closeTag(elm); assertFalse(elm.isUnclosed()); assertTrue(elm2.isUnclosed()); assertTrue(elm3.isUnclosed()); } /** * &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/x&gt; &lt;/a&gt; &lt;/x&gt; */ @Test void unopenedTags() { ASTElement elm = element("x"); ASTElement elm2 = element("a"); ASTElement elm3 = element("b"); ASTElement elm4 = element("b"); tagList.openTag(elm); tagList.openTag(elm2); tagList.openTag(elm3); tagList.openTag(elm4); tagList.closeTag(elm); tagList.closeTag(elm2); tagList.closeTag(elm3); tagList.closeTag(elm); assertFalse(elm.isUnclosed()); assertTrue(elm2.isUnclosed()); assertTrue(elm3.isUnclosed()); assertTrue(elm4.isUnclosed()); } /** * &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/z&gt; &lt;/a&gt; &lt;/x&gt; * */ @Test void interleavedTags() { ASTElement elm = element("x"); ASTElement elm2 = element("a"); ASTElement elm3 = element("b"); ASTElement elm4 = element("b"); ASTElement elm5 = element("z"); tagList.openTag(elm); tagList.openTag(elm2); tagList.openTag(elm3); tagList.openTag(elm4); // open b tagList.closeTag(elm5); // close z tagList.closeTag(elm2); // close a tagList.closeTag(elm); // close x assertFalse(elm.isUnclosed()); // x is closed assertFalse(elm2.isUnclosed()); // a is closed assertTrue(elm3.isUnclosed()); assertTrue(elm4.isUnclosed()); // elm5 ??? } /** * &lt;a&gt; &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/z&gt; &lt;/a&gt; &lt;/x&gt; */ @Test void openedIsolatedTag() { ASTElement a = element("a"); ASTElement x = element("x"); ASTElement a2 = element("a"); ASTElement b = element("b"); ASTElement b2 = element("b"); ASTElement z = element("z"); tagList.openTag(a); tagList.openTag(x); tagList.openTag(a2); tagList.openTag(b); tagList.openTag(b2); tagList.closeTag(z); // close z tagList.closeTag(a2); // close second a tagList.closeTag(x); // close x assertTrue(a.isUnclosed()); // first a is unclosed assertFalse(x.isUnclosed()); // x is closed assertFalse(a2.isUnclosed()); // a is closed assertTrue(b.isUnclosed()); assertTrue(b2.isUnclosed()); } private ASTElement element(String name) { ASTElement elm = new ASTElement(elmId++); elm.setName(name); return elm; } }
3,905
25.571429
89
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/JspDocStyleTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; 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 java.util.List; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * Test parsing of a JSP in document style, by checking the generated AST. * * @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be * */ class JspDocStyleTest extends AbstractJspNodesTst { /** * Smoke test for JSP parser. */ @Test void testSimplestJsp() { List<ASTElement> nodes = jsp.getNodes(ASTElement.class, TEST_SIMPLEST_HTML); assertEquals(1, nodes.size(), "Exactly " + 1 + " element(s) expected"); } /** * Test the information on a Element and Attribute. */ @Test void testElementAttributeAndNamespace() { ASTCompilationUnit root = jsp.parse(TEST_ELEMENT_AND_NAMESPACE); List<ASTElement> elementNodes = root.findDescendantsOfType(ASTElement.class); assertEquals(1, elementNodes.size(), "One element node expected!"); ASTElement element = elementNodes.get(0); assertEquals("h:html", element.getName(), "Correct name expected!"); assertTrue(element.isHasNamespacePrefix(), "Has namespace prefix!"); assertTrue(element.isEmpty(), "Element is empty!"); assertEquals("h", element.getNamespacePrefix(), "Correct namespace prefix of element expected!"); assertEquals("html", element.getLocalName(), "Correct local name of element expected!"); List<ASTAttribute> attributeNodes = root.findDescendantsOfType(ASTAttribute.class); assertEquals(1, attributeNodes.size(), "One attribute node expected!"); ASTAttribute attribute = attributeNodes.get(0); assertEquals("MyNsPrefix:MyAttr", attribute.getName(), "Correct name expected!"); assertTrue(attribute.isHasNamespacePrefix(), "Has namespace prefix!"); assertEquals("MyNsPrefix", attribute.getNamespacePrefix(), "Correct namespace prefix of element expected!"); assertEquals("MyAttr", attribute.getLocalName(), "Correct local name of element expected!"); } /** * Test exposing a bug of parsing error when having a hash as last character * in an attribute value. * */ @Test void testAttributeValueContainingHash() { ASTCompilationUnit root = jsp.parse(TEST_ATTRIBUTE_VALUE_CONTAINING_HASH); List<ASTAttribute> attrsList = root.findDescendantsOfType(ASTAttribute.class); assertEquals(3, attrsList.size(), "Three attributes expected!"); ASTAttribute attr = attrsList.get(0); assertEquals("something", attr.getName(), "Correct attribute name expected!"); assertEquals("#yes#", attr.getFirstDescendantOfType(ASTAttributeValue.class).getImage(), "Correct attribute value expected!"); attr = attrsList.get(1); assertEquals("foo", attr.getName(), "Correct attribute name expected!"); assertEquals("CREATE", attr.getFirstDescendantOfType(ASTAttributeValue.class).getImage(), "Correct attribute value expected!"); attr = attrsList.get(2); assertEquals("href", attr.getName(), "Correct attribute name expected!"); assertEquals("#", attr.getFirstDescendantOfType(ASTAttributeValue.class).getImage(), "Correct attribute value expected!"); } /** * Test correct parsing of CDATA. */ @Test void testCData() { List<ASTCData> cdataNodes = jsp.getNodes(ASTCData.class, TEST_CDATA); assertEquals(1, cdataNodes.size(), "One CDATA node expected!"); ASTCData cdata = cdataNodes.get(0); assertEquals(" some <cdata> ]] ]> ", cdata.getImage(), "Content incorrectly parsed!"); } /** * Test parsing of Doctype declaration. */ @Test void testDoctype() { ASTCompilationUnit root = jsp.parse(TEST_DOCTYPE); List<ASTDoctypeDeclaration> docTypeDeclarations = root.findDescendantsOfType(ASTDoctypeDeclaration.class); assertEquals(1, docTypeDeclarations.size(), "One doctype declaration expected!"); ASTDoctypeDeclaration docTypeDecl = docTypeDeclarations.iterator().next(); assertEquals("html", docTypeDecl.getName(), "Correct doctype-name expected!"); List<ASTDoctypeExternalId> externalIds = root.findDescendantsOfType(ASTDoctypeExternalId.class); assertEquals(1, externalIds.size(), "One doctype external id expected!"); ASTDoctypeExternalId externalId = externalIds.iterator().next(); assertEquals("-//W3C//DTD XHTML 1.1//EN", externalId.getPublicId(), "Correct external public id expected!"); assertEquals("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd", externalId.getUri(), "Correct external uri expected!"); } /** * Test parsing of a XML comment. * */ @Test void testComment() { List<ASTCommentTag> comments = jsp.getNodes(ASTCommentTag.class, TEST_COMMENT); assertEquals(1, comments.size(), "One comment expected!"); ASTCommentTag comment = comments.iterator().next(); assertEquals("comment", comment.getImage(), "Correct comment content expected!"); } /** * Test parsing of HTML &lt;script&gt; element. */ @Test void testHtmlScript() { List<ASTHtmlScript> scripts = jsp.getNodes(ASTHtmlScript.class, TEST_HTML_SCRIPT); assertEquals(1, scripts.size(), "One script expected!"); ASTHtmlScript script = scripts.iterator().next(); assertEquals("Script!", script.getImage(), "Correct script content expected!"); } /** * Test parsing of HTML &lt;script src="x"/&gt; element. It might not be valid * html but it is likely to appear in .JSP files. */ @Test void testImportHtmlScript() { List<ASTHtmlScript> scripts = jsp.getNodes(ASTHtmlScript.class, TEST_IMPORT_JAVASCRIPT); assertEquals(1, scripts.size(), "One script expected!"); ASTHtmlScript script = scripts.iterator().next(); List<ASTAttributeValue> value = script.findDescendantsOfType(ASTAttributeValue.class); assertEquals("filename.js", value.get(0).getImage()); } /** * Test parsing of HTML &lt;script&gt; element. */ @Test void testHtmlScriptWithAttribute() { List<ASTHtmlScript> scripts = jsp.getNodes(ASTHtmlScript.class, TEST_HTML_SCRIPT_WITH_ATTRIBUTE); assertEquals(1, scripts.size(), "One script expected!"); ASTHtmlScript script = scripts.iterator().next(); assertEquals("Script!", script.getImage(), "Correct script content expected!"); List<ASTAttributeValue> attrs = script.findDescendantsOfType(ASTAttributeValue.class); assertEquals("text/javascript", attrs.get(0).getImage()); } /** * A complex script containing HTML comments, escapes, quotes, etc. */ @Test void testComplexHtmlScript() { List<ASTHtmlScript> script = jsp.getNodes(ASTHtmlScript.class, TEST_COMPLEX_SCRIPT); assertEquals(1, script.size(), "One script expected!"); ASTHtmlScript next = script.iterator().next(); assertThat(next.getImage(), containsString("<!--")); List<ASTCommentTag> comments = jsp.getNodes(ASTCommentTag.class, TEST_COMPLEX_SCRIPT); assertEquals(1, comments.size(), "One comment expected!"); } /** * Test parsing of HTML &lt;script&gt; element. */ @Test void testInlineCss() { List<ASTElement> scripts = jsp.getNodes(ASTElement.class, TEST_INLINE_STYLE); assertEquals(3, scripts.size(), "Three elements expected!"); } /** * Test parsing of HTML text within element. */ @Test void testTextInTag() { List<ASTText> scripts = jsp.getNodes(ASTText.class, TEST_TEXT_IN_TAG); assertEquals(1, scripts.size(), "One text chunk expected!"); ASTText script = scripts.iterator().next(); assertEquals(" some text ", script.getImage(), "Correct content expected!"); } /** * Test parsing of HTML with no spaces between tags. Parser is likely in * this scenario. */ @Test void noSpacesBetweenTags() { List<ASTElement> elmts = jsp.getNodes(ASTElement.class, TEST_TAGS_NO_SPACE); assertEquals(2, elmts.size(), "Two tags expected!"); assertEquals("a", elmts.get(0).getName(), "Correct content expected!"); assertEquals("b", elmts.get(1).getName(), "Correct content expected!"); } /** * the $ sign might trick the parser into thinking an EL is next. He should * be able to treat it as plain text */ @Test void unclosedTagsWithDollar() { List<ASTText> scripts = jsp.getNodes(ASTText.class, TEST_TAGS_WITH_DOLLAR); assertEquals(2, scripts.size(), "Two text chunks expected!"); ASTText script = scripts.iterator().next(); assertEquals(" $ ", script.getImage(), "Correct content expected!"); } /** * Make sure EL expressions aren't treated as plain text when they are * around unclosed tags. */ @Test void unclosedTagsWithELWithin() { List<ASTElExpression> scripts = jsp.getNodes(ASTElExpression.class, TEST_TAGS_WITH_EL_WITHIN); assertEquals(2, scripts.size(), "Two EL expressions expected!"); assertEquals("expr1", scripts.get(0).getImage(), "Correct content expected!"); assertEquals("expr2", scripts.get(1).getImage(), "Correct content expected!"); } /** * Make sure mixed expressions don't confuse the parser */ @Test void mixedExpressions() { List<ASTJspExpression> exprs = jsp.getNodes(ASTJspExpression.class, TEST_TAGS_WITH_MIXED_EXPRESSIONS); assertEquals(1, exprs.size(), "One JSP expression expected!"); assertEquals("expr", exprs.iterator().next().getImage(), "Image of expression should be \"expr\""); List<ASTElExpression> els = jsp.getNodes(ASTElExpression.class, TEST_TAGS_WITH_MIXED_EXPRESSIONS); assertEquals(2, els.size(), "Two EL expression expected!"); assertEquals("expr", els.iterator().next().getImage(), "Image of el should be \"expr\""); List<ASTUnparsedText> unparsedtexts = jsp.getNodes(ASTUnparsedText.class, TEST_TAGS_WITH_MIXED_EXPRESSIONS); assertEquals(2, unparsedtexts.size(), "Two unparsed texts expected!"); assertEquals(" aaa ", unparsedtexts.get(0).getImage(), "Image of text should be \" aaa \""); assertEquals(" \\${expr} ", unparsedtexts.get(1).getImage(), "Image of text should be \"\\${expr}\""); // ASTText should contain the text between two tags. List<ASTText> texts = jsp.getNodes(ASTText.class, TEST_TAGS_WITH_MIXED_EXPRESSIONS); assertEquals(2, texts.size(), "Two regular texts expected!"); assertEquals(" \\${expr} ", texts.get(1).getImage(), "Image of text should be \"\\${expr}\""); assertEquals(" aaa ${expr}#{expr}", texts.get(0).getImage(), "Image of text should be all text between two nodes" + " \" aaa ${expr}#{expr} \""); } /** * Make sure JSP expressions are properly detected when they are next to * unclosed tags. */ @Test void unclosedTagsWithJspExpressionWithin() { List<ASTJspExpression> scripts = jsp.getNodes(ASTJspExpression.class, TEST_TAGS_WITH_EXPRESSION_WITHIN); assertEquals(2, scripts.size(), "Two JSP expressions expected!"); ASTJspExpression script = scripts.iterator().next(); assertEquals("expr", script.getImage(), "Correct content expected!"); } /** * A dangling unopened ( just &lt;/closed&gt; ) tag should not influence the * parsing. */ @Test @Disabled // sadly the number of // <opening> tags has to be >= then the number of </closing> tags void textBetweenUnopenedTag() { List<ASTText> scripts = jsp.getNodes(ASTText.class, TEST_TEXT_WITH_UNOPENED_TAG); assertEquals(2, scripts.size(), "Two text chunks expected!"); ASTText script = scripts.iterator().next(); assertEquals("$", script.getImage(), "Correct content expected!"); } /** * Parser should be able to handle documents which start or end with * unparsed text */ @Test @Disabled // sadly the number of // <opening> tags has to be >= then the number of </closing> tags void textMultipleClosingTags() { List<ASTText> scripts = jsp.getNodes(ASTText.class, TEST_MULTIPLE_CLOSING_TAGS); assertEquals(4, scripts.size(), "Four text chunks expected!"); ASTText script = scripts.iterator().next(); assertEquals(" some text ", script.getImage(), "Correct content expected!"); } /** * Test parsing of HTML &lt;script&gt; element. */ @Test void textAfterOpenAndClosedTag() { List<ASTElement> nodes = jsp.getNodes(ASTElement.class, TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG); assertEquals(2, nodes.size(), "Two elements expected!"); assertEquals("a", nodes.get(0).getName(), "First element should be a"); assertFalse(nodes.get(0).isUnclosed(), "first element should be closed"); assertEquals("b", nodes.get(1).getName(), "Second element should be b"); assertTrue(nodes.get(1).isUnclosed(), "Second element should not be closed"); List<ASTText> text = jsp.getNodes(ASTText.class, TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG); assertEquals(2, text.size(), "Two text chunks expected!"); } @Test void quoteEL() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_QUOTE_EL); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("${something}", attr.getImage(), "Expected to detect proper value for attribute!"); } @Test void quoteExpression() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_QUOTE_EXPRESSION); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<%=something%>", attr.getImage(), "Expected to detect proper value for attribute!"); } @Test @Disabled // tags contain quotes and break attribute parsing void quoteTagInAttribute() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_QUOTE_TAG_IN_ATTR); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<bean:write name=\"x\" property=\"z\">", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * smoke test for a non-quoted attribute value */ @Test void noQuoteAttrValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("yes|", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * tests whether JSP el is properly detected as attribute value */ @Test void noQuoteAttrWithJspEL() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_EL); assertEquals(2, attributes.size(), "two attributes expected!"); Iterator<ASTAttributeValue> iterator = attributes.iterator(); ASTAttributeValue attr2 = iterator.next(); if ("url".equals(attr2.getImage())) { // we have to employ this nasty work-around // in order to ensure that we check the proper attribute attr2 = iterator.next(); } assertEquals("${something}", attr2.getImage(), "Expected to detect proper value for EL in attribute!"); } /** * tests whether parse correctly detects presence of JSP expression &lt;%= %&gt; * within an non-quoted attribute value */ @Test void noQuoteAttrWithJspExpression() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_EXPRESSION); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<%=something%>", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * tests whether parse correctly interprets empty non quote attribute */ @Test void noQuoteAttrEmpty() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_EMPTY_ATTR); assertEquals(2, attributes.size(), "two attributes expected!"); Iterator<ASTAttributeValue> iterator = attributes.iterator(); ASTAttributeValue attr = iterator.next(); if ("http://someHost:/some_URL".equals(attr.getImage())) { // we have to employ this nasty work-around // in order to ensure that we check the proper attribute attr = iterator.next(); } assertEquals("", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * tests whether parse correctly interprets an cr lf instead of an attribute */ @Test void noQuoteAttrCrLf() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_CR_LF_ATTR); assertEquals(2, attributes.size(), "One attribute expected!"); Iterator<ASTAttributeValue> iterator = attributes.iterator(); ASTAttributeValue attr = iterator.next(); if ("http://someHost:/some_URL".equals(attr.getImage())) { // we have to employ this nasty work-around // in order to ensure that we check the proper attribute attr = iterator.next(); } assertEquals("\n", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * tests whether parse correctly interprets an tab instead of an attribute */ @Test void noQuoteAttrTab() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_TAB_ATTR); assertEquals(1, attributes.size(), "One attribute expected!"); Iterator<ASTAttributeValue> iterator = attributes.iterator(); ASTAttributeValue attr = iterator.next(); assertEquals("\t", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * tests whether parse does not fail in the presence of unclosed JSP * expression &lt;%= within an non-quoted attribute value */ @Test void noQuoteAttrWithMalformedJspExpression() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_MALFORMED_EXPR); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<%=something", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * test a no quote attribute value which contains a scriptlet &lt;% %&gt; within * its value */ @Test @Disabled // nice test for future development void noQuoteAttrWithScriptletInValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_SCRIPTLET); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<% String a = \"1\";%>", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * test a no quote attribute value can contain a tag (e.g. * attr=&lt;bean:write property="value" /&gt;) * */ @Test @Disabled // nice test for future development void noQuoteAttrWithBeanWriteTagAsValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_TAG_IN_ATTR); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<% String a = \"1\";%>", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * test a quote attribute value can contain a tag (e.g. * attr="&lt;bean:write property="value" /&gt;" ) Not sure if it's legal JSP code * but most JSP engine accept and properly treat this value at runtime */ @Test @Disabled // nice test for future development void quoteAttrWithBeanWriteTagAsValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_TAG_IN_ATTR); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("<% String a = \"1\";%>", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * test a no quote attribute value which contains the EL dollar sign $ * within its value */ @Test @Disabled // nice test for future development void noQuoteAttrWithDollarSignInValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_DOLLAR); assertEquals(2, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("${something", attr.getImage(), "Expected to detect proper value for attribute!"); } /** * test a no quote attribute value which contains the EL sharp sign # within * its value */ @Test @Disabled // nice test for future development void noQuoteAttrWithSharpSymbolInValue() { List<ASTAttributeValue> attributes = jsp.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_HASH); assertEquals(1, attributes.size(), "One attribute expected!"); ASTAttributeValue attr = attributes.iterator().next(); assertEquals("#{something", attr.getImage(), "Expected to detect proper value for attribute!"); } @Test void unclosedTag() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_SIMPLE); assertEquals(2, elements.size(), "2 tags expected"); assertEquals("tag:someTag", elements.get(0).getName(), "First element should be tag:someTag"); assertEquals("tag:if", elements.get(1).getName(), "Second element should be sorted tag:if"); assertFalse(elements.get(0).isEmpty()); assertFalse(elements.get(0).isUnclosed()); assertTrue(elements.get(1).isEmpty()); assertTrue(elements.get(1).isUnclosed()); } @Test void unclosedTagAndNoQuotesForAttribute() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_NO_QUOTE_ATTR); assertEquals(2, elements.size(), "2 tags expected"); ASTElement ifTag = elements.get(1); ASTElement someTag = elements.get(0); assertEquals("tag:if", ifTag.getName()); assertEquals("tag:someTag", someTag.getName()); assertTrue(ifTag.isEmpty()); assertTrue(ifTag.isUnclosed()); assertFalse(someTag.isEmpty()); assertFalse(someTag.isUnclosed()); } @Test void unclosedTagMultipleLevels() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_MULTIPLE_LEVELS); assertEquals(3, elements.size(), "3 tags expected"); ASTElement xtag = elements.get(0); ASTElement outerTag = elements.get(1); ASTElement innerTag = elements.get(2); assertEquals("tag:someTag", innerTag.getName()); assertEquals("tag:someTag", outerTag.getName()); assertEquals("tag:x", xtag.getName()); assertFalse(innerTag.isEmpty()); assertFalse(innerTag.isUnclosed()); assertTrue(outerTag.isEmpty()); assertTrue(outerTag.isUnclosed()); assertFalse(xtag.isEmpty()); assertFalse(xtag.isUnclosed()); } /** * &lt;html&gt; &lt;a1&gt; &lt;a2/&gt; &lt;b/&gt; &lt;/a1&gt; &lt;/html&gt; */ @Test void nestedEmptyTags() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_MULTIPLE_EMPTY_TAGS); assertEquals(4, elements.size(), "4 tags expected"); ASTElement a1Tag = elements.get(1); ASTElement a2Tag = elements.get(2); ASTElement bTag = elements.get(3); ASTElement htmlTag = elements.get(0); assertEquals("a1", a1Tag.getName()); assertEquals("a2", a2Tag.getName()); assertEquals("b", bTag.getName()); assertEquals("html", htmlTag.getName()); // a1 assertFalse(a1Tag.isEmpty()); assertFalse(a1Tag.isUnclosed()); // a2 assertTrue(a2Tag.isEmpty()); assertFalse(a2Tag.isUnclosed()); // b assertTrue(bTag.isEmpty()); assertFalse(bTag.isUnclosed()); // html assertFalse(htmlTag.isEmpty()); assertFalse(htmlTag.isUnclosed()); } /** * &lt;html&gt; &lt;a1&gt; &lt;a2&gt; &lt;a3&gt; &lt;/a2&gt; &lt;/a1&gt; &lt;b/&gt; &lt;a4/&gt; &lt;/html&gt; */ @Test void nestedMultipleTags() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_MULTIPLE_NESTED_TAGS); ASTElement html = elements.get(0); ASTElement a1 = elements.get(1); ASTElement a2 = elements.get(2); ASTElement a3 = elements.get(3); ASTElement b = elements.get(4); ASTElement a4 = elements.get(5); assertEquals(6, elements.size(), "6 tags expected"); assertEquals("a1", a1.getName()); assertEquals("a2", a2.getName()); assertEquals("a3", a3.getName()); assertEquals("a4", a4.getName()); assertEquals("b", b.getName()); assertEquals("html", html.getName()); // a1 not empty and closed assertFalse(a1.isEmpty()); assertFalse(a1.isUnclosed()); // a2 not empty and closed assertFalse(a2.isEmpty()); assertFalse(a2.isUnclosed()); // a3 empty and not closed assertTrue(a3.isEmpty()); assertTrue(a3.isUnclosed()); // a4 empty but closed assertTrue(a4.isEmpty()); assertFalse(a4.isUnclosed()); // b empty but closed assertTrue(b.isEmpty()); assertFalse(b.isUnclosed()); // html not empty and closed assertFalse(html.isEmpty()); assertFalse(html.isUnclosed()); } /** * will test &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/x&gt; &lt;/a&gt; &lt;/x&gt; . * Here x is the first tag to be closed thus rendering the next close of a (&lt;/a&gt;) * to be disregarded. */ @Test void unclosedParentTagClosedBeforeChild() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_END_AFTER_PARENT_CLOSE); assertEquals(4, elements.size(), "4 tags expected"); ASTElement x = elements.get(0); ASTElement a = elements.get(1); ASTElement b = elements.get(2); ASTElement b2 = elements.get(3); assertEquals("a", a.getName()); assertEquals("b", b.getName()); assertEquals("b", b2.getName()); assertEquals("x", x.getName()); // a assertTrue(a.isEmpty()); assertTrue(a.isUnclosed()); // b assertTrue(b.isEmpty()); assertTrue(b.isUnclosed()); // b assertTrue(b2.isEmpty()); assertTrue(b2.isUnclosed()); // x assertFalse(x.isEmpty()); assertFalse(x.isUnclosed()); } /** * &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/z&gt; &lt;/a&gt; &lt;/x&gt; An unmatched closing of 'z' appears * randomly in the document. This should be disregarded and structure of * children and parents should not be influenced. in other words &lt;/a&gt; should * close the first &lt;a&gt; tag , &lt;/x&gt; should close the first &lt;x&gt;, etc. */ @Test void unmatchedTagDoesNotInfluenceStructure() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_UNMATCHED_CLOSING_TAG); assertEquals(4, elements.size(), "4 tags expected"); ASTElement x = elements.get(0); ASTElement a = elements.get(1); ASTElement b1 = elements.get(2); ASTElement b2 = elements.get(3); assertEquals("a", a.getName()); assertEquals("b", b1.getName()); assertEquals("b", b2.getName()); assertEquals("x", x.getName()); // a is not empty and closed assertFalse(a.isEmpty()); assertFalse(a.isUnclosed()); // b empty and unclosed assertTrue(b1.isEmpty()); assertTrue(b1.isUnclosed()); // b empty and unclosed assertTrue(b2.isEmpty()); assertTrue(b2.isUnclosed()); // x not empty and closed assertFalse(x.isEmpty()); assertFalse(x.isUnclosed()); } /** * &lt;a&gt; &lt;x&gt; &lt;a&gt; &lt;b&gt; &lt;b&gt; &lt;/z&gt; &lt;/a&gt; &lt;/x&gt; * An unmatched closing of 'z' appears randomly in the document. This * should be disregarded and structure of children and parents should not be influenced. * Also un unclosed &lt;a&gt; tag appears at the start of the document */ @Test void unclosedStartTagWithUnmatchedCloseOfDifferentTag() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_START_TAG_WITH_UNMATCHED_CLOSE); assertEquals(5, elements.size(), "5 tags expected"); ASTElement a1 = elements.get(0); ASTElement x = elements.get(1); ASTElement a2 = elements.get(2); ASTElement b1 = elements.get(3); ASTElement b2 = elements.get(4); assertEquals("a", a1.getName()); assertEquals("a", a2.getName()); assertEquals("b", b1.getName()); assertEquals("b", b2.getName()); assertEquals("x", x.getName()); // first a is empty and unclosed assertTrue(a1.isEmpty()); assertTrue(a1.isUnclosed()); // second a not empty and closed assertFalse(a2.isEmpty()); assertFalse(a2.isUnclosed()); // b empty and unclosed assertTrue(b1.isEmpty()); assertTrue(b1.isUnclosed()); // b empty and unclosed assertTrue(b2.isEmpty()); assertTrue(b2.isUnclosed()); // x not empty and closed assertFalse(x.isEmpty()); assertFalse(x.isUnclosed()); } /** * {@link #TEST_UNCLOSED_END_OF_DOC} * &lt;tag:x&gt; &lt;tag:y&gt; * Tests whether parser breaks on no closed tags at all */ @Test // This is yet to be improved. If a closing tag does not // exist no tags will be marked as empty :( @Disabled void unclosedEndOfDoc() { List<ASTElement> elements = jsp.getNodes(ASTElement.class, TEST_UNCLOSED_END_OF_DOC); assertEquals(2, elements.size(), "2 tags expected"); ASTElement x = elements.get(0); ASTElement y = elements.get(1); assertEquals("tag:x", x.getName()); assertEquals("tag:y", y.getName()); // b // assertTrue(sortedElmnts.get(0).isEmpty()); assertTrue(x.isUnclosed()); // b assertTrue(y.isEmpty()); assertTrue(y.isUnclosed()); } private static final String TEST_SIMPLEST_HTML = "<html/>"; private static final String TEST_ELEMENT_AND_NAMESPACE = "<h:html MyNsPrefix:MyAttr='MyValue'/>"; private static final String TEST_CDATA = "<html><![CDATA[ some <cdata> ]] ]> ]]></html>"; private static final String TEST_DOCTYPE = "<?xml version=\"1.0\" standalone='yes'?>\n" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" " + "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" + "<greeting>Hello, world!</greeting>"; private static final String TEST_COMMENT = "<html><!-- comment --></html>"; private static final String TEST_ATTRIBUTE_VALUE_CONTAINING_HASH = "<tag:if something=\"#yes#\" foo=\"CREATE\"> <a href=\"#\">foo</a> </tag:if>"; private static final String TEST_HTML_SCRIPT = "<html><head><script>Script!</script></head></html>"; private static final String TEST_IMPORT_JAVASCRIPT = "<html><head><script src=\"filename.js\" type=\"text/javascript\"/></head></html>"; private static final String TEST_HTML_SCRIPT_WITH_ATTRIBUTE = "<html><head><script type=\"text/javascript\">Script!</script></head></html>"; private static final String TEST_COMPLEX_SCRIPT = "<HTML><BODY><!--Java Script-->" + "<SCRIPT language='JavaScript' type='text/javascript'>" + "<!--function calcDays(){" + " date1 = date1.split(\"-\"); date2 = date2.split(\"-\");" + " var sDate = new Date(date1[0]+\"/\"+date1[1]+\"/\"+date1[2]);" + " var eDate = new Date(date2[0]+\"/\"+date2[1]+\"/\"+date2[2]);" + " onload=calcDays;//-->" + "</SCRIPT></BODY></HTML>;"; private static final String TEST_INLINE_STYLE = "<html><head><style> div { color:red; } </style></head></html>"; private static final String TEST_TEXT_IN_TAG = "<a> some text </a>"; private static final String TEST_TAGS_NO_SPACE = "<a><b></a>"; private static final String TEST_TAGS_WITH_DOLLAR = "<a> $ <b> $ </a>"; private static final String TEST_TAGS_WITH_EL_WITHIN = "<a>#{expr1}<b>${expr2}</a>"; private static final String TEST_TAGS_WITH_MIXED_EXPRESSIONS = "<a> aaa ${expr} #{expr} <%=expr%> <b> \\${expr} </a>"; private static final String TEST_TAGS_WITH_EXPRESSION_WITHIN = "<a> <%=expr%> <b> <%=expr%> </a>"; private static final String TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG = "<a> some text <b> some text </a>"; private static final String TEST_TEXT_WITH_UNOPENED_TAG = "<a> some text </b> some text </a>"; private static final String TEST_MULTIPLE_CLOSING_TAGS = "<a> some text </b> </b> </b> some text </a>"; private static final String TEST_QUOTE_EL = "<tag:if something=\"${something}\" > </tag:if>"; private static final String TEST_QUOTE_EXPRESSION = "<tag:if something=\"<%=something%>\" > </tag:if>"; private static final String TEST_QUOTE_TAG_IN_ATTR = "<tag:if something=\"<bean:write name=\"x\" property=\"z\">\" > " + "<a href=http://someHost:/some_URL >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_ATTR = "<tag:if something=yes| > </tag:if>"; private static final String TEST_NO_QUOTE_EMPTY_ATTR = "<tag:if something= > <a href=http://someHost:/some_URL >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_TAG_IN_ATTR = "<tag:if something=<bean:write name=\"x\" property=\"z\"> > <a href=http://someHost:/some_URL >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_CR_LF_ATTR = "<tag:if something=\r\n > <a href=http://someHost:/some_URL >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_TAB_ATTR = "<tag:if something=\t > </tag:if>"; private static final String TEST_NO_QUOTE_ATTR_WITH_EL = "<tag:if something=${something} > <a href=url >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_ATTR_WITH_EXPRESSION = "<tag:if something=<%=something%> > </tag:if>"; /** * same as {@link #TEST_NO_QUOTE_ATTR_WITH_EXPRESSION} only expression is * not properly closed */ private static final String TEST_NO_QUOTE_ATTR_WITH_MALFORMED_EXPR = "<tag:if something=<%=something > </tag:if>"; private static final String TEST_NO_QUOTE_ATTR_WITH_SCRIPTLET = "<tag:if something=<% String a = \"1\";%>x > </tag:if>"; private static final String TEST_NO_QUOTE_ATTR_WITH_DOLLAR = "<tag:if something=${something > <a href=${ >foo</a> </tag:if>"; private static final String TEST_NO_QUOTE_ATTR_WITH_HASH = "<tag:if something=#{something > <a href=#{url} >foo</a> </tag:if>"; private static final String TEST_UNCLOSED_SIMPLE = "<tag:someTag> <tag:if something=\"x\" > </tag:someTag>"; /** * someTag is closed just once */ private static final String TEST_UNCLOSED_MULTIPLE_LEVELS = "<tag:x> <tag:someTag> <tag:someTag something=\"x\" > </tag:someTag> </tag:x>"; /** * nested empty tags */ private static final String TEST_MULTIPLE_EMPTY_TAGS = "<html> <a1> <a2/> <b/> </a1> </html>"; /** * multiple nested tags with some tags unclosed */ private static final String TEST_MULTIPLE_NESTED_TAGS = "<html> <a1> <a2> <a3> </a2> </a1> <b/> <a4/> </html>"; /** * </x> will close before </a>, thus leaving <a> to remain unclosed */ private static final String TEST_UNCLOSED_END_AFTER_PARENT_CLOSE = "<x> <a> <b> <b> </x> </a> aa </x> bb </x>"; /** * </z> is just a dangling closing tag not matching any parent. The parser * should disregard it */ private static final String TEST_UNCLOSED_UNMATCHED_CLOSING_TAG = "<x> <a> <b> <b> </z> </a> </x>"; /** * First <a> tag does not close. The first closing of </a> will match the * second opening of a. Another rogue </z> is there for testing compliance */ private static final String TEST_UNCLOSED_START_TAG_WITH_UNMATCHED_CLOSE = "<a> <x> <a> <b> <b> </z> </a> </x>"; private static final String TEST_UNCLOSED_END_OF_DOC = "<tag:x> <tag:y>"; private static final String TEST_UNCLOSED_NO_QUOTE_ATTR = "<tag:someTag> <tag:if something=x > </tag:someTag>"; }
38,078
40.799122
175
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/AbstractJspNodesTst.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public abstract class AbstractJspNodesTst { protected JspParsingHelper jsp = JspParsingHelper.DEFAULT.withResourceContext(getClass()); }
275
22
94
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; class XPathJspRuleTest extends AbstractJspNodesTst { /** * Test matching a XPath expression against a JSP source. */ @Test void testExpressionMatching() { Rule rule = jsp.newXpathRule("//Element [@Name='hr']"); Report report = jsp.executeRule(rule, "<html><hr/></html>"); assertEquals(1, report.getViolations().size(), "One violation expected!"); RuleViolation rv = report.getViolations().get(0); assertEquals(1, rv.getBeginLine()); } }
848
25.53125
82
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/security/NoUnsanitizedJSPExpressionTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.security; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoUnsanitizedJSPExpressionTest extends PmdRuleTst { // no additional unit tests }
288
23.083333
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/security/IframeMissingSrcAttributeTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.security; import net.sourceforge.pmd.testframework.PmdRuleTst; class IframeMissingSrcAttributeTest extends PmdRuleTst { // no additional unit tests }
287
23
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/errorprone/JspEncodingTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.errorprone; import net.sourceforge.pmd.testframework.PmdRuleTst; class JspEncodingTest extends PmdRuleTst { // no additional unit tests }
275
22
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/bestpractices/NoClassAttributeTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.bestpractices; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoClassAttributeTest extends PmdRuleTst { // no additional unit tests }
283
22.666667
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/bestpractices/NoHtmlCommentsTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.bestpractices; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoHtmlCommentsTest extends PmdRuleTst { // no additional unit tests }
281
22.5
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/bestpractices/NoJspForwardTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.bestpractices; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoJspForwardTest extends PmdRuleTst { // no additional unit tests }
279
22.333333
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/bestpractices/DontNestJsfInJstlIterationTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.bestpractices; import net.sourceforge.pmd.testframework.PmdRuleTst; class DontNestJsfInJstlIterationTest extends PmdRuleTst { // no additional unit tests }
293
23.5
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/codestyle/DuplicateJspImportsTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.codestyle; import net.sourceforge.pmd.testframework.PmdRuleTst; class DuplicateJspImportsTest extends PmdRuleTst { // no additional unit tests }
282
22.583333
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/design/NoInlineStyleInformationTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.design; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoInlineStyleInformationTest extends PmdRuleTst { // no additional unit tests }
284
22.75
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/design/NoInlineScriptTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.design; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoInlineScriptTest extends PmdRuleTst { // no additional unit tests }
274
21.916667
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/design/NoScriptletsTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.design; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoScriptletsTest extends PmdRuleTst { // no additional unit tests }
272
21.75
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/rule/design/NoLongScriptsTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.rule.design; import net.sourceforge.pmd.testframework.PmdRuleTst; class NoLongScriptsTest extends PmdRuleTst { // no additional unit tests }
273
21.833333
79
java
pmd
pmd-master/pmd-jsp/src/test/java/net/sourceforge/pmd/cpd/JSPTokenizerTest.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.cpd; import java.util.Properties; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest; class JSPTokenizerTest extends CpdTextComparisonTest { JSPTokenizerTest() { super(".jsp"); } @Override protected String getResourcePrefix() { return "../lang/jsp/cpd/testdata"; } @Override public Tokenizer newTokenizer(Properties properties) { return new JSPTokenizer(); } @Test void scriptletWithString() { doTest("scriptletWithString"); } }
673
18.257143
79
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/JspHandler.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp; import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler; import net.sourceforge.pmd.lang.ast.Parser; import net.sourceforge.pmd.lang.jsp.ast.JspParser; /** * Implementation of LanguageVersionHandler for the JSP parser. * * @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be */ public class JspHandler extends AbstractPmdLanguageVersionHandler { @Override public Parser getParser() { return new JspParser(); } }
595
23.833333
79
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/JspLanguageModule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp; import static net.sourceforge.pmd.util.CollectionUtil.listOf; import java.util.List; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase; /** * Created by christoferdutz on 20.09.14. */ public class JspLanguageModule extends SimpleLanguageModuleBase { public static final String NAME = "Java Server Pages"; public static final String TERSE_NAME = "jsp"; @InternalApi public static final List<String> EXTENSIONS = listOf("jsp", "jspx", "jspf", "tag"); public JspLanguageModule() { super(LanguageMetadata.withId(TERSE_NAME).name(NAME).shortName("JSP") .extensions(EXTENSIONS) .addVersion("2") .addDefaultVersion("3"), new JspHandler()); } }
971
28.454545
87
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/JspParser.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.ast.ParseException; import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior; import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeParserAdapter; /** * JSP language parser. */ public final class JspParser extends JjtreeParserAdapter<ASTCompilationUnit> { private static final TokenDocumentBehavior TOKEN_BEHAVIOR = new TokenDocumentBehavior(JspTokenKinds.TOKEN_NAMES); @Override protected TokenDocumentBehavior tokenBehavior() { return TOKEN_BEHAVIOR; } @Override protected ASTCompilationUnit parseImpl(CharStream cs, ParserTask task) throws ParseException { return new JspParserImpl(cs).CompilationUnit().makeTaskInfo(task); } @InternalApi public static TokenDocumentBehavior getTokenBehavior() { return TOKEN_BEHAVIOR; } }
1,104
30.571429
117
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTElExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTElExpression extends AbstractJspNode { ASTElExpression(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
404
21.5
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/JspVisitorBase.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import net.sourceforge.pmd.lang.ast.AstVisitorBase; public class JspVisitorBase<P, R> extends AstVisitorBase<P, R> implements JspVisitor<P, R> { }
280
22.416667
92
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTValueBinding.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTValueBinding extends AbstractJspNode { ASTValueBinding(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
404
21.5
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTDeclaration extends AbstractJspNode { private String name; ASTDeclaration(int id) { super(id); } public String getName() { return name; } void setName(String name) { this.name = name; } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
551
18.714286
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTContent.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTContent extends AbstractJspNode { ASTContent(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
394
20.944444
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/JspParserVisitorAdapter.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.ast.Node; /** * Backwards-compatibility only. * * @deprecated Use {@link JspVisitorBase} */ @Deprecated @DeprecatedUntil700 public class JspParserVisitorAdapter extends JspVisitorBase<Object, Object> implements JspParserVisitor { @Override protected Object visitChildren(Node node, Object data) { super.visitChildren(node, data); return data; } }
604
21.407407
105
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTJspDeclaration extends AbstractJspNode { ASTJspDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
407
23
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/JspNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.ast.AstVisitor; import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeNode; public interface JspNode extends JjtreeNode<JspNode> { /** * @deprecated Use {@link #acceptVisitor(AstVisitor, Object)} */ @Deprecated @DeprecatedUntil700 default Object jjtAccept(JspParserVisitor visitor, Object data) { return acceptVisitor(visitor, data); } }
600
25.130435
79
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspExpressionInAttribute.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTJspExpressionInAttribute extends AbstractJspNode { ASTJspExpressionInAttribute(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
428
22.833333
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/OpenTagRegister.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.annotation.InternalApi; /** * Utility class to keep track of unclosed tags. The mechanism is rather simple. * If a end tag (&lt;/x&gt;) is encountered, it will iterate through the open * tag list and it will mark the first tag named 'x' as closed. If other tags * have been opened after 'x' ( &lt;x&gt; &lt;y&gt; &lt;z&gt; &lt;/x&gt;) it * will mark y and z as unclosed. * * @author Victor Bucutea * */ @InternalApi class OpenTagRegister { private List<ASTElement> tagList = new ArrayList<>(); public void openTag(ASTElement elm) { if (elm == null || StringUtils.isBlank(elm.getName())) { throw new IllegalStateException("Tried to open a tag with empty name"); } tagList.add(elm); } /** * * @param closingTagName * @return true if a matching tag was found. False if no tag with this name * was ever opened ( or registered ) */ public boolean closeTag(String closingTagName) { if (StringUtils.isBlank(closingTagName)) { throw new IllegalStateException("Tried to close a tag with empty name"); } int lastRegisteredTagIdx = tagList.size() - 1; /* * iterate from top to bottom and look for the last tag with the same * name as element */ boolean matchingTagFound = false; List<ASTElement> processedElements = new ArrayList<>(); for (int i = lastRegisteredTagIdx; i >= 0; i--) { ASTElement parent = tagList.get(i); String parentName = parent.getName(); processedElements.add(parent); if (parentName.equals(closingTagName)) { // mark this tag as being closed parent.setUnclosed(false); // tag has children it cannot be empty parent.setEmpty(false); matchingTagFound = true; break; } else { // only mark as unclosed if tag is not // empty (e.g. <tag/> is empty and properly closed) if (!parent.isEmpty()) { parent.setUnclosed(true); } parent.setEmpty(true); } } /* * remove all processed tags. We should look for rogue tags which have * no start (unopened tags) e.g. " <a> <b> <b> </z> </a>" if "</z>" has * no open tag in the list (and in the whole document) we will consider * </a> as the closing tag for <a>.If on the other hand tags are * interleaved: <x> <a> <b> <b> </x> </a> then we will consider </x> the * closing tag of <x> and </a> a rogue tag or the closing tag of a * potentially open <a> parent tag ( but not the one after the <x> ) */ if (matchingTagFound) { tagList.removeAll(processedElements); } return matchingTagFound; } public void closeTag(ASTElement z) { closeTag(z.getName()); } }
3,270
32.377551
84
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTDoctypeDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTDoctypeDeclaration extends AbstractJspNode { /** * Name of the document type. Cannot be null. */ private String name; ASTDoctypeDeclaration(int id) { super(id); } public String getName() { return name; } void setName(String name) { this.name = name; } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
631
19.387097
90
java
pmd
pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTText.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.jsp.ast; public final class ASTText extends AbstractJspNode { ASTText(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
388
20.611111
90
java