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-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/internal/AbstractCounterCheckRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.apex.rule.internal;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.apex.ast.ASTApexFile;
import net.sourceforge.pmd.lang.apex.ast.ASTUserClass;
import net.sourceforge.pmd.lang.apex.ast.ApexNode;
import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
import net.sourceforge.pmd.lang.rule.internal.CommonPropertyDescriptors;
import net.sourceforge.pmd.properties.PropertyDescriptor;
/**
* Abstract class for rules counting some integer metric on some node.
*
* @author Clément Fournier
* @since 7.0.0
*/
public abstract class AbstractCounterCheckRule<T extends ApexNode<?>> extends AbstractApexRule {
private final PropertyDescriptor<Integer> reportLevel =
CommonPropertyDescriptors.reportLevelProperty()
.desc("Threshold above which a node is reported")
.require(positive())
.defaultValue(defaultReportLevel()).build();
private final Class<T> nodeType;
public AbstractCounterCheckRule(Class<T> nodeType) {
this.nodeType = nodeType;
definePropertyDescriptor(reportLevel);
}
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forTypes(nodeType);
}
protected abstract int defaultReportLevel();
protected Object[] getViolationParameters(T node, int metric, int limit) {
return new Object[] {metric, limit};
}
protected abstract int getMetric(T node);
/** Return true if the node should be ignored. */
protected boolean isIgnored(T node) {
return false;
}
@Override
public Object visit(ApexNode<?> node, Object data) {
@SuppressWarnings("unchecked")
T t = (T) node;
// since we only visit this node, it's ok
if (!isIgnored(t)) {
int metric = getMetric(t);
int limit = getProperty(reportLevel);
if (metric >= limit) {
addViolation(data, node, getViolationParameters(t, metric, limit));
}
}
return data;
}
public abstract static class AbstractLineLengthCheckRule<T extends ApexNode<?>> extends AbstractCounterCheckRule<T> {
public AbstractLineLengthCheckRule(Class<T> nodeType) {
super(nodeType);
}
@Override
protected int getMetric(T node) {
Node measured = node;
if (node instanceof ASTUserClass && node.getParent() instanceof ASTApexFile) {
measured = node.getParent();
}
return measured.getEndLine() - measured.getBeginLine();
}
}
}
| 3,014 | 28.851485 | 121 | java |
pmd | pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/multifile/ApexMultifileAnalysis.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.apex.multifile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.apex.ApexLanguageProcessor;
import net.sourceforge.pmd.lang.apex.ApexLanguageProperties;
import com.nawforce.apexlink.api.Org;
import com.nawforce.pkgforce.api.Issue;
import com.nawforce.pkgforce.diagnostics.LoggerOps;
/**
* Stores multi-file analysis data. The 'Org' here is the primary ApexLink structure for maintaining information
* about the Salesforce metadata. We load 'Packages' into it to perform analysis. Once constructed you
* can get 'Issue' information from it on what was found. The 'Org' holds mutable state for IDE use that can get quite
* large (a few hundred MB on very large projects). An alternative way to use this would be to cache the
* issues after packages are loaded and throw away the 'Org'. That would be a better model if all you wanted was the
* issues but more complex rules will need the ability to traverse the internal graph of the 'Org'.
*
* @author Kevin Jones
*/
@Experimental
public final class ApexMultifileAnalysis {
// test only
static final Logger LOG = LoggerFactory.getLogger(ApexMultifileAnalysis.class);
// Create a new org for each analysis
// Null if failed.
private final @Nullable Org org;
static {
// Setup logging
LoggerOps.setLogger(new AnalysisLogger());
// TODO: Provide means to control logging
LoggerOps.setLoggingLevel(LoggerOps.NO_LOGGING());
}
@InternalApi
public ApexMultifileAnalysis(ApexLanguageProperties properties) {
String rootDir = properties.getProperty(ApexLanguageProperties.MULTIFILE_DIRECTORY);
LOG.debug("MultiFile Analysis created for {}", rootDir);
Org org = null;
try {
// Load the package into the org, this can take some time!
if (rootDir != null && !rootDir.isEmpty()) {
Path projectPath = Paths.get(rootDir);
Path sfdxProjectJson = projectPath.resolve("sfdx-project.json");
// Limit analysis to SFDX Projects
// MDAPI analysis is currently supported but is expected to be deprecated soon
if (Files.isDirectory(projectPath) && Files.isRegularFile(sfdxProjectJson)) {
org = Org.newOrg(rootDir);
// FIXME: Syntax & Semantic errors found during Org loading are not currently being reported. These
// should be routed to the new SemanticErrorReporter but that is not available for use just yet.
// Specifically we should check sfdx-project.json was ok as errors will disable further analysis
Issue[] projectErrors =
Arrays.stream(org.issues().issuesForFile(sfdxProjectJson.toString()))
.filter(Issue::isError).toArray(Issue[]::new);
Arrays.stream(projectErrors).forEach(issue -> LOG.info(issue.toString()));
if (projectErrors.length != 0) {
org = null;
}
} else {
LOG.info("Missing project file at {}", sfdxProjectJson);
}
}
} catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {
// Note: Org.newOrg() will try to find the base Apex Types through the current classloader
// in package "com.nawforce.runforce". This requires, that directory listings can be retrievied
// on the URL that the classloader returns from getResource("/com/nawforce/runforce"):
// https://github.com/nawforce/apex-link/blob/7688adcb7a2d7f8aa28d0618ffb2a3aa81151858/apexlink/src/main/scala/com/nawforce/apexlink/types/platform/PlatformTypeDeclaration.scala#L260-L273
// However, when running as an Eclipse plugin, we have a special bundle classloader, that returns
// URIs in the form "bundleresource://...". For the schema "bundleresource", no FileSystemProvider can be
// found, so we get a java.nio.file.ProviderNotFoundException. Since all this happens during initialization of the class
// com.nawforce.apexlink.types.platform.PlatformTypeDeclaration we get a ExceptionInInitializerError
// and later NoClassDefFoundErrors, because PlatformTypeDeclaration couldn't be loaded.
LOG.error("Exception while initializing Apexlink ({})", e.getMessage(), e);
LOG.error("PMD will not attempt to initialize Apexlink further, this can cause rules like UnusedMethod to be dysfunctional");
}
this.org = org;
}
/**
* Returns true if this is analysis index is in a failed state.
* This object is then useless. The failed instance is returned
* from {@link ApexLanguageProcessor#getMultiFileState()} if
* loading the org failed, maybe because of malformed configuration.
*/
public boolean isFailed() {
return org == null;
}
public List<Issue> getFileIssues(String filename) {
// Extract issues for a specific metadata file from the org
return org == null ? Collections.emptyList()
: Collections.unmodifiableList(Arrays.asList(org.issues().issuesForFile(filename)));
}
/*
* Very simple logger to aid debugging, relays ApexLink logging into PMD
*/
private static final class AnalysisLogger implements com.nawforce.pkgforce.diagnostics.Logger {
@Override
public void info(String message) {
LOG.info(message);
}
@Override
public void debug(String message) {
LOG.debug(message);
}
@Override
public void trace(String message) {
LOG.trace(message);
}
}
}
| 6,293 | 44.280576 | 199 | java |
pmd | pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/internal/ApexDesignerBindings.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.apex.internal;
import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.apex.ast.ASTMethod;
import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTUserClass;
import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration;
import net.sourceforge.pmd.lang.apex.ast.ApexNode;
import net.sourceforge.pmd.lang.apex.ast.ApexParserVisitorAdapter;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.util.designerbindings.DesignerBindings.DefaultDesignerBindings;
public class ApexDesignerBindings extends DefaultDesignerBindings {
public static final ApexDesignerBindings INSTANCE = new ApexDesignerBindings();
@Override
public Attribute getMainAttribute(Node node) {
if (node instanceof ApexNode) {
Attribute attr = (Attribute) ((ApexNode<?>) node).jjtAccept(MainAttrVisitor.INSTANCE, null);
if (attr != null) {
return attr;
}
}
return super.getMainAttribute(node);
}
@Override
public TreeIconId getIcon(Node node) {
if (node instanceof ASTFieldDeclaration) {
return TreeIconId.FIELD;
} else if (node instanceof ASTUserClass) {
return TreeIconId.CLASS;
} else if (node instanceof ASTMethod) {
return TreeIconId.METHOD;
} else if (node instanceof ASTVariableDeclaration) {
return TreeIconId.VARIABLE;
}
return super.getIcon(node);
}
private static final class MainAttrVisitor extends ApexParserVisitorAdapter {
private static final MainAttrVisitor INSTANCE = new MainAttrVisitor();
@Override
public Object visit(ApexNode<?> node, Object data) {
return null; // don't recurse
}
@Override
public Object visit(ASTMethodCallExpression node, Object data) {
return new Attribute(node, "MethodName", node.getMethodName());
}
}
}
| 2,200 | 32.861538 | 104 | java |
pmd | pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
public class ApexLanguage extends AbstractLanguage {
public ApexLanguage() {
this(new Properties());
}
public ApexLanguage(Properties properties) {
super(ApexLanguageModule.NAME, ApexLanguageModule.TERSE_NAME, new ApexTokenizer(), ApexLanguageModule.EXTENSIONS);
setProperties(properties);
}
@Override
public final void setProperties(Properties properties) {
ApexTokenizer tokenizer = (ApexTokenizer) getTokenizer();
tokenizer.setProperties(properties);
}
}
| 740 | 25.464286 | 122 | java |
pmd | pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Locale;
import java.util.Properties;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.Lexer;
import org.antlr.runtime.Token;
import net.sourceforge.pmd.lang.apex.ApexJorjeLogging;
import net.sourceforge.pmd.lang.ast.TokenMgrError;
import net.sourceforge.pmd.lang.document.FileId;
import apex.jorje.parser.impl.ApexLexer;
public class ApexTokenizer implements Tokenizer {
public ApexTokenizer() {
ApexJorjeLogging.disableLogging();
}
/**
* If the properties is <code>false</code> (default), then the case of any token
* is ignored.
*/
public static final String CASE_SENSITIVE = "net.sourceforge.pmd.cpd.ApexTokenizer.caseSensitive";
private boolean caseSensitive;
public void setProperties(Properties properties) {
caseSensitive = Boolean.parseBoolean(properties.getProperty(CASE_SENSITIVE, "false"));
}
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) {
StringBuilder code = sourceCode.getCodeBuffer();
ANTLRStringStream ass = new ANTLRStringStream(code.toString());
ApexLexer lexer = new ApexLexer(ass) {
@Override
public void emitErrorMessage(String msg) {
throw new TokenMgrError(getLine(), getCharPositionInLine(), FileId.fromPathLikeString(getSourceName()), msg, null);
}
};
try {
Token token = lexer.nextToken();
while (token.getType() != Token.EOF) {
if (token.getChannel() != Lexer.HIDDEN) {
String tokenText = token.getText();
if (!caseSensitive) {
tokenText = tokenText.toLowerCase(Locale.ROOT);
}
TokenEntry tokenEntry = new TokenEntry(tokenText, sourceCode.getFileName(),
token.getLine(),
token.getCharPositionInLine() + 1,
token.getCharPositionInLine() + tokenText.length() + 1);
tokenEntries.add(tokenEntry);
}
token = lexer.nextToken();
}
} finally {
tokenEntries.add(TokenEntry.getEOF());
}
}
}
| 2,486 | 33.541667 | 131 | java |
pmd | pmd-master/pmd-fortran/src/test/java/net/sourceforge/pmd/cpd/FortranTokenizerTest.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;
/**
* @author rpelisse
*
*/
class FortranTokenizerTest extends CpdTextComparisonTest {
FortranTokenizerTest() {
super(".for");
}
@Override
protected String getResourcePrefix() {
return "../lang/fortran/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new FortranLanguage().getTokenizer();
}
@Test
void testSample() {
doTest("sample");
}
}
| 711 | 17.736842 | 79 | java |
pmd | pmd-master/pmd-fortran/src/main/java/net/sourceforge/pmd/cpd/FortranLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* Language implementation for Fortran
*
* @author Romain PELISSE belaran@gmail.com
*/
public class FortranLanguage extends AbstractLanguage {
/**
* Create a Fortran Language instance.
*/
public FortranLanguage() {
super("Fortran", "fortran", new AnyTokenizer("!"), ".for", ".f", ".f66", ".f77", ".f90");
}
}
| 469 | 22.5 | 97 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/RuleSetFactoryTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
/**
* Test velocity's rulesets.
*/
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
// no additional tests yet
}
| 314 | 20 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/LanguageVersionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm;
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(VmLanguageModule.NAME, VmLanguageModule.TERSE_NAME, "2.3",
getLanguage(VmLanguageModule.NAME).getDefaultVersion()));
}
}
| 535 | 27.210526 | 106 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/VmParserTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.vm.ast.VmParsingHelper;
/**
* Unit test for VM parsing.
*/
class VmParserTest {
private static final String VM_SRC = "<HTML><BODY>Hello $customer.Name <table> "
+ "#foreach($mud in $mudsOnSpecial)" + " #if ( $customer.hasPurchased($mud) )" + " <tr>" + " <td>"
+ " $flogger.getPromo( $mud )" + " </td>" + " </tr>" + " #elseif ($customer.broke) do stuff #end"
+ "\n " + "#end " + "</table>";
private static final String SRC2 = "#macro(tablerows $color $values ) " + "#foreach( $value in $values ) "
+ "<tr><td bgcolor=$color>$value</td></tr> " + "#end " + "#end "
+ "#set( $greatlakes = [\"Superior\",\"Michigan\",\"Huron\",\"Erie\",\"Ontario\"] ) "
+ "#set( $color = \"blue\" ) " + "<table> " + " #tablerows( $color $greatlakes ) " + "</table>";
private static final String SRC3 = "#if ( $c1 ) #if ( $c2)#end #end";
// private static final String VM_SRC = "#if( $mud == 1 ) blah #if ($dirt ==
// 2) stuff #end #end";
@Test
void testParser() {
VmParsingHelper.DEFAULT.parse(VM_SRC);
}
@Test
void testParser2() {
VmParsingHelper.DEFAULT.parse(SRC2);
}
@Test
void testParser3() {
VmParsingHelper.DEFAULT.parse(SRC3);
}
}
| 1,470 | 30.297872 | 116 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/ast/VmParsingHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.vm.VmLanguageModule;
public final class VmParsingHelper extends BaseParsingHelper<VmParsingHelper, ASTTemplate> {
public static final VmParsingHelper DEFAULT = new VmParsingHelper(Params.getDefault());
private VmParsingHelper(Params params) {
super(VmLanguageModule.NAME, ASTTemplate.class, params);
}
@Override
protected VmParsingHelper clone(Params params) {
return new VmParsingHelper(params);
}
}
| 667 | 28.043478 | 92 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/errorprone/EmptyIfStmtTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class EmptyIfStmtTest extends PmdRuleTst {
// no additional unit tests
}
| 273 | 21.833333 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/errorprone/EmptyForeachStmtTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class EmptyForeachStmtTest extends PmdRuleTst {
// no additional unit tests
}
| 278 | 22.25 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/bestpractices/UnusedMacroParameterTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UnusedMacroParameterTest extends PmdRuleTst {
// no additional unit tests
}
| 285 | 22.833333 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/bestpractices/AvoidReassigningParametersTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidReassigningParametersTest extends PmdRuleTst {
// no additional unit tests
}
| 291 | 23.333333 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/design/ExcessiveTemplateLengthTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveTemplateLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/design/AvoidDeeplyNestedIfStmtsTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidDeeplyNestedIfStmtsTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/design/NoInlineStylesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NoInlineStylesTest extends PmdRuleTst {
// no additional unit tests
}
| 272 | 21.75 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/design/NoInlineJavaScriptTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NoInlineJavaScriptTest extends PmdRuleTst {
// no additional unit tests
}
| 276 | 22.083333 | 79 | java |
pmd | pmd-master/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/rule/design/CollapsibleIfStatementsTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CollapsibleIfStatementsTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/VmHandler.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm;
import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.vm.ast.VmParser;
/**
* Implementation of LanguageVersionHandler for the VM parser.
*
*/
public class VmHandler extends AbstractPmdLanguageVersionHandler {
@Override
public Parser getParser() {
return new VmParser();
}
}
| 516 | 20.541667 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/VmLanguageModule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* Created by christoferdutz on 20.09.14.
*/
public class VmLanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "VM";
public static final String TERSE_NAME = "vm";
public VmLanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME)
.extensions("vm")
.addVersion("2.0")
.addVersion("2.1")
.addVersion("2.2")
.addDefaultVersion("2.3"),
new VmHandler());
}
}
| 789 | 27.214286 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTAddNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Handles number addition of nodes.
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTAddNode.java 712887 2008-11-11 00:27:50Z nbubna $
*/
public final class ASTAddNode extends ASTMathNode {
ASTAddNode(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,603 | 33.869565 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTSubtractNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Handles subtraction of nodes (in #set() )<br>
* <br>
*
* Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTSubtractNode.java 691048 2008-09-01 20:26:11Z nbubna $
*/
public final class ASTSubtractNode extends ASTMathNode {
ASTSubtractNode(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,636 | 33.104167 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/VmNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.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 VmNode extends JjtreeNode<VmNode> {
/**
* Accept the visitor.
*
* @deprecated Use {@link #acceptVisitor(AstVisitor, Object)}
*/
@Deprecated
@DeprecatedUntil700
default Object jjtAccept(VmParserVisitor visitor, Object data) {
return acceptVisitor(visitor, data);
}
}
| 630 | 24.24 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/NodeUtils.java |
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Utilities for dealing with the AST node structure.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: NodeUtils.java 687386 2008-08-20 16:57:07Z nbubna $
*/
final class NodeUtils {
private NodeUtils() { }
/**
* Collect all the <SPECIAL_TOKEN>s that are carried along with a token.
* Special tokens do not participate in parsing but can still trigger
* certain lexical actions. In some cases you may want to retrieve these
* special tokens, this is simply a way to extract them.
*
* @param t
* the Token
* @return StrBuilder with the special tokens.
*/
private static StringBuilder getSpecialText(final JavaccToken t) {
final StringBuilder sb = new StringBuilder();
JavaccToken tmpToken = t.getPreviousComment();
while (tmpToken.getPreviousComment() != null) {
tmpToken = tmpToken.getPreviousComment();
}
while (tmpToken != null) {
final String st = tmpToken.getImage();
int i = 0;
while (i < st.length()) {
final char c = st.charAt(i);
if (c == '#' || c == '$') {
sb.append(c);
}
/*
* more dreaded MORE hack :)
*
* looking for ("\\")*"$" sequences
*/
if (c == '\\') {
boolean ok = true;
boolean term = false;
int j = i;
for (ok = true; ok && j < st.length(); j++) {
final char cc = st.charAt(j);
if (cc == '\\') {
/*
* if we see a \, keep going
*/
continue;
} else if (cc == '$') {
/*
* a $ ends it correctly
*/
term = true;
ok = false;
} else {
/*
* nah...
*/
ok = false;
}
}
if (term) {
final String foo = st.substring(i, j);
sb.append(foo);
i = j;
}
}
i++;
}
tmpToken = tmpToken.next;
}
return sb;
}
/**
* complete node literal
*
* @param t
* @return A node literal.
*/
static String tokenLiteral(final JavaccToken t) {
// Look at kind of token and return "" when it's a multiline comment
if (t.kind == VmTokenKinds.MULTI_LINE_COMMENT) {
return "";
} else if (t.getPreviousComment() == null || t.getPreviousComment().getImage().startsWith("##")) {
return t.getImage();
} else {
final StringBuilder special = getSpecialText(t);
if (special.length() > 0) {
return special.append(t.getImage()).toString();
}
return t.getImage();
}
}
}
| 4,349 | 31.462687 | 106 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/VmParserVisitorAdapter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
@Deprecated
@DeprecatedUntil700
public class VmParserVisitorAdapter extends VmVisitorBase<Object, Object> implements VmParserVisitor {
}
| 327 | 22.428571 | 102 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMethod.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* ASTMethod.java
*
* <p>Method support for references : $foo.method()
*
* <p>NOTE :
* introspection is now done at render time.
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTMethod.java 720228 2008-11-24 16:58:33Z nbubna $
*/
public final class ASTMethod extends AbstractVmNode {
ASTMethod(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* @return Returns the methodName.
* @since 1.5
*/
public String getMethodName() {
return "";
}
}
| 1,699 | 28.310345 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/VmVisitorBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.lang.ast.AstVisitorBase;
public abstract class VmVisitorBase<P, R> extends AstVisitorBase<P, R> implements VmVisitor<P, R> {
}
| 287 | 21.153846 | 99 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/VmParserVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
@Deprecated
@DeprecatedUntil700
public interface VmParserVisitor extends VmVisitor<Object, Object> {
@Override
default Object visitNode(Node node, Object param) {
node.children().forEach(it -> it.acceptVisitor(this, param));
return param;
}
}
| 503 | 24.2 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTReference.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* This class is responsible for handling the references in VTL ($foo).
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="mailto:Christoph.Reck@dlr.de">Christoph Reck</a>
* @author <a href="mailto:kjohnson@transparent.com">Kent Johnson</a>
* @version $Id: ASTReference.java 806597 2009-08-21 15:21:44Z nbubna $
*/
public final class ASTReference extends AbstractVmNode {
private String rootString;
private String literal = null;
ASTReference(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Returns the 'root string', the reference key.
*
* @return the root string.
*/
public String getRootString() {
return rootString;
}
/**
* Routine to allow the literal representation to be externally overridden.
* Used now in the VM system to override a reference in a VM tree with the
* literal of the calling arg to make it work nicely when calling arg is
* null. It seems a bit much, but does keep things consistent.
*
* <p>Note, you can only set the literal once...
*
* @param literal
* String to render to when null
*/
void setLiteral(final String literal) {
/*
* do only once
*/
if (this.literal == null) {
this.literal = literal;
}
}
/**
* Override of the SimpleNode method literal() Returns the literal
* representation of the node. Should be something like $<token>.
*
* @return A literal string.
*/
@Override
public String literal() {
if (literal != null) {
return literal;
}
// this value could be cached in this.literal but it increases memory
// usage
return super.literal();
}
}
| 2,982 | 30.072917 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTDirective.java |
package net.sourceforge.pmd.lang.vm.ast;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* This class is responsible for handling the pluggable directives in VTL.
*
* <p>For example : #foreach()
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="mailto:kav@kav.dk">Kasper Nielsen</a>
* @version $Id: ASTDirective.java 724825 2008-12-09 18:56:06Z nbubna $
*/
public final class ASTDirective extends AbstractVmNode {
private static final Set<String> DIRECTIVE_NAMES;
private static final Set<String> BLOCK_DIRECTIVES;
private static final Set<String> LINE_DIRECTIVES;
static {
Set<String> blocks = new HashSet<>();
blocks.add("define");
blocks.add("foreach");
blocks.add("literal");
blocks.add("macro");
Set<String> lines = new HashSet<>();
lines.add("break");
lines.add("evaluate");
lines.add("include");
lines.add("parse");
lines.add("stop");
Set<String> directives = new HashSet<>();
directives.addAll(blocks);
directives.addAll(lines);
DIRECTIVE_NAMES = Collections.unmodifiableSet(directives);
BLOCK_DIRECTIVES = Collections.unmodifiableSet(blocks);
LINE_DIRECTIVES = Collections.unmodifiableSet(lines);
}
private String directiveName = "";
ASTDirective(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Sets the directive name. Used by the parser. This keeps us from having to
* dig it out of the token stream and gives the parse the change to
* override.
*/
void setDirectiveName(final String str) {
directiveName = str;
}
/**
* Gets the name of this directive.
*
* @return The name of this directive.
*/
public String getDirectiveName() {
return directiveName;
}
boolean isDirective() {
assert directiveName != null; // directive name must be set before
return DIRECTIVE_NAMES.contains(directiveName);
}
// block macro call of type: #@foobar($arg1 $arg2) astBody #end
boolean isBlock() {
assert directiveName != null; // directive name must be set before
return directiveName.startsWith("@")
|| BLOCK_DIRECTIVES.contains(directiveName);
}
boolean isLine() {
assert directiveName != null; // directive name must be set before
return LINE_DIRECTIVES.contains(directiveName)
// not a real directive, but maybe a Velocimacro
|| !isDirective();
}
}
| 3,735 | 30.931624 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTTemplate.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
public final class ASTTemplate extends AbstractVmNode implements RootNode {
private AstInfo<ASTTemplate> astInfo;
public ASTTemplate(int id) {
super(id);
}
@Override
public AstInfo<ASTTemplate> getAstInfo() {
return astInfo;
}
ASTTemplate makeTaskInfo(ParserTask task) {
this.astInfo = new AstInfo<>(task, this);
return this;
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 831 | 22.771429 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/VmParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeParserAdapter;
/**
* Adapter for the VmParser.
*/
public class VmParser extends JjtreeParserAdapter<ASTTemplate> {
private static final TokenDocumentBehavior TOKEN_BEHAVIOR = new TokenDocumentBehavior(VmTokenKinds.TOKEN_NAMES) {
@Override
public JavaccToken createToken(JavaccTokenDocument self, int kind, CharStream cs, @Nullable String image) {
String realImage = image == null ? cs.getTokenImage() : image;
if (kind == VmTokenKinds.ESCAPE_DIRECTIVE) {
realImage = escapedDirective(realImage);
}
return super.createToken(self, kind, cs, realImage);
}
private String escapedDirective(String strImage) {
int iLast = strImage.lastIndexOf("\\");
String strDirective = strImage.substring(iLast + 1);
return strImage.substring(0, iLast / 2) + strDirective;
}
};
@Override
protected TokenDocumentBehavior tokenBehavior() {
return TOKEN_BEHAVIOR;
}
@Override
protected ASTTemplate parseImpl(CharStream cs, ParserTask task) throws ParseException {
return new VmParserImpl(cs).Template().makeTaskInfo(task);
}
}
| 1,781 | 33.269231 | 117 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTModNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Handles modulus division
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTModNode.java 691048 2008-09-01 20:26:11Z nbubna $
*/
public final class ASTModNode extends ASTMathNode {
ASTModNode(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,530 | 32.282609 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTDivNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Handles number division of nodes
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTDivNode.java 691048 2008-09-01 20:26:11Z nbubna $
*/
public final class ASTDivNode extends ASTMathNode {
ASTDivNode(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,603 | 33.12766 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/AbstractVmNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.AbstractJjtreeNode;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
abstract class AbstractVmNode extends AbstractJjtreeNode<AbstractVmNode, VmNode> implements VmNode {
protected AbstractVmNode(final int i) {
super(i);
}
@Override // override to make protected member accessible to parser
protected void setImage(String image) {
super.setImage(image);
}
@Override
public String getXPathNodeName() {
return VmParserImplTreeConstants.jjtNodeName[id];
}
protected abstract <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data);
@Override
@SuppressWarnings("unchecked")
public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof VmVisitor) {
return acceptVmVisitor((VmVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
/*
* see org.apache.velocity.runtime.parser.node.Node#literal()
*/
public String literal() {
// if we have only one string, just return it and avoid
// buffer allocation. VELOCITY-606
if (getFirstToken() != null && getFirstToken().equals(getLastToken())) {
return NodeUtils.tokenLiteral(getFirstToken());
}
JavaccToken t = getFirstToken();
final StringBuilder sb = new StringBuilder(NodeUtils.tokenLiteral(t));
while (t != null && !t.equals(getLastToken())) {
t = t.getNext();
sb.append(NodeUtils.tokenLiteral(t));
}
return sb.toString();
}
}
| 2,590 | 33.092105 | 100 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMathNode.java | package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Helps handle math
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author Nathan Bubna
* @version $Id: ASTMathNode.java 517553 2007-03-13 06:09:58Z wglass $
*/
abstract class ASTMathNode extends AbstractVmNode {
ASTMathNode(int id) {
super(id);
}
}
| 1,458 | 33.738095 | 81 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTBlock.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.ast;
import org.apache.commons.lang3.StringUtils;
public final class ASTBlock extends AbstractVmNode {
ASTBlock(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public boolean isEmpty() {
return getNumChildren() == 0
|| getNumChildren() == 1
&& getChild(0) instanceof ASTText
&& StringUtils.isBlank(getChild(0).getText());
}
}
| 653 | 22.357143 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMulNode.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Handles multiplication
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
* @author <a href="mailto:pero@antaramusic.de">Peter Romianowski</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTMulNode.java 691048 2008-09-01 20:26:11Z nbubna $
*/
public final class ASTMulNode extends ASTMathNode {
ASTMulNode(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,593 | 32.914894 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTStringLiteral.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* ASTStringLiteral support. Will interpolate!
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @version $Id: ASTStringLiteral.java 705297 2008-10-16 17:59:24Z nbubna $
*/
public final class ASTStringLiteral extends AbstractVmNode {
ASTStringLiteral(int id) {
super(id);
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Check to see if this is an interpolated string.
*
* @return true if this is constant (not an interpolated string)
* @since 1.6
*/
public boolean isConstant() {
return false;
}
}
| 1,614 | 31.3 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTEscape.java |
package net.sourceforge.pmd.lang.vm.ast;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* This class is responsible for handling Escapes in VTL.
*
* <p>Please look at the Parser.jjt file which is what controls the generation of
* this class.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTEscape.java 517553 2007-03-13 06:09:58Z wglass $
*/
public final class ASTEscape extends AbstractVmNode {
/** Used by the parser. */
private String val;
ASTEscape(int id) {
super(id);
}
void setValue(String value) {
this.val = value;
}
public String getValue() {
return val;
}
@Override
protected <P, R> R acceptVmVisitor(VmVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,605 | 27.678571 | 91 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/AbstractVmRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.lang.vm.ast.VmParserVisitor;
public abstract class AbstractVmRule extends AbstractRule implements VmParserVisitor {
@Override
public void apply(Node target, RuleContext ctx) {
target.acceptVisitor(this, ctx);
}
}
| 526 | 26.736842 | 86 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/errorprone/EmptyForeachStmtRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.errorprone;
import net.sourceforge.pmd.lang.vm.ast.ASTBlock;
import net.sourceforge.pmd.lang.vm.ast.ASTForeachStatement;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class EmptyForeachStmtRule extends AbstractVmRule {
@Override
public Object visit(final ASTForeachStatement node, final Object data) {
if (node.getFirstChildOfType(ASTBlock.class).isEmpty()) {
addViolation(data, node);
}
return super.visit(node, data);
}
}
| 622 | 27.318182 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/errorprone/EmptyIfStmtRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.errorprone;
import net.sourceforge.pmd.lang.vm.ast.ASTBlock;
import net.sourceforge.pmd.lang.vm.ast.ASTElseIfStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTElseStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.vm.ast.VmNode;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class EmptyIfStmtRule extends AbstractVmRule {
@Override
public Object visit(final ASTIfStatement node, final Object data) {
handleIf(node, data);
return super.visit(node, data);
}
@Override
public Object visit(final ASTElseIfStatement node, final Object data) {
handleIf(node, data);
return super.visit(node, data);
}
@Override
public Object visit(final ASTElseStatement node, final Object data) {
handleIf(node, data);
return super.visit(node, data);
}
private void handleIf(final VmNode node, final Object data) {
if (node.getFirstChildOfType(ASTBlock.class).isEmpty()) {
addViolation(data, node);
}
}
}
| 1,203 | 29.871795 | 79 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/bestpractices/AvoidReassigningParametersRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.bestpractices;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.lang.vm.ast.ASTDirective;
import net.sourceforge.pmd.lang.vm.ast.ASTReference;
import net.sourceforge.pmd.lang.vm.ast.ASTSetDirective;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class AvoidReassigningParametersRule extends AbstractVmRule {
@Override
public Object visit(final ASTDirective node, final Object data) {
if ("macro".equals(node.getDirectiveName())) {
final Set<String> paramNames = new HashSet<>();
final List<ASTReference> params = node.findChildrenOfType(ASTReference.class);
for (final ASTReference param : params) {
paramNames.add(param.getFirstToken().getImage());
}
final List<ASTSetDirective> assignments = node.findDescendantsOfType(ASTSetDirective.class);
for (final ASTSetDirective assignment : assignments) {
final ASTReference ref = assignment.getFirstChildOfType(ASTReference.class);
if (ref != null && paramNames.contains(ref.getFirstToken().getImage())) {
addViolation(data, node, ref.getFirstToken().getImage());
}
}
}
return super.visit(node, data);
}
}
| 1,453 | 38.297297 | 104 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/bestpractices/UnusedMacroParameterRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.bestpractices;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.lang.vm.ast.ASTBlock;
import net.sourceforge.pmd.lang.vm.ast.ASTDirective;
import net.sourceforge.pmd.lang.vm.ast.ASTReference;
import net.sourceforge.pmd.lang.vm.ast.ASTStringLiteral;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class UnusedMacroParameterRule extends AbstractVmRule {
@Override
public Object visit(final ASTDirective node, final Object data) {
if ("macro".equals(node.getDirectiveName())) {
final Set<String> paramNames = new HashSet<>();
final List<ASTReference> params = node.findChildrenOfType(ASTReference.class);
for (final ASTReference param : params) {
paramNames.add(param.literal());
}
final ASTBlock macroBlock = node.getFirstChildOfType(ASTBlock.class);
if (macroBlock != null) {
for (final ASTReference referenceInMacro : macroBlock.findDescendantsOfType(ASTReference.class)) {
checkForParameter(paramNames, referenceInMacro.literal());
}
for (final ASTStringLiteral literalInMacro : macroBlock.findDescendantsOfType(ASTStringLiteral.class)) {
final String text = literalInMacro.literal();
checkForParameter(paramNames, text);
}
}
if (!paramNames.isEmpty()) {
addViolation(data, node, paramNames.toString());
}
}
return super.visit(node, data);
}
private void checkForParameter(final Set<String> paramNames, final String nameToSearch) {
final Set<String> paramsContained = new HashSet<>();
for (final String param : paramNames) {
if (containsAny(nameToSearch, formatNameVariations(param))) {
paramsContained.add(param);
}
}
paramNames.removeAll(paramsContained);
}
private boolean containsAny(final String text, final String[] formatNameVariations) {
for (final String formattedName : formatNameVariations) {
if (text.contains(formattedName)) {
return true;
}
}
return false;
}
private String[] formatNameVariations(final String param) {
final String actualName = param.substring(1);
return new String[] { param, "${" + actualName + "}", "${" + actualName + ".", "$!" + actualName,
"$!{" + actualName + ".", "$!{" + actualName + "}", };
}
}
| 2,726 | 38.521739 | 120 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/design/CollapsibleIfStatementsRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.vm.ast.ASTBlock;
import net.sourceforge.pmd.lang.vm.ast.ASTElseIfStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTElseStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTText;
import net.sourceforge.pmd.lang.vm.ast.VmNode;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class CollapsibleIfStatementsRule extends AbstractVmRule {
@Override
public Object visit(final ASTIfStatement node, final Object data) {
handleIfElseIf(node, data);
return super.visit(node, data);
}
@Override
public Object visit(final ASTElseIfStatement node, final Object data) {
// verify that this elseif doesn't have any siblings
if (node.getParent().findChildrenOfType(ASTElseIfStatement.class).size() == 1) {
handleIfElseIf(node, data);
}
return super.visit(node, data);
}
private void handleIfElseIf(final VmNode node, final Object data) {
if (node.getFirstChildOfType(ASTElseStatement.class) == null
&& node.getFirstChildOfType(ASTElseIfStatement.class) == null) {
final ASTBlock ifBlock = node.getFirstChildOfType(ASTBlock.class);
boolean violationFound = false;
int ifCounter = 0;
for (int i = 0; i < ifBlock.getNumChildren(); i++) {
final Node blockChild = ifBlock.getChild(i);
if (blockChild instanceof ASTText) {
if (StringUtils.isNotBlank(((ASTText) blockChild).getFirstToken().getImage())) {
violationFound = false;
break;
}
} else if (blockChild instanceof ASTIfStatement) {
// check if it has an ELSE of ELSEIF
violationFound = !hasElseOrElseIf(blockChild);
if (!violationFound) {
break;
}
ifCounter++;
} else if (blockChild instanceof ASTElseIfStatement) {
// check if it has an ELSE of ELSEIF
violationFound = !hasElseOrElseIf(blockChild);
if (!violationFound) {
break;
}
ifCounter++;
} else {
// any other node - not violation
violationFound = false;
break;
}
}
if (violationFound && ifCounter == 1) {
addViolation(data, node);
}
}
}
private boolean hasElseOrElseIf(final Node parentIfNode) {
return parentIfNode.getFirstChildOfType(ASTElseStatement.class) != null
|| parentIfNode.getFirstChildOfType(ASTElseIfStatement.class) != null;
}
}
| 3,118 | 37.9875 | 100 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/design/NoInlineJavaScriptRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.pmd.lang.vm.ast.ASTText;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
public class NoInlineJavaScriptRule extends AbstractVmRule {
private static final Pattern SCRIPT_PATTERN = Pattern.compile("<script\\s[^>]*>", Pattern.CASE_INSENSITIVE);
private static final Pattern SRC_PATTERN = Pattern.compile("\\ssrc\\s*=", Pattern.CASE_INSENSITIVE);
@Override
public Object visit(final ASTText node, final Object data) {
final Matcher matcher = SCRIPT_PATTERN.matcher(node.literal());
while (matcher.find()) {
final String currentMatch = matcher.group();
if (!SRC_PATTERN.matcher(currentMatch).find()) {
addViolation(data, node);
}
}
return super.visit(node, data);
}
}
| 1,004 | 33.655172 | 112 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/design/AvoidDeeplyNestedIfStmtsRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import net.sourceforge.pmd.lang.vm.ast.ASTElseIfStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.vm.ast.ASTTemplate;
import net.sourceforge.pmd.lang.vm.ast.VmNode;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
public class AvoidDeeplyNestedIfStmtsRule extends AbstractVmRule {
private int depth;
private int depthLimit;
private static final PropertyDescriptor<Integer> PROBLEM_DEPTH_DESCRIPTOR
= PropertyFactory.intProperty("problemDepth")
.desc("The if statement depth reporting threshold")
.require(positive()).defaultValue(3).build();
public AvoidDeeplyNestedIfStmtsRule() {
definePropertyDescriptor(PROBLEM_DEPTH_DESCRIPTOR);
}
@Override
public Object visit(ASTTemplate node, Object data) {
depth = 0;
depthLimit = getProperty(PROBLEM_DEPTH_DESCRIPTOR);
return super.visit(node, data);
}
@Override
public Object visit(ASTIfStatement node, Object data) {
return handleIf(node, data);
}
@Override
public Object visit(ASTElseIfStatement node, Object data) {
return handleIf(node, data);
}
private Object handleIf(VmNode node, Object data) {
depth++;
super.visitVmNode(node, data);
if (depth == depthLimit) {
addViolation(data, node);
}
depth--;
return data;
}
}
| 1,812 | 29.216667 | 85 | java |
pmd | pmd-master/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/rule/design/ExcessiveTemplateLengthRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vm.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import net.sourceforge.pmd.lang.rule.internal.CommonPropertyDescriptors;
import net.sourceforge.pmd.lang.vm.ast.ASTTemplate;
import net.sourceforge.pmd.lang.vm.rule.AbstractVmRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
public class ExcessiveTemplateLengthRule extends AbstractVmRule {
private static final PropertyDescriptor<Integer> REPORT_LEVEL =
CommonPropertyDescriptors.reportLevelProperty()
.desc("Threshold above which a node is reported")
.require(positive())
.defaultValue(1000)
.build();
public ExcessiveTemplateLengthRule() {
definePropertyDescriptor(REPORT_LEVEL);
addRuleChainVisit(ASTTemplate.class);
}
@Override
public Object visit(final ASTTemplate node, final Object data) {
if (node.getEndLine() - node.getBeginLine() >= getProperty(REPORT_LEVEL)) {
addViolation(data, node);
}
return data;
}
}
| 1,279 | 33.594595 | 85 | java |
pmd | pmd-master/pmd-ant/src/test/java/net/sourceforge/pmd/ant/AbstractAntTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties;
import java.io.File;
import java.io.PrintStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.junit.jupiter.api.AfterAll;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.internal.util.IOUtil;
class AbstractAntTest {
protected Project project;
protected StringBuilder log;
protected StringWriter out;
protected StringWriter err;
protected void configureProject(String filename) {
project = new Project();
project.init();
project.addBuildListener(new AntBuildListener(Project.MSG_INFO));
File antFile = new File(filename);
ProjectHelper.configureProject(project, antFile);
}
@AfterAll
static void resetLogging() {
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null);
}
protected void executeTarget(String targetName) {
// restoring system properties: PMDTask might change logging properties
// See Slf4jSimpleConfigurationForAnt and resetLogging
try {
restoreSystemProperties(() -> {
executeTargetImpl(targetName);
});
} catch (BuildException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void executeTargetImpl(String targetName) {
log = new StringBuilder();
out = new StringWriter();
err = new StringWriter();
PrintStream outStream = new PrintStream(IOUtil.fromWriter(out, Charset.defaultCharset().name()));
PrintStream errStream = new PrintStream(IOUtil.fromWriter(err, Charset.defaultCharset().name()));
synchronized (System.out) {
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
originalOut.flush();
originalErr.flush();
try {
System.setOut(outStream);
System.setErr(errStream);
project.executeTarget(targetName);
} finally {
System.setOut(originalOut);
System.setErr(originalErr);
}
}
}
private class AntBuildListener implements BuildListener {
private final int logLevel;
private AntBuildListener(int logLevel) {
this.logLevel = logLevel;
}
@Override
public void buildStarted(BuildEvent event) {
}
@Override
public void buildFinished(BuildEvent event) {
}
@Override
public void targetStarted(BuildEvent event) {
}
@Override
public void targetFinished(BuildEvent event) {
}
@Override
public void taskStarted(BuildEvent event) {
}
@Override
public void taskFinished(BuildEvent event) {
}
@Override
public void messageLogged(BuildEvent event) {
if (event.getPriority() > logLevel) {
return;
}
log.append(event.getMessage());
}
}
}
| 3,507 | 27.520325 | 105 | java |
pmd | pmd-master/pmd-ant/src/test/java/net/sourceforge/pmd/ant/FormatterTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
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.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.renderers.CSVRenderer;
import net.sourceforge.pmd.renderers.HTMLRenderer;
import net.sourceforge.pmd.renderers.TextRenderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
class FormatterTest {
@Test
void testType() {
Formatter f = new Formatter();
f.setType("xml");
assertTrue(f.createRenderer() instanceof XMLRenderer);
f.setType("text");
assertTrue(f.createRenderer() instanceof TextRenderer);
f.setType("csv");
assertTrue(f.createRenderer() instanceof CSVRenderer);
f.setType("html");
assertTrue(f.createRenderer() instanceof HTMLRenderer);
try {
f.setType("FAIL");
f.createRenderer();
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException be) {
assertTrue(be.getMessage().startsWith("Can't find the custom format FAIL"));
}
}
@Test
void testNull() {
Formatter f = new Formatter();
assertTrue(f.isNoOutputSupplied(), "Formatter toFile should start off null!");
f.setToFile(new File("foo"));
assertFalse(f.isNoOutputSupplied(), "Formatter toFile should not be null!");
}
}
| 1,585 | 30.72 | 88 | java |
pmd | pmd-master/pmd-ant/src/test/java/net/sourceforge/pmd/ant/CPDTaskTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
*
* @author Romain Pelisse <belaran@gmail.com>
*
*/
class CPDTaskTest extends AbstractAntTest {
@BeforeEach
void setUp() {
configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/cpdtasktest.xml");
}
@Test
void testBasic() {
executeTarget("testBasic");
// FIXME: This clearly needs to be improved - but I don't like to write
// test, so feel free to contribute :)
assertTrue(new File("target/cpd.ant.tests").exists());
}
}
| 793 | 22.352941 | 91 | java |
pmd | pmd-master/pmd-ant/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
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.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.tools.ant.BuildException;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.util.IOUtil;
class PMDTaskTest extends AbstractAntTest {
@BeforeEach
void setUp() {
configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/pmdtasktest.xml");
}
@Test
void testFormatterWithNoToFileAttribute() {
try {
executeTarget("testFormatterWithNoToFileAttribute");
fail("This should throw an exception");
} catch (BuildException ex) {
assertEquals("toFile or toConsole needs to be specified in Formatter", ex.getMessage());
}
}
@Test
void testNoRuleSets() {
try {
executeTarget("testNoRuleSets");
fail("This should throw an exception");
} catch (BuildException ex) {
assertEquals("No rulesets specified", ex.getMessage());
}
}
@Test
void testBasic() {
executeTarget("testBasic");
}
@Test
void testInvalidLanguageVersion() {
try {
executeTarget("testInvalidLanguageVersion");
assertEquals(
"The following language is not supported:<sourceLanguage name=\"java\" version=\"42\" />.",
log.toString());
fail("This should throw an exception");
} catch (BuildException ex) {
assertEquals(
"The following language is not supported:<sourceLanguage name=\"java\" version=\"42\" />.",
ex.getMessage());
}
}
@Test
void testRelativizeWith() throws IOException {
executeTarget("testRelativizeWith");
try (InputStream in = Files.newInputStream(Paths.get("target/pmd-ant-test.txt"))) {
String actual = IOUtil.readToString(in, StandardCharsets.UTF_8);
// remove any trailing newline
actual = actual.replaceAll("\n|\r", "");
assertThat(actual, containsString("src" + File.separator + "sample.dummy:1:\tSampleXPathRule:\tTest Rule 2"));
}
}
@Test
void testXmlFormatter() throws IOException {
executeTarget("testXmlFormatter");
try (InputStream in = Files.newInputStream(Paths.get("target/pmd-ant-xml.xml"));
InputStream expectedStream = PMDTaskTest.class.getResourceAsStream("xml/expected-pmd-ant-xml.xml")) {
String actual = readAndNormalize(in);
String expected = readAndNormalize(expectedStream);
assertEquals(expected, actual);
}
}
private static @NonNull String readAndNormalize(InputStream expectedStream) throws IOException {
String expected = IOUtil.readToString(expectedStream, StandardCharsets.UTF_8);
expected = expected.replaceFirst("timestamp=\"[^\"]+\"", "timestamp=\"\"");
expected = expected.replaceFirst("\\.xsd\" version=\"[^\"]+\"", ".xsd\" version=\"\"");
return expected;
}
}
| 3,599 | 33.285714 | 122 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import java.io.BufferedWriter;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Parameter;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.RendererFactory;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.FileNameRenderer;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
import net.sourceforge.pmd.reporting.ListenerInitializer;
@InternalApi
public class Formatter {
private File toFile;
private String type;
private boolean toConsole;
private boolean showSuppressed;
private final List<Parameter> parameters = new ArrayList<>();
private Writer writer;
private Renderer renderer;
public void setShowSuppressed(boolean value) {
this.showSuppressed = value;
}
public void setType(String type) {
this.type = type;
}
public void setToFile(File toFile) {
this.toFile = toFile;
}
public void setToConsole(boolean toConsole) {
this.toConsole = toConsole;
}
public void addConfiguredParam(Parameter parameter) {
this.parameters.add(parameter);
}
@Deprecated
@InternalApi
public Renderer getRenderer() {
return renderer;
}
@Deprecated
@InternalApi
public void start(String baseDir) {
Properties properties = createProperties();
Charset charset;
{
String s = (String) properties.get("encoding");
if (null == s) {
if (toConsole) {
s = getConsoleEncoding();
if (null == s) {
s = System.getProperty("file.encoding");
}
}
if (null == s) {
charset = StandardCharsets.UTF_8;
} else {
charset = Charset.forName(s);
}
// Configures the encoding for the renderer.
final Parameter parameter = new Parameter();
parameter.setName("encoding");
parameter.setValue(charset.name());
parameters.add(parameter);
} else {
charset = Charset.forName(s);
}
}
try {
if (toConsole) {
writer = new BufferedWriter(new OutputStreamWriter(System.out, charset));
}
if (toFile != null) {
writer = getToFileWriter(baseDir, toFile, charset);
}
renderer = createRenderer();
renderer.setWriter(writer);
} catch (IOException ioe) {
throw new BuildException(ioe.getMessage(), ioe);
}
}
@Deprecated
@InternalApi
public void end(Report errorReport) {
try {
renderer.renderFileReport(errorReport);
renderer.end();
if (toConsole) {
writer.flush();
} else {
writer.close();
}
} catch (IOException ioe) {
throw new BuildException(ioe.getMessage(), ioe);
}
}
@Deprecated
@InternalApi
public boolean isNoOutputSupplied() {
return toFile == null && !toConsole;
}
@Override
public String toString() {
return "file = " + toFile + "; renderer = " + type;
}
private static String[] validRendererCodes() {
return RendererFactory.supportedRenderers().toArray(new String[0]);
}
private static String unknownRendererMessage(String userSpecifiedType) {
String[] typeCodes = validRendererCodes();
StringBuilder sb = new StringBuilder(100);
sb.append("Formatter type must be one of: '").append(typeCodes[0]);
for (int i = 1; i < typeCodes.length; i++) {
sb.append("', '").append(typeCodes[i]);
}
sb.append("', or a class name; you specified: ").append(userSpecifiedType);
return sb.toString();
}
// FIXME - hm, what about this consoleRenderer thing... need a test for this
Renderer createRenderer() {
if (StringUtils.isBlank(type)) {
throw new BuildException(unknownRendererMessage("<unspecified>"));
}
Properties properties = createProperties();
Renderer renderer = RendererFactory.createRenderer(type, properties);
renderer.setShowSuppressedViolations(showSuppressed);
return renderer;
}
private Properties createProperties() {
Properties properties = new Properties();
for (Parameter parameter : parameters) {
properties.put(parameter.getName(), parameter.getValue());
}
return properties;
}
private static Writer getToFileWriter(String baseDir, File toFile, Charset charset) throws IOException {
final File file;
if (toFile.isAbsolute()) {
file = toFile;
} else {
file = new File(baseDir + System.getProperty("file.separator") + toFile.getPath());
}
OutputStream output = null;
Writer writer = null;
boolean isOnError = true;
try {
output = Files.newOutputStream(file.toPath());
writer = new BufferedWriter(new OutputStreamWriter(output, charset));
isOnError = false;
} finally {
if (isOnError) {
IOUtil.closeQuietly(output);
IOUtil.closeQuietly(writer);
}
}
return writer;
}
private static String getConsoleEncoding() {
Console console = System.console();
// in case of pipe or redirect, no interactive console.
if (console != null) {
try {
Object res = FieldUtils.readDeclaredField(console, "cs", true);
if (res instanceof Charset) {
return ((Charset) res).name();
}
} catch (IllegalArgumentException | ReflectiveOperationException ignored) {
// fall-through
}
// Maybe this is Java17? Then there will be
// https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/Console.html#charset()
// instead of the field "cs".
try {
Charset charset = (Charset) MethodUtils.invokeMethod(console, "charset");
return charset.name();
} catch (IllegalArgumentException | ReflectiveOperationException ignored) {
// fall-through
}
return getNativeConsoleEncoding();
}
return null;
}
private static String getNativeConsoleEncoding() {
try {
Object res = MethodUtils.invokeStaticMethod(Console.class, "encoding");
if (res instanceof String) {
return (String) res;
}
} catch (IllegalArgumentException | ReflectiveOperationException ignored) {
// fall-through
}
return null;
}
@Deprecated
@InternalApi
public GlobalAnalysisListener newListener(Project project) throws IOException {
start(project.getBaseDir().toString());
Renderer renderer = getRenderer();
return new GlobalAnalysisListener() {
final GlobalAnalysisListener listener = renderer.newListener();
@Override
public ListenerInitializer initializer() {
return new ListenerInitializer() {
@Override
public void setFileNameRenderer(FileNameRenderer fileNameRenderer) {
renderer.setFileNameRenderer(fileNameRenderer);
}
};
}
@Override
public FileAnalysisListener startFileAnalysis(TextFile file) {
return listener.startFileAnalysis(file);
}
@Override
public void close() throws Exception {
listener.close();
if (!toConsole) {
writer.close();
}
}
};
}
}
| 8,996 | 30.791519 | 108 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/SourceLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import net.sourceforge.pmd.lang.Language;
/**
* Stores LanguageVersion terse name value.
*/
public class SourceLanguage {
private String name;
private String version;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
/** This actually corresponds to a {@link Language#getTerseName()}. */
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "<sourceLanguage name=\"" + this.name + "\" version=\"" + this.version + "\" />";
}
}
| 806 | 19.692308 | 96 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* PMD and CPD integration for the Apache Ant build system.
*/
package net.sourceforge.pmd.ant;
| 189 | 20.111111 | 79 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/RuleSetWrapper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
public class RuleSetWrapper {
private String file;
public final String getFile() {
return file;
}
public final void addText(String t) {
this.file = t;
}
}
| 316 | 16.611111 | 79 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/PMDTask.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.Resource;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.ant.internal.PMDTaskImpl;
/**
* PMD Ant task. Setters of this class are interpreted by Ant as properties
* settable in the XML. This is therefore published API.
*/
public class PMDTask extends Task {
private Path classpath;
private Path auxClasspath;
private final List<Formatter> formatters = new ArrayList<>();
private final List<FileSet> filesets = new ArrayList<>();
private boolean failOnError;
private boolean failOnRuleViolation;
private final List<Path> relativizePathsWith = new ArrayList<>();
private String suppressMarker;
private String rulesetFiles;
private boolean noRuleSetCompatibility;
private String encoding;
private int threads = 1; // same default as in PMDParameters (CLI)
private int minimumPriority = RulePriority.LOW.getPriority(); // inclusive
private int maxRuleViolations = 0;
private String failuresPropertyName;
private SourceLanguage sourceLanguage;
private String cacheLocation;
private boolean noCache;
private final Collection<RuleSetWrapper> nestedRules = new ArrayList<>();
@Override
public void execute() throws BuildException {
validate();
ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(PMDTask.class.getClassLoader());
try {
PMDTaskImpl mirror = new PMDTaskImpl(this);
mirror.execute();
} catch (Exception e) {
throw new BuildException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldClassloader);
}
}
private void validate() throws BuildException {
if (formatters.isEmpty()) {
Formatter defaultFormatter = new Formatter();
defaultFormatter.setType("text");
defaultFormatter.setToConsole(true);
formatters.add(defaultFormatter);
} else {
for (Formatter f : formatters) {
if (f.isNoOutputSupplied()) {
throw new BuildException("toFile or toConsole needs to be specified in Formatter");
}
}
}
if (rulesetFiles == null) {
if (nestedRules.isEmpty()) {
throw new BuildException("No rulesets specified");
}
rulesetFiles = getNestedRuleSetFiles();
}
}
private String getNestedRuleSetFiles() {
final StringBuilder sb = new StringBuilder();
for (Iterator<RuleSetWrapper> it = nestedRules.iterator(); it.hasNext();) {
RuleSetWrapper rs = it.next();
sb.append(rs.getFile());
if (it.hasNext()) {
sb.append(',');
}
}
return sb.toString();
}
public void setSuppressMarker(String suppressMarker) {
this.suppressMarker = suppressMarker;
}
public void setFailOnError(boolean fail) {
this.failOnError = fail;
}
public void setFailOnRuleViolation(boolean fail) {
this.failOnRuleViolation = fail;
}
public void setMaxRuleViolations(int max) {
if (max >= 0) {
this.maxRuleViolations = max;
this.failOnRuleViolation = true;
}
}
public void setRuleSetFiles(String ruleSets) {
this.rulesetFiles = ruleSets;
}
public void setEncoding(String sourceEncoding) {
this.encoding = sourceEncoding;
}
public void setThreads(int threads) {
this.threads = threads;
}
public void setFailuresPropertyName(String failuresPropertyName) {
this.failuresPropertyName = failuresPropertyName;
}
public void setMinimumPriority(int minPriority) {
this.minimumPriority = minPriority;
}
public void addFileset(FileSet set) {
filesets.add(set);
}
public void addFormatter(Formatter f) {
formatters.add(f);
}
public void addConfiguredSourceLanguage(SourceLanguage version) {
this.sourceLanguage = version;
}
public void setClasspath(Path classpath) {
this.classpath = classpath;
}
public Path getClasspath() {
return classpath;
}
public Path createClasspath() {
if (classpath == null) {
classpath = new Path(getProject());
}
return classpath.createPath();
}
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
public void setAuxClasspath(Path auxClasspath) {
this.auxClasspath = auxClasspath;
}
public Path getAuxClasspath() {
return auxClasspath;
}
public Path createAuxClasspath() {
if (auxClasspath == null) {
auxClasspath = new Path(getProject());
}
return auxClasspath.createPath();
}
public void setAuxClasspathRef(Reference r) {
createAuxClasspath().setRefid(r);
}
public void addRuleset(RuleSetWrapper r) {
nestedRules.add(r);
}
public List<Formatter> getFormatters() {
return formatters;
}
public List<FileSet> getFilesets() {
return filesets;
}
public boolean isFailOnError() {
return failOnError;
}
public boolean isFailOnRuleViolation() {
return failOnRuleViolation;
}
public String getSuppressMarker() {
return suppressMarker;
}
public String getRulesetFiles() {
return rulesetFiles;
}
public String getEncoding() {
return encoding;
}
public int getThreads() {
return threads;
}
public int getMinimumPriority() {
return minimumPriority;
}
public int getMaxRuleViolations() {
return maxRuleViolations;
}
public String getFailuresPropertyName() {
return failuresPropertyName;
}
public SourceLanguage getSourceLanguage() {
return sourceLanguage;
}
public Collection<RuleSetWrapper> getNestedRules() {
return nestedRules;
}
public boolean isNoRuleSetCompatibility() {
return noRuleSetCompatibility;
}
public void setNoRuleSetCompatibility(boolean noRuleSetCompatibility) {
this.noRuleSetCompatibility = noRuleSetCompatibility;
}
public String getCacheLocation() {
return cacheLocation;
}
public void setCacheLocation(String cacheLocation) {
this.cacheLocation = cacheLocation;
}
public boolean isNoCache() {
return noCache;
}
public void setNoCache(boolean noCache) {
this.noCache = noCache;
}
public void addRelativizePathsWith(Path relativizePathsWith) {
this.relativizePathsWith.add(relativizePathsWith);
}
public List<Path> getRelativizePathsWith() {
return relativizePathsWith;
}
@InternalApi
public List<java.nio.file.Path> getRelativizeRoots() {
List<java.nio.file.Path> paths = new ArrayList<>();
for (Path path : getRelativizePathsWith()) {
for (Resource resource : path) {
paths.add(Paths.get(resource.toString()));
}
}
return paths;
}
}
| 7,807 | 26.017301 | 103 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/CPDTask.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
import net.sourceforge.pmd.cpd.CPD;
import net.sourceforge.pmd.cpd.CPDConfiguration;
import net.sourceforge.pmd.cpd.CPDReport;
import net.sourceforge.pmd.cpd.CSVRenderer;
import net.sourceforge.pmd.cpd.Language;
import net.sourceforge.pmd.cpd.LanguageFactory;
import net.sourceforge.pmd.cpd.ReportException;
import net.sourceforge.pmd.cpd.SimpleRenderer;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.XMLRenderer;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
/**
* CPD Ant task. Setters of this class are interpreted by Ant as properties
* settable in the XML. This is therefore published API.
*
* <p>Runs the CPD utility via ant. The ant task looks like this:</p>
*
* <pre>
* <project name="CPDProj" default="main" basedir=".">
* <taskdef name="cpd" classname="net.sourceforge.pmd.cpd.CPDTask" />
* <target name="main">
* <cpd encoding="UTF-16LE" language="java" ignoreIdentifiers="true"
* ignoreLiterals="true" ignoreAnnotations="true" minimumTokenCount="100"
* outputFile="c:\cpdrun.txt">
* <fileset dir="/path/to/my/src">
* <include name="*.java"/>
* </fileset>
* </cpd>
* </target>
* </project>
* </pre>
*
* <p>Required: minimumTokenCount, outputFile, and at least one file</p>
*/
public class CPDTask extends Task {
private static final String TEXT_FORMAT = "text";
private static final String XML_FORMAT = "xml";
private static final String CSV_FORMAT = "csv";
private String format = TEXT_FORMAT;
private String language = "java";
private int minimumTokenCount;
private boolean ignoreLiterals;
private boolean ignoreIdentifiers;
private boolean ignoreAnnotations;
private boolean ignoreUsings;
private boolean skipLexicalErrors;
private boolean skipDuplicateFiles;
private boolean skipBlocks = true;
private String skipBlocksPattern = Tokenizer.DEFAULT_SKIP_BLOCKS_PATTERN;
private File outputFile;
private String encoding = System.getProperty("file.encoding");
private List<FileSet> filesets = new ArrayList<>();
@Override
public void execute() throws BuildException {
ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(CPDTask.class.getClassLoader());
try {
validateFields();
log("Starting run, minimumTokenCount is " + minimumTokenCount, Project.MSG_INFO);
log("Tokenizing files", Project.MSG_INFO);
CPDConfiguration config = new CPDConfiguration();
config.setMinimumTileSize(minimumTokenCount);
config.setLanguage(createLanguage());
config.setSourceEncoding(encoding);
config.setSkipDuplicates(skipDuplicateFiles);
config.setSkipLexicalErrors(skipLexicalErrors);
CPD cpd = new CPD(config);
tokenizeFiles(cpd);
log("Starting to analyze code", Project.MSG_INFO);
long timeTaken = analyzeCode(cpd);
log("Done analyzing code; that took " + timeTaken + " milliseconds");
log("Generating report", Project.MSG_INFO);
report(cpd);
} catch (IOException ioe) {
log(ioe.toString(), Project.MSG_ERR);
throw new BuildException("IOException during task execution", ioe);
} catch (ReportException re) {
re.printStackTrace();
log(re.toString(), Project.MSG_ERR);
throw new BuildException("ReportException during task execution", re);
} finally {
Thread.currentThread().setContextClassLoader(oldClassloader);
}
}
private Language createLanguage() {
Properties p = new Properties();
if (ignoreLiterals) {
p.setProperty(Tokenizer.IGNORE_LITERALS, "true");
}
if (ignoreIdentifiers) {
p.setProperty(Tokenizer.IGNORE_IDENTIFIERS, "true");
}
if (ignoreAnnotations) {
p.setProperty(Tokenizer.IGNORE_ANNOTATIONS, "true");
}
if (ignoreUsings) {
p.setProperty(Tokenizer.IGNORE_USINGS, "true");
}
p.setProperty(Tokenizer.OPTION_SKIP_BLOCKS, Boolean.toString(skipBlocks));
p.setProperty(Tokenizer.OPTION_SKIP_BLOCKS_PATTERN, skipBlocksPattern);
return LanguageFactory.createLanguage(language, p);
}
private void report(CPD cpd) throws ReportException {
if (!cpd.getMatches().hasNext()) {
log("No duplicates over " + minimumTokenCount + " tokens found", Project.MSG_INFO);
}
CPDReportRenderer renderer = createRenderer();
CPDReport report = cpd.toReport();
try {
// will be closed via BufferedWriter/OutputStreamWriter chain down below
final OutputStream os;
if (outputFile == null) {
os = System.out;
} else if (outputFile.isAbsolute()) {
os = Files.newOutputStream(outputFile.toPath());
} else {
os = Files.newOutputStream(new File(getProject().getBaseDir(), outputFile.toString()).toPath());
}
if (encoding == null) {
encoding = System.getProperty("file.encoding");
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(os, encoding))) {
renderer.render(report, writer);
}
} catch (IOException ioe) {
throw new ReportException(ioe);
}
}
private void tokenizeFiles(CPD cpd) throws IOException {
for (FileSet fileSet : filesets) {
DirectoryScanner directoryScanner = fileSet.getDirectoryScanner(getProject());
String[] includedFiles = directoryScanner.getIncludedFiles();
for (int i = 0; i < includedFiles.length; i++) {
File file = new File(
directoryScanner.getBasedir() + System.getProperty("file.separator") + includedFiles[i]);
log("Tokenizing " + file.getAbsolutePath(), Project.MSG_VERBOSE);
cpd.add(file);
}
}
}
private long analyzeCode(CPD cpd) {
long start = System.currentTimeMillis();
cpd.go();
long stop = System.currentTimeMillis();
return stop - start;
}
private CPDReportRenderer createRenderer() {
if (TEXT_FORMAT.equals(format)) {
return new SimpleRenderer();
} else if (CSV_FORMAT.equals(format)) {
return new CSVRenderer();
}
return new XMLRenderer();
}
private void validateFields() throws BuildException {
if (minimumTokenCount == 0) {
throw new BuildException("minimumTokenCount is required and must be greater than zero");
}
if (filesets.isEmpty()) {
throw new BuildException("Must include at least one FileSet");
}
if (!Arrays.asList(LanguageFactory.supportedLanguages).contains(language)) {
throw new BuildException("Language " + language + " is not supported. Available languages: "
+ Arrays.toString(LanguageFactory.supportedLanguages));
}
}
public void addFileset(FileSet set) {
filesets.add(set);
}
public void setMinimumTokenCount(int minimumTokenCount) {
this.minimumTokenCount = minimumTokenCount;
}
public void setIgnoreLiterals(boolean value) {
this.ignoreLiterals = value;
}
public void setIgnoreIdentifiers(boolean value) {
this.ignoreIdentifiers = value;
}
public void setIgnoreAnnotations(boolean value) {
this.ignoreAnnotations = value;
}
public void setIgnoreUsings(boolean value) {
this.ignoreUsings = value;
}
public void setSkipLexicalErrors(boolean skipLexicalErrors) {
this.skipLexicalErrors = skipLexicalErrors;
}
public void setSkipDuplicateFiles(boolean skipDuplicateFiles) {
this.skipDuplicateFiles = skipDuplicateFiles;
}
public void setOutputFile(File outputFile) {
this.outputFile = outputFile;
}
public void setFormat(FormatAttribute formatAttribute) {
this.format = formatAttribute.getValue();
}
public void setLanguage(String language) {
this.language = language;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setSkipBlocks(boolean skipBlocks) {
this.skipBlocks = skipBlocks;
}
public void setSkipBlocksPattern(String skipBlocksPattern) {
this.skipBlocksPattern = skipBlocksPattern;
}
public static class FormatAttribute extends EnumeratedAttribute {
private static final String[] FORMATS = new String[] { XML_FORMAT, TEXT_FORMAT, CSV_FORMAT };
@Override
public String[] getValues() {
return FORMATS;
}
}
}
| 9,738 | 33.90681 | 113 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/Slf4jSimpleConfigurationForAnt.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant.internal;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.XmlLogger;
import org.apache.tools.ant.taskdefs.RecorderEntry;
import org.slf4j.event.Level;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
public final class Slf4jSimpleConfigurationForAnt {
private Slf4jSimpleConfigurationForAnt() { }
private static final Level DEFAULT_LEVEL = Level.INFO;
// Maps from ant's Project.MSG_* to org.slf4j.event.Level
private static final Level[] LOG_LEVELS = {
Level.ERROR, // Project.MSG_ERR=0
Level.WARN, // Project.MSG_WARN=1
Level.INFO, // Project.MSG_INFO=2
Level.DEBUG, // Project.MSG_VERBOSE=3
Level.TRACE, // Project.MSG_DEBUG=4
};
@SuppressWarnings("PMD.CloseResource")
public static Level reconfigureLoggingForAnt(Project antProject) {
if (!Slf4jSimpleConfiguration.isSimpleLogger()) {
// do nothing, not even set system properties, if not Simple Logger is in use
return DEFAULT_LEVEL;
}
PrintStream original = System.err;
try {
System.setErr(new SimpleLoggerToAntBridge(antProject, original));
// configuring the format so that the log level appears at the beginning of the printed line
System.setProperty("org.slf4j.simpleLogger.showDateTime", "false");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
System.setProperty("org.slf4j.simpleLogger.showThreadId", "false");
System.setProperty("org.slf4j.simpleLogger.levelInBrackets", "false");
// using cacheOutputStream so that we can restore System.err after SimpleLogger has been initialized
System.setProperty("org.slf4j.simpleLogger.cacheOutputStream", "true");
System.setProperty("org.slf4j.simpleLogger.logFile", "System.err");
Level level = getAntLogLevel(antProject);
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(level);
return level;
} finally {
System.setErr(original);
}
}
private static final class SimpleLoggerToAntBridge extends PrintStream {
private static final Map<String, Integer> ANT_LOG_LEVELS;
static {
ANT_LOG_LEVELS = new HashMap<>();
ANT_LOG_LEVELS.put(Level.ERROR.name(), Project.MSG_ERR);
ANT_LOG_LEVELS.put(Level.WARN.name(), Project.MSG_WARN);
ANT_LOG_LEVELS.put(Level.INFO.name(), Project.MSG_INFO);
ANT_LOG_LEVELS.put(Level.DEBUG.name(), Project.MSG_VERBOSE);
ANT_LOG_LEVELS.put(Level.TRACE.name(), Project.MSG_DEBUG);
}
private final StringBuilder buffer = new StringBuilder(100);
private final Project antProject;
SimpleLoggerToAntBridge(Project antProject, PrintStream original) {
super(original);
this.antProject = antProject;
}
@Override
public void println(String x) {
buffer.append(x).append(System.lineSeparator());
}
@Override
public void flush() {
String logLevel = determineLogLevel();
int antLogLevel = ANT_LOG_LEVELS.getOrDefault(logLevel, Project.MSG_INFO);
antProject.log(buffer.toString(), antLogLevel);
buffer.setLength(0);
}
private String determineLogLevel() {
int firstSpace = buffer.indexOf(" ");
if (firstSpace != -1) {
String level = buffer.substring(0, firstSpace);
buffer.delete(0, firstSpace + 1);
return level;
}
return DEFAULT_LEVEL.name();
}
}
@SuppressWarnings("PMD.AvoidAccessibilityAlteration")
private static Level getAntLogLevel(Project project) {
for (final BuildListener l : project.getBuildListeners()) {
Field declaredField = null;
try {
if (l instanceof DefaultLogger) {
declaredField = DefaultLogger.class.getDeclaredField("msgOutputLevel");
} else if (l instanceof XmlLogger) {
declaredField = XmlLogger.class.getDeclaredField("msgOutputLevel");
} else if (l instanceof RecorderEntry) {
declaredField = RecorderEntry.class.getDeclaredField("loglevel");
} else if ("org.gradle.api.internal.project.ant.AntLoggingAdapter".equals(l.getClass().getName())) {
return determineGradleLogLevel(project, l);
} else {
try {
declaredField = l.getClass().getDeclaredField("logLevel");
if (declaredField.getType() != Integer.class && declaredField.getType() != int.class) {
declaredField = null;
project.log("Unsupported build listener: " + l.getClass(), Project.MSG_DEBUG);
}
} catch (final NoSuchFieldException e) {
project.log("Unsupported build listener: " + l.getClass(), Project.MSG_DEBUG);
}
}
if (declaredField != null) {
declaredField.setAccessible(true);
return LOG_LEVELS[declaredField.getInt(l)];
}
} catch (final ReflectiveOperationException ignored) {
// Just ignore it
}
}
project.log("Could not determine ant log level, no supported build listeners found. "
+ "Log level is set to " + DEFAULT_LEVEL, Project.MSG_WARN);
return DEFAULT_LEVEL;
}
@SuppressWarnings("PMD.AvoidAccessibilityAlteration")
private static Level determineGradleLogLevel(Project project, BuildListener l) {
try {
project.log("Detected gradle AntLoggingAdapter", Project.MSG_DEBUG);
Field loggerField = l.getClass().getDeclaredField("logger");
loggerField.setAccessible(true);
// org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger
Object logger = loggerField.get(l);
Class<?> gradleLogLevel = l.getClass().getClassLoader().loadClass("org.gradle.api.logging.LogLevel");
Method isLevelAtMostMethod = logger.getClass().getDeclaredMethod("isLevelAtMost", gradleLogLevel);
isLevelAtMostMethod.setAccessible(true);
Object[] logLevels = gradleLogLevel.getEnumConstants();
// the log levels in gradle are declared in the order DEBUG, INFO, LIFECYCLE, WARN, QUIET, ERROR
Level[] mapping = new Level[] {
Level.TRACE, // DEBUG
Level.DEBUG, // INFO
Level.INFO, // LIFECYCLE
Level.WARN, // WARN
Level.ERROR, // QUIET
Level.ERROR, // ERROR
};
for (int i = 0; i < Math.min(logLevels.length, mapping.length); i++) {
boolean enabled = (boolean) isLevelAtMostMethod.invoke(logger, logLevels[i]);
if (enabled) {
project.log("Current log level: " + logLevels[i] + " -> " + mapping[i], Project.MSG_DEBUG);
return mapping[i];
}
}
} catch (ReflectiveOperationException ignored) {
// ignored
}
project.log("Could not determine log level, falling back to default: " + DEFAULT_LEVEL, Project.MSG_WARN);
return DEFAULT_LEVEL;
}
}
| 7,955 | 40.65445 | 116 | java |
pmd | pmd-master/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.ant.Formatter;
import net.sourceforge.pmd.ant.PMDTask;
import net.sourceforge.pmd.ant.SourceLanguage;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.internal.util.ClasspathClassLoader;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
import net.sourceforge.pmd.reporting.ReportStats;
import net.sourceforge.pmd.reporting.ReportStatsListener;
public class PMDTaskImpl {
private Path classpath;
private Path auxClasspath;
private final List<Formatter> formatters = new ArrayList<>();
private final List<FileSet> filesets = new ArrayList<>();
private final PMDConfiguration configuration = new PMDConfiguration();
private boolean failOnError;
private boolean failOnRuleViolation;
private int maxRuleViolations = 0;
private String failuresPropertyName;
private Project project;
public PMDTaskImpl(PMDTask task) {
configuration.addRelativizeRoots(task.getRelativizeRoots());
if (task.getSuppressMarker() != null) {
configuration.setSuppressMarker(task.getSuppressMarker());
}
this.failOnError = task.isFailOnError();
this.failOnRuleViolation = task.isFailOnRuleViolation();
this.maxRuleViolations = task.getMaxRuleViolations();
if (this.maxRuleViolations > 0) {
this.failOnRuleViolation = true;
}
if (task.getRulesetFiles() != null) {
configuration.setRuleSets(Arrays.asList(task.getRulesetFiles().split(",")));
}
configuration.setRuleSetFactoryCompatibilityEnabled(!task.isNoRuleSetCompatibility());
if (task.getEncoding() != null) {
configuration.setSourceEncoding(task.getEncoding());
}
configuration.setThreads(task.getThreads());
this.failuresPropertyName = task.getFailuresPropertyName();
configuration.setMinimumPriority(RulePriority.valueOf(task.getMinimumPriority()));
configuration.setAnalysisCacheLocation(task.getCacheLocation());
configuration.setIgnoreIncrementalAnalysis(task.isNoCache());
SourceLanguage version = task.getSourceLanguage();
if (version != null) {
Language lang = LanguageRegistry.PMD.getLanguageById(version.getName());
LanguageVersion languageVersion = lang == null ? null : lang.getVersion(version.getVersion());
if (languageVersion == null) {
throw new BuildException("The following language is not supported:" + version + '.');
}
configuration.setDefaultLanguageVersion(languageVersion);
}
classpath = task.getClasspath();
auxClasspath = task.getAuxClasspath();
filesets.addAll(task.getFilesets());
formatters.addAll(task.getFormatters());
project = task.getProject();
}
private void doTask() {
setupClassLoader();
if (configuration.getSuppressMarker() != null) {
project.log("Setting suppress marker to be " + configuration.getSuppressMarker(), Project.MSG_VERBOSE);
}
List<String> ruleSetPaths = expandRuleSetPaths(configuration.getRuleSetPaths());
// don't let PmdAnalysis.create create rulesets itself.
configuration.setRuleSets(Collections.emptyList());
ReportStats stats;
try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) {
RuleSetLoader rulesetLoader =
pmd.newRuleSetLoader().loadResourcesWith(setupResourceLoader());
pmd.addRuleSets(rulesetLoader.loadRuleSetsWithoutException(ruleSetPaths));
for (FileSet fileset : filesets) {
DirectoryScanner ds = fileset.getDirectoryScanner(project);
for (String srcFile : ds.getIncludedFiles()) {
pmd.files().addFile(ds.getBasedir().toPath().resolve(srcFile));
}
}
@SuppressWarnings("PMD.CloseResource")
ReportStatsListener reportStatsListener = new ReportStatsListener();
pmd.addListener(getListener(reportStatsListener));
pmd.performAnalysis();
stats = reportStatsListener.getResult();
if (failOnError && pmd.getReporter().numErrors() > 0) {
throw new BuildException("Some errors occurred while running PMD");
}
}
int problemCount = stats.getNumViolations();
project.log(problemCount + " problems found", Project.MSG_VERBOSE);
if (failuresPropertyName != null && problemCount > 0) {
project.setProperty(failuresPropertyName, String.valueOf(problemCount));
project.log("Setting property " + failuresPropertyName + " to " + problemCount, Project.MSG_VERBOSE);
}
if (failOnRuleViolation && problemCount > maxRuleViolations) {
throw new BuildException("Stopping build since PMD found " + problemCount + " rule violations in the code");
}
}
private List<String> expandRuleSetPaths(List<String> ruleSetPaths) {
List<String> paths = new ArrayList<>(ruleSetPaths);
for (int i = 0; i < paths.size(); i++) {
paths.set(i, project.replaceProperties(paths.get(i)));
}
return paths;
}
private @NonNull GlobalAnalysisListener getListener(ReportStatsListener reportSizeListener) {
List<GlobalAnalysisListener> renderers = new ArrayList<>(formatters.size() + 1);
try {
renderers.add(makeLogListener());
renderers.add(reportSizeListener);
for (Formatter formatter : formatters) {
project.log("Sending a report to " + formatter, Project.MSG_VERBOSE);
renderers.add(formatter.newListener(project));
}
return GlobalAnalysisListener.tee(renderers);
} catch (Exception e) {
// close those opened so far
Exception e2 = IOUtil.closeAll(renderers);
if (e2 != null) {
e.addSuppressed(e2);
}
throw new BuildException("Exception while initializing renderers", e);
}
}
private GlobalAnalysisListener makeLogListener() {
return new GlobalAnalysisListener() {
@Override
public FileAnalysisListener startFileAnalysis(TextFile dataSource) {
String name = dataSource.getFileId().getUriString();
project.log("Processing file " + name, Project.MSG_VERBOSE);
return FileAnalysisListener.noop();
}
@Override
public void close() {
// nothing to do
}
};
}
private ClassLoader setupResourceLoader() {
if (classpath == null) {
classpath = new Path(project);
}
/*
* 'basedir' is added to the path to make sure that relative paths such
* as "<ruleset>resources/custom_ruleset.xml</ruleset>" still work when
* ant is invoked from a different directory using "-f"
*/
classpath.add(new Path(null, project.getBaseDir().toString()));
project.log("Using the AntClassLoader: " + classpath, Project.MSG_VERBOSE);
// must be true, otherwise you'll get ClassCastExceptions as classes
// are loaded twice
// and exist in multiple class loaders
final boolean parentFirst = true;
return new AntClassLoader(Thread.currentThread().getContextClassLoader(),
project, classpath, parentFirst);
}
private void setupClassLoader() {
try {
if (auxClasspath != null) {
project.log("Using auxclasspath: " + auxClasspath, Project.MSG_VERBOSE);
configuration.prependAuxClasspath(auxClasspath.toString());
}
} catch (IllegalArgumentException ioe) {
throw new BuildException(ioe.getMessage(), ioe);
}
}
public void execute() throws BuildException {
Level level = Slf4jSimpleConfigurationForAnt.reconfigureLoggingForAnt(project);
Slf4jSimpleConfiguration.installJulBridge();
// need to reload the logger with the new configuration
Logger log = LoggerFactory.getLogger(PMDTaskImpl.class);
log.info("Logging is at {}", level);
try {
doTask();
} finally {
// only close the classloader, if it is ours. Otherwise we end up with class not found
// exceptions
if (configuration.getClassLoader() instanceof ClasspathClassLoader) {
IOUtil.tryCloseClassLoader(configuration.getClassLoader());
}
}
}
}
| 9,848 | 39.530864 | 120 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/RuleSetFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
// no additional tests yet
}
| 280 | 22.416667 | 79 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/LanguageVersionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
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(HtmlLanguageModule.NAME, HtmlLanguageModule.TERSE_NAME, "5",
getLanguage(HtmlLanguageModule.NAME).getDefaultVersion()));
}
}
| 545 | 27.736842 | 108 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/HtmlXPathRuleTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlComment;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlDocument;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlTextNode;
import net.sourceforge.pmd.lang.html.ast.HtmlParsingHelper;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
class HtmlXPathRuleTest {
// from https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_props_getter
private static final String LIGHTNING_WEB_COMPONENT = "<!-- helloExpressions.html -->\n"
+ "<template>\n"
+ " <p>Hello, { greeting}!</p>\n"
+ " <lightning-input label=\"Name\" value={ greeting} onchange={handleChange}></lightning-input>\n"
+ " <div class=\"slds-m-around_medium\">\n"
+ " <lightning-input name='firstName' label=\"First Name\" onchange={ handleChange}></lightning-input>\n"
+ " <lightning-input name='lastName' label=\"Last Name\" onchange={handleChange}></lightning-input>\n"
+ " <p class=\"slds-m-top_medium\">Uppercased Full Name: {uppercasedFullName}</p>\n"
+ " </div>\n"
+ " <template if:true={visible}>\n"
+ " <p>Test</p>\n"
+ " </template>\n"
+ "</template>";
@Test
void selectTextNode() {
// from https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_props_getter
// "Don’t add spaces around the property, for example, { data } is not valid HTML."
String xpath = "//text()[contains(., '{ ')]";
List<RuleViolation> violations = runXPath(LIGHTNING_WEB_COMPONENT, xpath);
assertEquals(1, violations.size());
assertEquals(3, violations.get(0).getBeginLine());
}
@Test
void selectTextNodeByNodeNameShouldNotWork() {
String xpath = "//*[local-name() = '#text']";
List<RuleViolation> violations = runXPath(LIGHTNING_WEB_COMPONENT, xpath);
assertEquals(0, violations.size());
}
@Test
void verifyTextNodeName() {
ASTHtmlDocument document = HtmlParsingHelper.DEFAULT.parse("<p>foobar</p>");
ASTHtmlTextNode textNode = document.getFirstDescendantOfType(ASTHtmlTextNode.class);
assertEquals("#text", textNode.getXPathNodeName());
}
@Test
void verifyCommentNodeName() {
ASTHtmlDocument document = HtmlParsingHelper.DEFAULT.parse("<p><!-- a comment --></p>");
ASTHtmlComment comment = document.getFirstDescendantOfType(ASTHtmlComment.class);
assertEquals("#comment", comment.getXPathNodeName());
}
@Test
void selectAttributes() {
// from https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_props_getter
// "Don’t add spaces around the property, for example, { data } is not valid HTML."
String xpath = "//*[@value = '{']";
List<RuleViolation> violations = runXPath(LIGHTNING_WEB_COMPONENT, xpath);
assertEquals(1, violations.size());
assertEquals(4, violations.get(0).getBeginLine());
}
@Test
void selectAttributesMultiple() {
// from https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_props_getter
// "Don’t add spaces around the property, for example, { data } is not valid HTML."
String xpath = "//*[@*[local-name() = ('value', 'onchange')] = '{']";
List<RuleViolation> violations = runXPath(LIGHTNING_WEB_COMPONENT, xpath);
assertEquals(2, violations.size());
assertEquals(4, violations.get(0).getBeginLine());
assertEquals(6, violations.get(1).getBeginLine());
}
@Test
void selectAttributeByName() {
String xpath = "//*[@*[local-name() = 'if:true']]";
List<RuleViolation> violations = runXPath(LIGHTNING_WEB_COMPONENT, xpath);
assertEquals(1, violations.size());
assertEquals(10, violations.get(0).getBeginLine());
}
private List<RuleViolation> runXPath(String html, String xpath) {
XPathRule rule = new XPathRule(XPathVersion.DEFAULT, xpath);
rule.setMessage("test");
rule.setLanguage(HtmlParsingHelper.DEFAULT.getLanguage());
Report report = HtmlParsingHelper.DEFAULT.executeRule(rule, html);
return report.getViolations();
}
}
| 4,734 | 41.657658 | 124 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/HtmlTokenizerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
import net.sourceforge.pmd.lang.html.ast.HtmlTokenizer;
class HtmlTokenizerTest extends CpdTextComparisonTest {
HtmlTokenizerTest() {
super(".html");
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new HtmlTokenizer();
}
@Override
protected String getResourcePrefix() {
return "cpd";
}
@Test
void testSimpleHtmlFile() {
doTest("SimpleHtmlFile");
}
}
| 754 | 18.868421 | 79 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/HtmlJavaRuleTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlElement;
import net.sourceforge.pmd.lang.html.rule.AbstractHtmlRule;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
class HtmlJavaRuleTest {
// from https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_props_getter
private static final String LIGHTNING_WEB_COMPONENT = "<!-- helloExpressions.html -->\n"
+ "<template>\n"
+ " <p>Hello, { greeting}!</p>\n"
+ " <lightning-input label=\"Name\" value={ greeting} onchange=\"{ handleChange }\"></lightning-input>\n"
+ " <div class=\"slds-m-around_medium\">\n"
+ " <lightning-input name='firstName' label=\"First Name\" onchange={ handleChange }></lightning-input>\n"
+ " <lightning-input name='lastName' label=\"Last Name\" onchange={handleChange}></lightning-input>\n"
+ " <p class=\"slds-m-top_medium\">Uppercased Full Name: {uppercasedFullName}</p>\n"
+ " </div>\n"
+ "</template>";
@Test
void findAllAttributesWithInvalidExpression() {
// "Don’t add spaces around the property, for example, { data } is not valid HTML."
Rule rule = new AbstractHtmlRule() {
@Override
public String getMessage() {
return "Invalid expression";
}
@Override
public Object visit(ASTHtmlElement node, Object data) {
for (Attribute attribute : node.getAttributes()) {
if ("{".equals(attribute.getValue())) {
RuleContext ctx = (RuleContext) data;
ctx.addViolation(node);
}
}
return super.visit(node, data);
}
};
rule.setLanguage(HtmlParsingHelper.DEFAULT.getLanguage());
List<RuleViolation> violations = runRule(LIGHTNING_WEB_COMPONENT, rule);
assertEquals(2, violations.size());
assertEquals(4, violations.get(0).getBeginLine());
assertEquals(6, violations.get(1).getBeginLine());
}
private List<RuleViolation> runRule(String html, Rule rule) {
Report report = HtmlParsingHelper.DEFAULT.executeRule(rule, html);
return report.getViolations();
}
}
| 2,735 | 40.454545 | 125 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/HtmlParsingHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlDocument;
public class HtmlParsingHelper extends BaseParsingHelper<HtmlParsingHelper, ASTHtmlDocument> {
public static final HtmlParsingHelper DEFAULT = new HtmlParsingHelper(Params.getDefault());
public HtmlParsingHelper(BaseParsingHelper.Params params) {
super(HtmlLanguageModule.NAME, ASTHtmlDocument.class, params);
}
@Override
protected @NonNull HtmlParsingHelper clone(@NonNull Params params) {
return new HtmlParsingHelper(params);
}
}
| 783 | 30.36 | 95 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/ast/HtmlTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
class HtmlTreeDumpTest extends BaseTreeDumpTest {
HtmlTreeDumpTest() {
super(new RelevantAttributePrinter(), ".html");
}
@Override
public BaseParsingHelper<HtmlParsingHelper, ASTHtmlDocument> getParser() {
return HtmlParsingHelper.DEFAULT.withResourceContext(HtmlTreeDumpTest.class, "testdata");
}
@Test
void simpleHtmlFile() {
doTest("SimpleHtmlFile");
}
@Test
void templateFragment() {
doTest("TemplateFragment");
}
@Test
void simpleXmlFile() {
doTest("SimpleXmlFile");
}
}
| 932 | 22.923077 | 97 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/ast/PositionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.CoordinatesPrinter;
class PositionTest extends BaseTreeDumpTest {
PositionTest() {
super(CoordinatesPrinter.INSTANCE, ".html");
}
@Override
public BaseParsingHelper<HtmlParsingHelper, ASTHtmlDocument> getParser() {
return HtmlParsingHelper.DEFAULT.withResourceContext(HtmlTreeDumpTest.class, "testdata");
}
@Test
void testPositions() {
doTest("SimpleHtmlFile2");
}
}
| 754 | 25.964286 | 97 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/ast/HtmlParsingHelper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.html.HtmlLanguageModule;
public final class HtmlParsingHelper extends BaseParsingHelper<HtmlParsingHelper, ASTHtmlDocument> {
public static final HtmlParsingHelper DEFAULT = new HtmlParsingHelper(Params.getDefault());
private HtmlParsingHelper(Params params) {
super(HtmlLanguageModule.NAME, ASTHtmlDocument.class, params);
}
@Override
protected HtmlParsingHelper clone(Params params) {
return new HtmlParsingHelper(params);
}
}
| 698 | 29.391304 | 100 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/rule/bestpractices/UseAltAttributeForImagesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UseAltAttributeForImagesTest extends PmdRuleTst {
// no additional unit tests
}
| 291 | 23.333333 | 79 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/rule/bestpractices/UnnecessaryTypeAttributeTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UnnecessaryTypeAttributeTest extends PmdRuleTst {
// no additional unit tests
}
| 291 | 23.333333 | 79 | java |
pmd | pmd-master/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/rule/bestpractices/AvoidInlineStylesTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidInlineStylesTest extends PmdRuleTst {
// no additional unit tests
}
| 285 | 22.833333 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
@net.sourceforge.pmd.annotation.Experimental
package net.sourceforge.pmd.lang.html;
| 172 | 23.714286 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/HtmlCpdLanguage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import net.sourceforge.pmd.cpd.AbstractLanguage;
import net.sourceforge.pmd.lang.html.ast.HtmlTokenizer;
public final class HtmlCpdLanguage extends AbstractLanguage {
public HtmlCpdLanguage() {
super(HtmlLanguageModule.NAME, HtmlLanguageModule.TERSE_NAME, new HtmlTokenizer(), HtmlLanguageModule.EXTENSIONS);
}
}
| 460 | 26.117647 | 122 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/HtmlLanguageModule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.List;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
public final class HtmlLanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "HTML";
public static final String TERSE_NAME = "html";
@InternalApi
public static final List<String> EXTENSIONS = listOf("html", "htm", "xhtml", "xht", "shtml");
public HtmlLanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME)
.extensions(EXTENSIONS)
.addVersion("4")
.addDefaultVersion("5"),
new HtmlHandler());
}
public static HtmlLanguageModule getInstance() {
return (HtmlLanguageModule) LanguageRegistry.PMD.getLanguageById(TERSE_NAME);
}
}
| 1,107 | 31.588235 | 97 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/HtmlHandler.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html;
import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.html.ast.HtmlParser;
class HtmlHandler extends AbstractPmdLanguageVersionHandler {
@Override
public Parser getParser() {
return new HtmlParser();
}
}
| 445 | 21.3 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import net.sourceforge.pmd.lang.ast.AstVisitor;
public interface HtmlVisitor<P, R> extends AstVisitor<P, R> {
/**
* The default visit method, to which other methods delegate.
*/
default R visitHtmlNode(HtmlNode node, P data) {
return visitNode(node, data);
}
default R visit(ASTHtmlCDataNode node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlComment node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlDocument node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlDocumentType node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlElement node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlTextNode node, P data) {
return visitHtmlNode(node, data);
}
default R visit(ASTHtmlXmlDeclaration node, P data) {
return visitHtmlNode(node, data);
}
}
| 1,141 | 23.826087 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlComment.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.Comment;
public final class ASTHtmlComment extends AbstractHtmlNode<Comment> {
ASTHtmlComment(Comment node) {
super(node);
}
public String getData() {
return node.getData();
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 528 | 20.16 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlCDataNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.CDataNode;
public final class ASTHtmlCDataNode extends AbstractHtmlNode<CDataNode> {
ASTHtmlCDataNode(CDataNode node) {
super(node);
}
public String getText() {
return node.text();
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 535 | 20.44 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlXmlDeclaration.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.XmlDeclaration;
public final class ASTHtmlXmlDeclaration extends AbstractHtmlNode<XmlDeclaration> {
ASTHtmlXmlDeclaration(XmlDeclaration node) {
super(node);
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public String getName() {
return node.name();
}
}
| 560 | 21.44 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/AbstractHtmlNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.Node;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.AbstractNode;
import net.sourceforge.pmd.lang.document.TextRegion;
abstract class AbstractHtmlNode<T extends Node> extends AbstractNode<AbstractHtmlNode<?>, HtmlNode> implements HtmlNode {
protected final T node;
protected int startOffset;
protected int endOffset;
AbstractHtmlNode(T node) {
this.node = node;
}
public String getNodeName() {
return node.nodeName();
}
@Override
public String getXPathNodeName() {
return node.nodeName();
}
@Override
public TextRegion getTextRegion() {
return TextRegion.fromBothOffsets(startOffset, endOffset);
}
@Override
@SuppressWarnings("unchecked")
public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof HtmlVisitor) {
return this.acceptHtmlVisitor((HtmlVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
protected abstract <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data);
// overridden to make them visible
@Override
protected void addChild(AbstractHtmlNode<?> child, int index) {
super.addChild(child, index);
}
}
| 1,512 | 26.017857 | 121 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlDocumentType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.DocumentType;
public final class ASTHtmlDocumentType extends AbstractHtmlNode<DocumentType> {
ASTHtmlDocumentType(DocumentType node) {
super(node);
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public String getName() {
return node.name();
}
public String getPublicId() {
return node.publicId();
}
public String getSystemId() {
return node.systemId();
}
}
| 696 | 20.121212 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlElement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jsoup.nodes.Element;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
public class ASTHtmlElement extends AbstractHtmlNode<Element> {
private final List<Attribute> attributes;
ASTHtmlElement(Element element) {
super(element);
attributes = new ArrayList<>();
for (org.jsoup.nodes.Attribute att : node.attributes()) {
attributes.add(new Attribute(this, att.getKey(), att.getValue()));
}
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public List<Attribute> getAttributes() {
return attributes;
}
public boolean hasAttribute(String name) {
return attributes.stream().anyMatch(attribute -> name.equalsIgnoreCase(attribute.getName()));
}
public String getAttribute(String rel) {
return attributes.stream()
.filter(attribute -> rel.equalsIgnoreCase(attribute.getName()))
.findFirst()
.map(Attribute::getValue)
.map(String::valueOf)
.orElse(null);
}
@Override
public Iterator<Attribute> getXPathAttributesIterator() {
Iterator<Attribute> defaultAttributes = super.getXPathAttributesIterator();
Iterator<Attribute> elementAttributes = attributes.iterator();
return new Iterator<Attribute>() {
@Override
public boolean hasNext() {
return defaultAttributes.hasNext() || elementAttributes.hasNext();
}
@Override
public Attribute next() {
if (defaultAttributes.hasNext()) {
return defaultAttributes.next();
}
return elementAttributes.next();
}
};
}
}
| 2,077 | 27.465753 | 101 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import net.sourceforge.pmd.lang.ast.impl.GenericNode;
public interface HtmlNode extends GenericNode<HtmlNode> {
}
| 248 | 19.75 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlDocument.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import java.util.Map;
import org.jsoup.nodes.Document;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.RootNode;
public final class ASTHtmlDocument extends ASTHtmlElement implements RootNode {
private final AstInfo<ASTHtmlDocument> astInfo;
ASTHtmlDocument(Document document,
Parser.ParserTask task,
Map<Integer, String> suppressMap) {
super(document);
this.astInfo = new AstInfo<>(task, this).withSuppressMap(suppressMap);
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
@Override
public AstInfo<ASTHtmlDocument> getAstInfo() {
return astInfo;
}
}
| 966 | 25.135135 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import java.io.IOException;
import java.io.UncheckedIOException;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.TokenEntry;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.Tokens;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.html.HtmlLanguageModule;
public class HtmlTokenizer implements Tokenizer {
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) {
HtmlLanguageModule html = HtmlLanguageModule.getInstance();
try (LanguageProcessor processor = html.createProcessor(html.newPropertyBundle());
TextFile tf = TextFile.forCharSeq(
sourceCode.getCodeBuffer(),
FileId.fromPathLikeString(sourceCode.getFileName()),
html.getDefaultVersion()
);
TextDocument textDoc = TextDocument.create(tf)) {
ParserTask task = new ParserTask(
textDoc,
SemanticErrorReporter.noop(),
LanguageProcessorRegistry.singleton(processor)
);
HtmlParser parser = new HtmlParser();
ASTHtmlDocument root = parser.parse(task);
traverse(root, tokenEntries);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tokenEntries.add(TokenEntry.EOF);
}
}
private void traverse(HtmlNode node, Tokens tokenEntries) {
String image = node.getXPathNodeName();
if (node instanceof ASTHtmlTextNode) {
image = ((ASTHtmlTextNode) node).getText();
}
TokenEntry token = new TokenEntry(image, node.getReportLocation());
tokenEntries.add(token);
for (HtmlNode child : node.children()) {
traverse(child, tokenEntries);
}
}
}
| 2,413 | 33 | 90 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTreeBuilder.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import java.util.Map;
import org.jsoup.nodes.CDataNode;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.nodes.XmlDeclaration;
import net.sourceforge.pmd.lang.ast.Parser;
final class HtmlTreeBuilder {
public ASTHtmlDocument build(Document doc,
Parser.ParserTask task,
Map<Integer, String> suppressMap) {
ASTHtmlDocument root = new ASTHtmlDocument(doc, task, suppressMap);
addChildren(root, doc);
LineNumbers lineNumbers = new LineNumbers(root);
lineNumbers.determine();
return root;
}
private void addChildren(AbstractHtmlNode<?> parent, Node node) {
for (Node child : node.childNodes()) {
AbstractHtmlNode<?> converted = convertJsoupNode(child);
parent.addChild(converted, parent.getNumChildren());
addChildren(converted, child);
}
}
private AbstractHtmlNode<? extends Node> convertJsoupNode(Node node) {
if (node instanceof Element) {
return new ASTHtmlElement((Element) node);
} else if (node instanceof CDataNode) {
return new ASTHtmlCDataNode((CDataNode) node);
} else if (node instanceof TextNode) {
return new ASTHtmlTextNode((TextNode) node);
} else if (node instanceof Comment) {
return new ASTHtmlComment((Comment) node);
} else if (node instanceof XmlDeclaration) {
return new ASTHtmlXmlDeclaration((XmlDeclaration) node);
} else if (node instanceof DocumentType) {
return new ASTHtmlDocumentType((DocumentType) node);
} else {
throw new RuntimeException("Unsupported node type: " + node.getClass());
}
}
}
| 2,057 | 32.737705 | 84 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/ASTHtmlTextNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import org.jsoup.nodes.TextNode;
public class ASTHtmlTextNode extends AbstractHtmlNode<TextNode> {
ASTHtmlTextNode(TextNode node) {
super(node);
}
@Override
protected <P, R> R acceptHtmlVisitor(HtmlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public String getNormalizedText() {
return node.text();
}
public String getText() {
return node.getWholeText();
}
@Override
public String getImage() {
return getNormalizedText();
}
}
| 695 | 19.470588 | 95 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import java.util.HashMap;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
public final class HtmlParser implements net.sourceforge.pmd.lang.ast.Parser {
@Override
public ASTHtmlDocument parse(ParserTask task) {
Document doc = Parser.xmlParser().parseInput(task.getTextDocument().getText().newReader(), "");
HtmlTreeBuilder builder = new HtmlTreeBuilder();
return builder.build(doc, task, new HashMap<>());
}
}
| 599 | 26.272727 | 103 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/LineNumbers.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.ast;
import net.sourceforge.pmd.lang.document.Chars;
class LineNumbers {
private final ASTHtmlDocument document;
private final Chars htmlString;
LineNumbers(ASTHtmlDocument document) {
this.document = document;
this.htmlString = document.getTextDocument().getText();
}
public void determine() {
determineLocation(document, 0);
}
private int determineLocation(AbstractHtmlNode<?> n, int index) {
int nextIndex = index;
int nodeLength = 0;
int textLength = 0;
if (n instanceof ASTHtmlDocument) {
nextIndex = index;
} else if (n instanceof ASTHtmlComment) {
nextIndex = htmlString.indexOf("<!--", nextIndex);
} else if (n instanceof ASTHtmlElement) {
nextIndex = htmlString.indexOf("<" + n.getXPathNodeName(), nextIndex);
nodeLength = htmlString.indexOf(">", nextIndex) - nextIndex + 1;
} else if (n instanceof ASTHtmlCDataNode) {
nextIndex = htmlString.indexOf("<![CDATA[", nextIndex);
} else if (n instanceof ASTHtmlXmlDeclaration) {
nextIndex = htmlString.indexOf("<?", nextIndex);
} else if (n instanceof ASTHtmlTextNode) {
textLength = ((ASTHtmlTextNode) n).getText().length();
} else if (n instanceof ASTHtmlDocumentType) {
nextIndex = index;
}
setBeginLocation(n, nextIndex);
nextIndex += nodeLength;
for (net.sourceforge.pmd.lang.ast.Node child : n.children()) {
nextIndex = determineLocation((AbstractHtmlNode<?>) child, nextIndex);
}
// autoclosing element, eg <a />
boolean isAutoClose = n.getNumChildren() == 0
&& n instanceof ASTHtmlElement
// nextIndex is up to the closing > at this point
&& htmlString.startsWith("/>", nextIndex - 2);
if (n instanceof ASTHtmlDocument) {
nextIndex = htmlString.length();
} else if (n instanceof ASTHtmlElement && !isAutoClose) {
nextIndex += 2 + n.getXPathNodeName().length() + 1; // </nodename>
} else if (n instanceof ASTHtmlComment) {
nextIndex += 4 + 3; // <!-- and -->
nextIndex += ((ASTHtmlComment) n).getData().length();
} else if (n instanceof ASTHtmlTextNode) {
nextIndex += textLength;
} else if (n instanceof ASTHtmlCDataNode) {
nextIndex += "<![CDATA[".length() + ((ASTHtmlCDataNode) n).getText().length() + "]]>".length();
} else if (n instanceof ASTHtmlXmlDeclaration) {
nextIndex = htmlString.indexOf("?>", nextIndex) + 2;
} else if (n instanceof ASTHtmlDocumentType) {
nextIndex = htmlString.indexOf(">", nextIndex) + 1;
}
setEndLocation(n, nextIndex - 1);
return nextIndex;
}
private void setBeginLocation(AbstractHtmlNode<?> n, int index) {
if (n != null) {
n.startOffset = index;
}
}
private void setEndLocation(AbstractHtmlNode<?> n, int index) {
if (n != null) {
n.endOffset = index;
}
}
}
| 3,295 | 34.826087 | 107 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/rule/AbstractHtmlRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.html.ast.HtmlVisitor;
import net.sourceforge.pmd.lang.rule.AbstractRule;
public abstract class AbstractHtmlRule extends AbstractRule implements HtmlVisitor {
@Override
public Object visitNode(Node node, Object param) {
node.children().forEach(c -> c.acceptVisitor(this, param));
return param;
}
@Override
public void apply(Node target, RuleContext ctx) {
target.acceptVisitor(this, ctx);
}
}
| 690 | 26.64 | 84 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/rule/bestpractices/UseAltAttributeForImagesRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule.bestpractices;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlElement;
import net.sourceforge.pmd.lang.html.rule.AbstractHtmlRule;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
public class UseAltAttributeForImagesRule extends AbstractHtmlRule {
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forXPathNames(Arrays.asList("img"));
}
@Override
public Object visit(ASTHtmlElement node, Object data) {
if (!node.hasAttribute("alt")) {
RuleContext ctx = (RuleContext) data;
ctx.addViolation(node);
return data;
}
return data;
}
}
| 942 | 26.735294 | 79 | java |
pmd | pmd-master/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/rule/bestpractices/UnnecessaryTypeAttributeRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.html.rule.bestpractices;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.html.ast.ASTHtmlElement;
import net.sourceforge.pmd.lang.html.rule.AbstractHtmlRule;
public class UnnecessaryTypeAttributeRule extends AbstractHtmlRule {
@Override
public Object visit(ASTHtmlElement node, Object data) {
if ("link".equalsIgnoreCase(node.getNodeName())) {
checkLink(node, data);
} else if ("script".equalsIgnoreCase(node.getNodeName())) {
checkScript(node, data);
}
return super.visit(node, data);
}
private void checkScript(ASTHtmlElement node, Object data) {
if (node.hasAttribute("type")) {
addViolation(node, data);
}
}
private void checkLink(ASTHtmlElement node, Object data) {
String rel = node.getAttribute("rel");
if (node.hasAttribute("type") && "stylesheet".equalsIgnoreCase(rel)) {
addViolation(node, data);
}
}
private void addViolation(ASTHtmlElement node, Object data) {
RuleContext ctx = (RuleContext) data;
ctx.addViolation(node);
}
}
| 1,263 | 29.095238 | 79 | java |
pmd | pmd-master/pmd-julia/src/test/java/net/sourceforge/pmd/cpd/JuliaTokenizerTest.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;
import net.sourceforge.pmd.lang.julia.cpd.JuliaTokenizer;
class JuliaTokenizerTest extends CpdTextComparisonTest {
JuliaTokenizerTest() {
super(".jl");
}
@Override
protected String getResourcePrefix() {
return "../lang/julia/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
JuliaTokenizer tok = new JuliaTokenizer();
return tok;
}
@Test
void testMathExample() {
doTest("mathExample");
}
}
| 757 | 20.657143 | 79 | java |
pmd | pmd-master/pmd-julia/src/main/java/net/sourceforge/pmd/lang/julia/ast/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Contains the Antlr grammar for Julia.
*/
package net.sourceforge.pmd.lang.julia.ast;
| 182 | 19.333333 | 79 | java |
pmd | pmd-master/pmd-julia/src/main/java/net/sourceforge/pmd/lang/julia/cpd/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Contains Julia tokenizer and language classes.
*/
package net.sourceforge.pmd.lang.julia.cpd;
| 191 | 20.333333 | 79 | java |
pmd | pmd-master/pmd-julia/src/main/java/net/sourceforge/pmd/lang/julia/cpd/JuliaLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.julia.cpd;
import net.sourceforge.pmd.cpd.AbstractLanguage;
/**
* Language implementation for Julia.
*/
public class JuliaLanguage extends AbstractLanguage {
/**
* Creates a new Julia Language instance.
*/
public JuliaLanguage() {
super("Julia", "julia", new JuliaTokenizer(), ".jl");
}
}
| 446 | 20.285714 | 79 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.