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-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/AbstractJspNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.AbstractJjtreeNode;
abstract class AbstractJspNode extends AbstractJjtreeNode<AbstractJspNode, JspNode> implements JspNode {
protected AbstractJspNode(int id) {
super(id);
}
@Override
@SuppressWarnings("unchecked")
public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof JspVisitor) {
return this.acceptVisitor((JspVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
protected abstract <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data);
@Override // override to make protected member accessible to parser
protected void setImage(String image) {
super.setImage(image);
}
@Override
public String getXPathNodeName() {
return JspParserImplTreeConstants.jjtNodeName[id];
}
}
| 1,139 | 29 | 104 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTJspExpression extends AbstractJspNode {
ASTJspExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 406 | 21.611111 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTAttribute.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTAttribute extends AbstractJspNode {
private String name;
ASTAttribute(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
/**
* @return boolean - true if the element has a namespace-prefix, false
* otherwise
*/
public boolean isHasNamespacePrefix() {
return name.indexOf(':') >= 0;
}
/**
* @return String - the part of the name that is before the (first) colon
* (":")
*/
public String getNamespacePrefix() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(0, colonIndex) : "";
}
/**
* @return String - The part of the name that is after the first colon
* (":"). If the name does not contain a colon, the full name is
* returned.
*/
public String getLocalName() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(colonIndex + 1) : name;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,380 | 24.109091 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspDirective.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTJspDirective extends AbstractJspNode {
/**
* Name of the element-tag. Cannot be null.
*/
private String name;
ASTJspDirective(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 617 | 18.935484 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspDirectiveAttribute.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTJspDirectiveAttribute extends AbstractJspNode {
private String name;
private String value;
ASTJspDirectiveAttribute(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
void setValue(String value) {
this.value = value;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 726 | 18.648649 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTUnparsedText.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTUnparsedText extends AbstractJspNode {
ASTUnparsedText(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 404 | 21.5 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspScriptlet.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTJspScriptlet extends AbstractJspNode {
ASTJspScriptlet(int id) {
super(id);
}
@Override
public <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 401 | 21.333333 | 87 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTAttributeValue.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTAttributeValue extends AbstractJspNode {
ASTAttributeValue(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 408 | 21.722222 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTDoctypeExternalId.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTDoctypeExternalId extends AbstractJspNode {
/**
* URI of the external entity. Cannot be null.
*/
private String uri;
/**
* Public ID of the external entity. This is optional.
*/
private String publicId;
ASTDoctypeExternalId(int id) {
super(id);
}
public boolean isHasPublicId() {
return null != publicId;
}
public String getUri() {
return uri;
}
void setUri(String uri) {
this.uri = uri;
}
/**
* @return Returns the publicId (or an empty string if there is none for
* this external entity id).
*/
public String getPublicId() {
return null == publicId ? "" : publicId;
}
void setPublicId(String publicId) {
this.publicId = publicId;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,110 | 20.365385 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTHtmlScript.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTHtmlScript extends AbstractJspNode {
ASTHtmlScript(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 400 | 21.277778 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTCData.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTCData extends AbstractJspNode {
ASTCData(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 390 | 20.722222 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTElement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTElement extends AbstractJspNode {
/**
* Name of the element-tag. Cannot be null.
*/
private String name;
/**
* Flag indicating that the element consists of one tag ("<... />").
*/
private boolean empty; //
/**
* Flag indicating that the parser did not find a proper ending marker or
* ending tag for this element.
*/
private boolean unclosed;
ASTElement(int id) {
super(id);
}
/**
* @return boolean - true if the element has a namespace-prefix, false
* otherwise
*/
public boolean isHasNamespacePrefix() {
return name.indexOf(':') >= 0;
}
/**
* @return String - the part of the name that is before the (first) colon
* (":")
*/
public String getNamespacePrefix() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(0, colonIndex) : "";
}
/**
* @return String - The part of the name that is after the first colon
* (":"). If the name does not contain a colon, the full name is
* returned.
*/
public String getLocalName() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(colonIndex + 1) : name;
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
public boolean isEmpty() {
return empty;
}
public boolean isUnclosed() {
return unclosed;
}
void setUnclosed(boolean unclosed) {
this.unclosed = unclosed;
}
void setEmpty(boolean empty) {
this.empty = empty;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,999 | 22.529412 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/JspParserVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Backwards-compatibility only.
*
* @deprecated Use {@link JspVisitor}
*/
@Deprecated
@DeprecatedUntil700
public interface JspParserVisitor extends JspVisitor<Object, Object> {
@Override
default Object visitNode(Node node, Object param) {
node.children().forEach(c -> c.acceptVisitor(this, param));
return param;
}
}
| 586 | 22.48 | 79 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTJspComment.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTJspComment extends AbstractJspNode {
ASTJspComment(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 400 | 21.277778 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTCommentTag.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
public final class ASTCommentTag extends AbstractJspNode {
ASTCommentTag(int id) {
super(id);
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 400 | 21.277778 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/ast/ASTCompilationUnit.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.ast;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
public final class ASTCompilationUnit extends AbstractJspNode implements RootNode {
private AstInfo<ASTCompilationUnit> astInfo;
ASTCompilationUnit(int id) {
super(id);
}
@Override
public AstInfo<ASTCompilationUnit> getAstInfo() {
return astInfo;
}
ASTCompilationUnit makeTaskInfo(ParserTask task) {
this.astInfo = new AstInfo<>(task, this);
return this;
}
@Override
protected <P, R> R acceptVisitor(JspVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 859 | 24.294118 | 90 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/rule/AbstractJspRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.jsp.ast.JspParserVisitor;
import net.sourceforge.pmd.lang.rule.AbstractRule;
public abstract class AbstractJspRule extends AbstractRule implements JspParserVisitor {
@Override
public void apply(Node target, RuleContext ctx) {
target.acceptVisitor(this, ctx);
}
}
| 531 | 27 | 88 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/rule/security/NoUnsanitizedJSPExpressionRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.rule.security;
import net.sourceforge.pmd.lang.jsp.ast.ASTElExpression;
import net.sourceforge.pmd.lang.jsp.ast.ASTElement;
import net.sourceforge.pmd.lang.jsp.rule.AbstractJspRule;
/**
* This rule detects unsanitized JSP Expressions (can lead to Cross Site
* Scripting (XSS) attacks)
*
* @author maxime_robert
*/
public class NoUnsanitizedJSPExpressionRule extends AbstractJspRule {
@Override
public Object visit(ASTElExpression node, Object data) {
if (elOutsideTaglib(node)) {
addViolation(data, node);
}
return super.visit(node, data);
}
private boolean elOutsideTaglib(ASTElExpression node) {
ASTElement parentASTElement = node.getFirstParentOfType(ASTElement.class);
boolean elInTaglib = parentASTElement != null && parentASTElement.getName() != null
&& parentASTElement.getName().contains(":");
boolean elWithFnEscapeXml = node.getImage() != null && node.getImage().matches("^fn:escapeXml\\(.+\\)$");
return !elInTaglib && !elWithFnEscapeXml;
}
}
| 1,197 | 29.717949 | 113 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/rule/codestyle/DuplicateJspImportsRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.rule.codestyle;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.jsp.ast.ASTJspDirectiveAttribute;
import net.sourceforge.pmd.lang.jsp.rule.AbstractJspRule;
public class DuplicateJspImportsRule extends AbstractJspRule {
private Set<String> imports = new HashSet<>();
@Override
public void start(RuleContext ctx) {
imports.clear();
}
@Override
public Object visit(ASTJspDirectiveAttribute node, Object data) {
if (!"import".equals(node.getName())) {
return super.visit(node, data);
}
String values = node.getValue();
StringTokenizer st = new StringTokenizer(values, ",");
int count = st.countTokens();
for (int ix = 0; ix < count; ix++) {
String token = st.nextToken();
if (imports.contains(token)) {
addViolation(data, node, node.getImage());
} else {
imports.add(token);
}
}
return super.visit(node, data);
}
}
| 1,242 | 26.622222 | 79 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/lang/jsp/rule/design/NoInlineStyleInformationRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.jsp.rule.design;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.Locale;
import java.util.Set;
import net.sourceforge.pmd.lang.jsp.ast.ASTAttribute;
import net.sourceforge.pmd.lang.jsp.ast.ASTElement;
import net.sourceforge.pmd.lang.jsp.rule.AbstractJspRule;
/**
* This rule checks that no "style" elements (like <B>, <FONT>, ...) are used,
* and that no "style" attributes (like "font", "size", "align") are used.
*
* @author pieter_van_raemdonck
*/
public class NoInlineStyleInformationRule extends AbstractJspRule {
// These lists should probably be extended
/**
* List of HTML element-names that define style.
*/
private static final Set<String> STYLE_ELEMENT_NAMES =
setOf("B", "I", "FONT", "BASEFONT", "U", "CENTER");
/**
* List of HTML element-names that can have attributes defining style.
*/
private static final Set<String> ELEMENT_NAMES_THAT_CAN_HAVE_STYLE_ATTRIBUTES =
setOf("P", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "TD", "COL", "COLGROUP");
/**
* List of attributes that define style when they are attributes of HTML
* elements with names in ELEMENT_NAMES_THAT_CAN_HAVE_STYLE_ATTRIBUTES.
*/
private static final Set<String> STYLE_ATTRIBUTES =
setOf("STYLE", "FONT", "SIZE", "COLOR", "FACE", "ALIGN", "VALIGN", "BGCOLOR");
@Override
public Object visit(ASTAttribute node, Object data) {
if (isStyleAttribute(node)) {
addViolation(data, node);
}
return super.visit(node, data);
}
@Override
public Object visit(ASTElement node, Object data) {
if (isStyleElement(node)) {
addViolation(data, node);
}
return super.visit(node, data);
}
/**
* Checks whether the name of the elementNode argument is one of
* STYLE_ELEMENT_NAMES.
*
* @param elementNode
* @return boolean
*/
private boolean isStyleElement(ASTElement elementNode) {
return STYLE_ELEMENT_NAMES.contains(elementNode.getName().toUpperCase(Locale.ROOT));
}
/**
* Checks whether the attributeNode argument is a style attribute of a HTML
* element that can have style attributes.
*
* @param attributeNode
* The attribute node.
* @return <code>true</code> if a style attribute, <code>false</code>
* otherwise.
*/
private boolean isStyleAttribute(ASTAttribute attributeNode) {
if (STYLE_ATTRIBUTES.contains(attributeNode.getName().toUpperCase(Locale.ROOT))) {
if (attributeNode.getParent() instanceof ASTElement) {
ASTElement parent = (ASTElement) attributeNode.getParent();
if (ELEMENT_NAMES_THAT_CAN_HAVE_STYLE_ATTRIBUTES.contains(parent.getName().toUpperCase(Locale.ROOT))) {
return true;
}
}
}
return false;
}
}
| 3,087 | 31.166667 | 119 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/cpd/JSPTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.lang.TokenManager;
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.jsp.ast.JspParser;
import net.sourceforge.pmd.lang.jsp.ast.JspTokenKinds;
public class JSPTokenizer extends JavaCCTokenizer {
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return JspTokenKinds.newTokenManager(sourceCode);
}
@Override
protected JavaccTokenDocument.TokenDocumentBehavior tokenBehavior() {
return JspParser.getTokenBehavior();
}
}
| 871 | 30.142857 | 79 | java |
pmd | pmd-master/pmd-jsp/src/main/java/net/sourceforge/pmd/cpd/JSPLanguage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.jsp.JspLanguageModule;
public class JSPLanguage extends AbstractLanguage {
public JSPLanguage() {
super(JspLanguageModule.NAME, JspLanguageModule.TERSE_NAME, new JSPTokenizer(), JspLanguageModule.EXTENSIONS);
}
}
| 384 | 26.5 | 118 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/LanguageVersionDiscovererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static java.util.Collections.singleton;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.vf.ast.AbstractVfTest;
/**
* @author sergey.gorbaty
*
*/
class LanguageVersionDiscovererTest extends AbstractVfTest {
/**
* Test on VF file.
*/
@Test
void testVFFile() {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD);
File vfFile = new File("/path/to/MyPage.page");
LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(vfFile);
assertEquals(vf.getLanguage().getDefaultVersion(), languageVersion, "LanguageVersion must be VF!");
}
@Test
void testComponentFile() {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(new LanguageRegistry(singleton(vf.getLanguage())));
File vfFile = new File("/path/to/MyPage.component");
LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(vfFile);
assertEquals(vf.getLanguage().getDefaultVersion(), languageVersion, "LanguageVersion must be VF!");
}
}
| 1,481 | 32.681818 | 128 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/RuleSetFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
RuleSetFactoryTest() {
super(ApexLanguageModule.TERSE_NAME);
}
// no additional tests yet
}
| 415 | 23.470588 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/LanguageVersionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import java.util.Arrays;
import java.util.Collection;
import net.sourceforge.pmd.AbstractLanguageVersionTest;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
class LanguageVersionTest extends AbstractLanguageVersionTest {
static Collection<TestDescriptor> data() {
return Arrays.asList(new TestDescriptor(VfLanguageModule.NAME, VfLanguageModule.TERSE_NAME,
ApexLanguageModule.getInstance().getDefaultVersion().getVersion(),
getLanguage(VfLanguageModule.NAME).getDefaultVersion()));
}
}
| 673 | 31.095238 | 99 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/DataTypeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import apex.jorje.semantic.symbol.type.BasicType;
class DataTypeTest {
@Test
void testFromString() {
assertEquals(DataType.AutoNumber, DataType.fromString("AutoNumber"));
assertEquals(DataType.AutoNumber, DataType.fromString("autonumber"));
assertEquals(DataType.Unknown, DataType.fromString(""));
assertEquals(DataType.Unknown, DataType.fromString(null));
}
@Test
void testFromTypeName() {
assertEquals(DataType.Checkbox, DataType.fromTypeName("Boolean"));
assertEquals(DataType.Currency, DataType.fromTypeName("Currency"));
assertEquals(DataType.DateTime, DataType.fromTypeName("Datetime"));
assertEquals(DataType.Number, DataType.fromTypeName("DECIMAL"));
assertEquals(DataType.Number, DataType.fromTypeName("double"));
assertEquals(DataType.Text, DataType.fromTypeName("string"));
assertEquals(DataType.Unknown, DataType.fromTypeName("Object"));
assertEquals(DataType.Unknown, DataType.fromTypeName(null));
}
@Test
void testDeprecatedFromBasicType() {
assertEquals(DataType.Checkbox, DataType.fromBasicType(BasicType.BOOLEAN));
assertEquals(DataType.Number, DataType.fromBasicType(BasicType.DECIMAL));
assertEquals(DataType.Number, DataType.fromBasicType(BasicType.DOUBLE));
assertEquals(DataType.Unknown, DataType.fromBasicType(BasicType.APEX_OBJECT));
assertEquals(DataType.Unknown, DataType.fromBasicType(null));
}
@Test
void testRequiresEncoding() {
assertFalse(DataType.AutoNumber.requiresEscaping);
assertTrue(DataType.Text.requiresEscaping);
}
}
| 2,005 | 38.333333 | 86 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/VFTestUtils.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
import net.sourceforge.pmd.util.log.MessageReporter;
public final class VFTestUtils {
private VFTestUtils() {
}
/**
* Salesforce metadata is stored in two different formats, the newer sfdx form and the older mdapi format. Used to
* locate metadata on the file system during unit tests.
*/
public enum MetadataFormat {
SFDX("sfdx"),
MDAPI("mdapi");
public final String directoryName;
MetadataFormat(String directoryName) {
this.directoryName = directoryName;
}
}
/**
* Represents the metadata types that are referenced from unit tests. Used to locate metadata on the file system
* during unit tests.
*/
public enum MetadataType {
Apex("classes"),
Objects("objects"),
Vf("pages");
public final String directoryName;
MetadataType(String directoryName) {
this.directoryName = directoryName;
}
}
public static LanguageProcessorRegistry fakeLpRegistry() {
LanguageRegistry registry = new LanguageRegistry(setOf(ApexLanguageModule.getInstance(), VfLanguageModule.getInstance()));
return LanguageProcessorRegistry.create(registry, Collections.emptyMap(), MessageReporter.quiet());
}
/**
* @return the path of the directory that matches the given parameters. The directory path is constructed using the
* following convention:
* src/test/resources/_decomposed_test_package_name_/_test_class_name_minus_Test_/metadata/_metadata_format_/_metadata_type_
*/
public static Path getMetadataPath(Object testClazz, MetadataFormat metadataFormat, MetadataType metadataType) {
Path path = Paths.get("src", "test", "resources");
// Decompose the test's package structure into directories
for (String directory : testClazz.getClass().getPackage().getName().split("\\.")) {
path = path.resolve(directory);
}
// Remove 'Test' from the class name
path = path.resolve(testClazz.getClass().getSimpleName().replaceFirst("Test$", ""));
// Append additional directories based on the MetadataFormat and MetadataType
path = path.resolve("metadata").resolve(metadataFormat.directoryName);
if (metadataType != null) {
path = path.resolve(metadataType.directoryName);
}
return path.toAbsolutePath();
}
}
| 2,863 | 34.8 | 130 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/ApexClassPropertyTypesVisitorTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
class ApexClassPropertyTypesVisitorTest {
@Test
@SuppressWarnings("PMD.CloseResource")
void testApexClassIsProperlyParsed() {
Path apexPath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Apex)
.resolve("ApexController.cls")
.toAbsolutePath();
ApexClassPropertyTypesVisitor visitor = new ApexClassPropertyTypesVisitor();
try (LanguageProcessorRegistry lpReg = VFTestUtils.fakeLpRegistry()) {
new ApexClassPropertyTypes(lpReg).parseApex(apexPath).acceptVisitor(visitor, null);
}
List<Pair<String, String>> variables = visitor.getVariables();
assertEquals(7, variables.size());
Map<String, String> variableNameToVariableType = new Hashtable<>();
for (Pair<String, String> variable : variables) {
// Map the values and ensure there were no duplicates
String previous = variableNameToVariableType.put(variable.getKey(), variable.getValue());
assertNull(previous, variable.getKey());
}
assertTrue("ID".equalsIgnoreCase(variableNameToVariableType.get("ApexController.AccountIdProp")));
assertTrue("ID".equalsIgnoreCase(variableNameToVariableType.get("ApexController.AccountId")));
assertTrue("String".equalsIgnoreCase(variableNameToVariableType.get("ApexController.AccountName")));
assertTrue("ApexController.InnerController".equalsIgnoreCase(variableNameToVariableType.get("ApexController.InnerController")));
assertTrue("ID".equalsIgnoreCase(variableNameToVariableType.get("ApexController.InnerController.InnerAccountIdProp")));
assertTrue("ID".equalsIgnoreCase(variableNameToVariableType.get("ApexController.InnerController.InnerAccountId")));
assertTrue("String".equalsIgnoreCase(variableNameToVariableType.get("ApexController.InnerController.InnerAccountName")));
}
}
| 2,578 | 46.759259 | 136 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/VfDocStyleTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Test parsing of a VF in document style, by checking the generated AST.
* Original @author pieter_van_raemdonck - Application Engineers NV/SA -
* www.ae.be
*
* @author sergey.gorbaty - VF adaptation
*
*/
class VfDocStyleTest extends AbstractVfTest {
/**
* Smoke test for VF parser.
*/
@Test
void testSimplestVf() {
List<ASTElement> nodes = vf.getNodes(ASTElement.class, TEST_SIMPLEST_HTML);
assertEquals(1, nodes.size(), "Exactly " + 1 + " element(s) expected");
}
/**
* Test the information on a Element and Attribute.
*/
@Test
void testElementAttributeAndNamespace() {
ASTCompilationUnit root = vf.parse(TEST_ELEMENT_AND_NAMESPACE);
List<ASTElement> elementNodes = root.findDescendantsOfType(ASTElement.class);
assertEquals(1, elementNodes.size(), "One element node expected!");
ASTElement element = elementNodes.iterator().next();
assertEquals("h:html", element.getName(), "Correct name expected!");
assertTrue(element.isHasNamespacePrefix(), "Has namespace prefix!");
assertTrue(element.isEmpty(), "Element is empty!");
assertEquals("h", element.getNamespacePrefix(), "Correct namespace prefix of element expected!");
assertEquals("html", element.getLocalName(), "Correct local name of element expected!");
List<ASTAttribute> attributeNodes = root.findDescendantsOfType(ASTAttribute.class);
assertEquals(1, attributeNodes.size(), "One attribute node expected!");
ASTAttribute attribute = attributeNodes.iterator().next();
assertEquals("MyNsPrefix:MyAttr", attribute.getName(), "Correct name expected!");
assertTrue(attribute.isHasNamespacePrefix(), "Has namespace prefix!");
assertEquals("MyNsPrefix", attribute.getNamespacePrefix(), "Correct namespace prefix of element expected!");
assertEquals("MyAttr", attribute.getLocalName(), "Correct local name of element expected!");
}
/**
* Test exposing a bug of parsing error when having a hash as last character
* in an attribute value.
*
*/
@Test
void testAttributeValueContainingHash() {
List<ASTAttribute> attributes = vf.getNodes(ASTAttribute.class, TEST_ATTRIBUTE_VALUE_CONTAINING_HASH);
assertEquals(3, attributes.size(), "Three attributes expected!");
ASTAttribute attr = attributes.get(0);
assertEquals("something", attr.getName(), "Correct attribute name expected!");
assertEquals("#yes#", attr.getFirstDescendantOfType(ASTText.class).getImage(),
"Correct attribute value expected!");
attr = attributes.get(1);
assertEquals("foo", attr.getName(), "Correct attribute name expected!");
assertEquals("CREATE", attr.getFirstDescendantOfType(ASTText.class).getImage(),
"Correct attribute value expected!");
attr = attributes.get(2);
assertEquals("href", attr.getName(), "Correct attribute name expected!");
assertEquals("#", attr.getFirstDescendantOfType(ASTText.class).getImage(), "Correct attribute value expected!");
}
/**
* Test correct parsing of CDATA.
*/
@Test
void testCData() {
List<ASTCData> cdataNodes = vf.getNodes(ASTCData.class, TEST_CDATA);
assertEquals(1, cdataNodes.size(), "One CDATA node expected!");
ASTCData cdata = cdataNodes.iterator().next();
assertEquals(" some <cdata> ]] ]> ", cdata.getImage(), "Content incorrectly parsed!");
}
/**
* Test parsing of Doctype declaration.
*/
@Test
void testDoctype() {
ASTCompilationUnit root = vf.parse(TEST_DOCTYPE);
List<ASTDoctypeDeclaration> docTypeDeclarations = root.findDescendantsOfType(ASTDoctypeDeclaration.class);
assertEquals(1, docTypeDeclarations.size(), "One doctype declaration expected!");
ASTDoctypeDeclaration docTypeDecl = docTypeDeclarations.iterator().next();
assertEquals("html", docTypeDecl.getName(), "Correct doctype-name expected!");
List<ASTDoctypeExternalId> externalIds = root.findDescendantsOfType(ASTDoctypeExternalId.class);
assertEquals(1, externalIds.size(), "One doctype external id expected!");
ASTDoctypeExternalId externalId = externalIds.iterator().next();
assertEquals("-//W3C//DTD XHTML 1.1//EN", externalId.getPublicId(), "Correct external public id expected!");
assertEquals("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd", externalId.getUri(),
"Correct external uri expected!");
}
/**
* Test parsing of HTML <script> element.
*/
@Test
void testHtmlScript() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_HTML_SCRIPT);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
ASTText text = script.getFirstChildOfType(ASTText.class);
assertEquals("Script!", text.getImage(), "Correct script content expected!");
}
/**
* Test parsing of EL in attribute of an element.
*/
@Test
void testELInTagValue() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_EL_IN_TAG_ATTRIBUTE);
assertEquals(1, elements.size(), "One element expected!");
ASTElement element = elements.iterator().next();
ASTAttributeValue attribute = element.getFirstDescendantOfType(ASTAttributeValue.class);
ASTIdentifier id = attribute.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("foo", id.getImage(), "Correct identifier expected");
}
/**
* Test parsing of EL in attribute of an element that also has a comment.
*/
@Test
void testELInTagValueWithCommentDQ() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_EL_IN_TAG_ATTRIBUTE_WITH_COMMENT);
assertEquals(1, elements.size(), "One element expected!");
ASTElement element = elements.iterator().next();
ASTElExpression elExpr = element.getFirstDescendantOfType(ASTElExpression.class);
ASTIdentifier id = elExpr.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("init", id.getImage(), "Correct identifier expected");
}
/**
* Test parsing of EL in attribute of an element that also has a comment.
*/
@Test
void testELInTagValueWithCommentSQ() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_EL_IN_TAG_ATTRIBUTE_WITH_COMMENT_SQ);
assertEquals(1, elements.size(), "One element expected!");
ASTElement element = elements.iterator().next();
ASTElExpression elExpr = element.getFirstDescendantOfType(ASTElExpression.class);
ASTIdentifier id = elExpr.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("init", id.getImage(), "Correct identifier expected");
}
/**
* Test parsing of EL in HTML <script> element.
*/
@Test
void testELInHtmlScript() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_EL_IN_HTML_SCRIPT);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
ASTText text = script.getFirstChildOfType(ASTText.class);
assertEquals("vartext=", text.getImage(), "Correct script content expected!");
ASTElExpression el = script.getFirstChildOfType(ASTElExpression.class);
ASTIdentifier id = el.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("elInScript", id.getImage(), "Correct EL content expected!");
}
/**
* Test parsing of inline comment in EL.
*/
@Test
void testInlineCommentInEL() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_EL_IN_HTML_SCRIPT_WITH_COMMENT);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
ASTText text = script.getFirstChildOfType(ASTText.class);
assertEquals("vartext=", text.getImage(), "Correct script content expected!");
ASTElExpression el = script.getFirstChildOfType(ASTElExpression.class);
ASTIdentifier id = el.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("elInScript", id.getImage(), "Correct EL content expected!");
}
/**
* Test parsing of quoted EL in HTML <script> element.
*/
@Test
void testQuotedELInHtmlScript() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_QUOTED_EL_IN_HTML_SCRIPT);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
ASTText text = script.getFirstChildOfType(ASTText.class);
assertEquals("vartext='textHere", text.getImage(), "Correct script content expected!");
ASTElExpression el = script.getFirstChildOfType(ASTElExpression.class);
ASTIdentifier id = el.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("elInScript", id.getImage(), "Correct EL content expected!");
}
/**
* Test parsing of HTML <script src="x"/> element. It might not be
* valid html but it is likely to appear in .page files.
*/
@Test
void testImportHtmlScript() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_IMPORT_JAVASCRIPT);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
List<ASTAttribute> attr = script.findDescendantsOfType(ASTAttribute.class);
assertEquals(1, attr.size(), "One script expected!");
ASTAttribute att = attr.iterator().next();
ASTAttributeValue val = att.getFirstChildOfType(ASTAttributeValue.class);
ASTText text = val.getFirstChildOfType(ASTText.class);
assertEquals("filename.js", text.getImage());
}
/**
* Test parsing of HTML <script> element.
*/
@Test
void testHtmlScriptWithAttribute() {
List<ASTHtmlScript> scripts = vf.getNodes(ASTHtmlScript.class, TEST_HTML_SCRIPT_WITH_ATTRIBUTE);
assertEquals(1, scripts.size(), "One script expected!");
ASTHtmlScript script = scripts.iterator().next();
ASTText text = script.getFirstChildOfType(ASTText.class);
assertEquals("Script!", text.getImage(), "Correct script content expected!");
List<ASTText> attrs = script.findDescendantsOfType(ASTText.class);
assertEquals("text/javascript", attrs.get(0).getImage());
}
/**
* A complex script containing HTML comments, escapes, quotes, etc.
*/
@Test
void testComplexHtmlScript() {
List<ASTHtmlScript> script = vf.getNodes(ASTHtmlScript.class, TEST_COMPLEX_SCRIPT);
assertEquals(1, script.size(), "One script expected!");
ASTHtmlScript next = script.iterator().next();
ASTText text = next.getFirstChildOfType(ASTText.class);
assertTrue(text.getImage().contains("<!--"));
}
/**
* Test parsing of HTML <style> element.
*/
@Test
void testInlineCss() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_INLINE_STYLE);
assertEquals(3, elements.size(), "Two elements expected!");
}
/**
* Test parsing of HTML text within element.
*/
@Test
void testTextInTag() {
List<ASTText> scripts = vf.getNodes(ASTText.class, TEST_TEXT_IN_TAG);
assertEquals(1, scripts.size(), "One text chunk expected!");
ASTText script = scripts.iterator().next();
assertEquals(" some text ", script.getImage(), "Correct content expected!");
}
/**
* Test parsing of HTML with no spaces between tags. Parser is likely in
* this scenario.
*/
@Test
void noSpacesBetweenTags() {
List<ASTElement> scripts = vf.getNodes(ASTElement.class, TEST_TAGS_NO_SPACE);
assertEquals(2, scripts.size(), "Two tags expected!");
Iterator<ASTElement> iterator = scripts.iterator();
ASTElement script = iterator.next();
assertEquals("a", script.getName(), "Correct content expected!");
script = iterator.next();
assertEquals("b", script.getName(), "Correct content expected!");
}
/**
* the $ sign might trick the parser into thinking an EL is next. He should
* be able to treat it as plain text
*/
@Test
void unclosedTagsWithDollar() {
List<ASTText> scripts = vf.getNodes(ASTText.class, TEST_TAGS_WITH_DOLLAR);
assertEquals(2, scripts.size(), "Two text chunks expected!");
ASTText script = scripts.iterator().next();
assertEquals(" $ ", script.getImage(), "Correct content expected!");
}
/**
* Make sure EL expressions aren't treated as plain text when they are
* around unclosed tags.
*/
@Test
void unclosedTagsWithELWithin() {
List<ASTElement> element = vf.getNodes(ASTElement.class, TEST_TAGS_WITH_EL_WITHIN);
assertEquals(1, element.size(), "One element expected!");
for (ASTElement elem : element) {
ASTContent content = elem.getFirstChildOfType(ASTContent.class);
List<ASTElExpression> els = content.findChildrenOfType(ASTElExpression.class);
assertEquals(2, els.size(), "Two EL expressions expected!");
ASTElExpression node = (ASTElExpression) content.getChild(0);
ASTIdentifier id = node.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("expr1", id.getImage(), "Correct content expected!");
node = (ASTElExpression) content.getChild(1);
id = node.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("expr2", id.getImage(), "Correct content expected!");
}
}
/**
* Test parsing of HTML <script> element.
*/
@Test
void textAfterOpenAndClosedTag() {
List<ASTElement> nodes = vf.getNodes(ASTElement.class, TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG);
assertEquals(2, nodes.size(), "Two elements expected!");
assertEquals("a", nodes.get(0).getName(), "First element should be a");
assertFalse(nodes.get(0).isUnclosed(), "first element should be closed");
assertEquals("b", nodes.get(1).getName(), "Second element should be b");
assertTrue(nodes.get(1).isUnclosed(), "Second element should not be closed");
List<ASTText> text = vf.getNodes(ASTText.class, TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG);
assertEquals(2, text.size(), "Two text chunks expected!");
}
@Test
void quoteEL() {
List<ASTAttributeValue> attributes = vf.getNodes(ASTAttributeValue.class, TEST_QUOTE_EL);
assertEquals(1, attributes.size(), "One attribute expected!");
ASTAttributeValue attr = attributes.iterator().next();
List<ASTElExpression> els = attr.findChildrenOfType(ASTElExpression.class);
assertEquals(1, els.size(), "Must be 1!");
ASTExpression expr = els.get(0).getFirstChildOfType(ASTExpression.class);
ASTIdentifier id = expr.getFirstChildOfType(ASTIdentifier.class);
assertEquals("something", id.getImage(), "Expected to detect proper value for attribute!");
}
/**
* smoke test for a non-quoted attribute value
*/
@Test
void quoteAttrValue() {
List<ASTAttributeValue> attributes = vf.getNodes(ASTAttributeValue.class, TEST_ATTR);
assertEquals(1, attributes.size(), "One attribute expected!");
ASTAttributeValue attr = attributes.iterator().next();
ASTText text = attr.getFirstChildOfType(ASTText.class);
assertEquals("yes|", text.getImage(), "Expected to detect proper value for attribute!");
}
/**
* tests whether parse correctly interprets empty non quote attribute
*/
@Test
void noQuoteAttrEmpty() {
List<ASTAttributeValue> attributes = vf.getNodes(ASTAttributeValue.class, TEST_EMPTY_ATTR);
assertEquals(2, attributes.size(), "two attributes expected!");
Iterator<ASTAttributeValue> iterator = attributes.iterator();
ASTAttributeValue attr = iterator.next();
if ("http://someHost:/some_URL".equals(attr.getImage())) {
// we have to employ this nasty work-around
// in order to ensure that we check the proper attribute
attr = iterator.next();
}
assertNull(attr.getImage(), "Expected to detect proper value for attribute!");
}
/**
* tests whether parse correctly interprets an tab instead of an attribute
*/
@Test
void singleQuoteAttrTab() {
List<ASTAttributeValue> attributes = vf.getNodes(ASTAttributeValue.class, TEST_TAB_ATTR);
assertEquals(1, attributes.size(), "One attribute expected!");
Iterator<ASTAttributeValue> iterator = attributes.iterator();
ASTAttributeValue attr = iterator.next();
ASTText text = attr.getFirstChildOfType(ASTText.class);
assertEquals("\t", text.getImage(), "Expected to detect proper value for attribute!");
}
@Test
void unclosedTag() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_SIMPLE);
assertEquals(2, elements.size(), "2 tags expected");
assertEquals("tag:someTag", elements.get(0).getName(), "Second element should be tag:someTag");
assertEquals("tag:if", elements.get(1).getName(), "First element should be sorted tag:if");
assertTrue(elements.get(1).isEmpty());
assertTrue(elements.get(1).isUnclosed());
assertFalse(elements.get(0).isEmpty());
assertFalse(elements.get(0).isUnclosed());
}
@Test
void unclosedTagAndNoQuotesForAttribute() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_ATTR);
assertEquals(2, elements.size(), "2 tags expected");
assertEquals("tag:someTag", elements.get(0).getName(), "Second element should be tag:someTag");
assertEquals("tag:if", elements.get(1).getName(), "First element should be sorted tag:if");
assertTrue(elements.get(1).isEmpty());
assertTrue(elements.get(1).isUnclosed());
assertFalse(elements.get(0).isEmpty());
assertFalse(elements.get(0).isUnclosed());
}
@Test
void unclosedTagMultipleLevels() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_MULTIPLE_LEVELS);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(3, elements.size(), "3 tags expected");
assertEquals("tag:someTag", sortedElmnts.get(0).getName(), "First element should be sorted tag:someTag");
assertEquals("tag:someTag", sortedElmnts.get(1).getName(), "Second element should be tag:someTag");
assertEquals("tag:x", sortedElmnts.get(2).getName(), "Third element should be tag:x");
assertFalse(sortedElmnts.get(0).isEmpty());
assertFalse(sortedElmnts.get(0).isUnclosed());
assertTrue(sortedElmnts.get(1).isEmpty());
assertTrue(sortedElmnts.get(1).isUnclosed());
assertFalse(sortedElmnts.get(2).isEmpty());
assertFalse(sortedElmnts.get(2).isUnclosed());
}
/**
* <html> <a1> <a2/> <b/> </a1> </html>
*/
@Test
void nestedEmptyTags() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_MULTIPLE_EMPTY_TAGS);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(4, elements.size(), "4 tags expected");
assertEquals("a1", sortedElmnts.get(0).getName(), "First element should a1");
assertEquals("a2", sortedElmnts.get(1).getName(), "Second element should be a2");
assertEquals("b", sortedElmnts.get(2).getName(), "Third element should be b");
assertEquals("html", sortedElmnts.get(3).getName(), "Third element should be html");
// a1
assertFalse(sortedElmnts.get(0).isEmpty());
assertFalse(sortedElmnts.get(0).isUnclosed());
// a2
assertTrue(sortedElmnts.get(1).isEmpty());
assertFalse(sortedElmnts.get(1).isUnclosed());
// b
assertTrue(sortedElmnts.get(2).isEmpty());
assertFalse(sortedElmnts.get(2).isUnclosed());
// html
assertFalse(sortedElmnts.get(3).isEmpty());
assertFalse(sortedElmnts.get(3).isUnclosed());
}
/**
* <html> <a1> <a2> <a3> </a2> </a1>
* <b/> <a4/> </html>
*/
@Test
void nestedMultipleTags() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_MULTIPLE_NESTED_TAGS);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(6, elements.size(), "4 tags expected");
assertEquals("a1", sortedElmnts.get(0).getName(), "First element should a1");
assertEquals("a2", sortedElmnts.get(1).getName(), "Second element should be a2");
assertEquals("a3", sortedElmnts.get(2).getName(), "Third element should be a3");
assertEquals("a4", sortedElmnts.get(3).getName(), "Forth element should be a4");
assertEquals("b", sortedElmnts.get(4).getName(), "Fifth element should be b");
assertEquals("html", sortedElmnts.get(5).getName(), "Sixth element should be html");
// a1 not empty and closed
assertFalse(sortedElmnts.get(0).isEmpty());
assertFalse(sortedElmnts.get(0).isUnclosed());
// a2 not empty and closed
assertFalse(sortedElmnts.get(1).isEmpty());
assertFalse(sortedElmnts.get(1).isUnclosed());
// a3 empty and not closed
assertTrue(sortedElmnts.get(2).isEmpty());
assertTrue(sortedElmnts.get(2).isUnclosed());
// a4 empty but closed
assertTrue(sortedElmnts.get(3).isEmpty());
assertFalse(sortedElmnts.get(3).isUnclosed());
// b empty but closed
assertTrue(sortedElmnts.get(4).isEmpty());
assertFalse(sortedElmnts.get(4).isUnclosed());
// html not empty and closed
assertFalse(sortedElmnts.get(5).isEmpty());
assertFalse(sortedElmnts.get(5).isUnclosed());
}
/**
* will test <x> <a> <b> <b> </x> </a>
* </x> . Here x is the first tag to be closed thus rendering the next
* close of a (</a>) to be disregarded.
*/
@Test
void unclosedParentTagClosedBeforeChild() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_END_AFTER_PARENT_CLOSE);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(4, elements.size(), "4 tags expected");
assertEquals("a", sortedElmnts.get(0).getName(), "First element should be 'a'");
assertEquals("b", sortedElmnts.get(1).getName(), "Second element should be b");
assertEquals("b", sortedElmnts.get(2).getName(), "Third element should be b");
assertEquals("x", sortedElmnts.get(3).getName(), "Forth element should be x");
// a
assertTrue(sortedElmnts.get(0).isEmpty());
assertTrue(sortedElmnts.get(0).isUnclosed());
// b
assertTrue(sortedElmnts.get(1).isEmpty());
assertTrue(sortedElmnts.get(1).isUnclosed());
// b
assertTrue(sortedElmnts.get(2).isEmpty());
assertTrue(sortedElmnts.get(2).isUnclosed());
// x
assertFalse(sortedElmnts.get(3).isEmpty());
assertFalse(sortedElmnts.get(3).isUnclosed());
}
/**
* <x> <a> <b> <b> </z> </a> </x>
* An unmatched closing of 'z' appears randomly in the document. This should
* be disregarded and structure of children and parents should not be
* influenced. in other words </a> should close the first <a>
* tag , </x> should close the first <x>, etc.
*/
@Test
void unmatchedTagDoesNotInfluenceStructure() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_UNMATCHED_CLOSING_TAG);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(4, elements.size(), "4 tags expected");
assertEquals("a", sortedElmnts.get(0).getName(), "First element should be 'a'");
assertEquals("b", sortedElmnts.get(1).getName(), "Second element should be b");
assertEquals("b", sortedElmnts.get(2).getName(), "Third element should be b");
assertEquals("x", sortedElmnts.get(3).getName(), "Forth element should be x");
// a is not empty and closed
assertFalse(sortedElmnts.get(0).isEmpty());
assertFalse(sortedElmnts.get(0).isUnclosed());
// b empty and unclosed
assertTrue(sortedElmnts.get(1).isEmpty());
assertTrue(sortedElmnts.get(1).isUnclosed());
// b empty and unclosed
assertTrue(sortedElmnts.get(2).isEmpty());
assertTrue(sortedElmnts.get(2).isUnclosed());
// x not empty and closed
assertFalse(sortedElmnts.get(3).isEmpty());
assertFalse(sortedElmnts.get(3).isUnclosed());
}
/**
* <a> <x> <a> <b> <b> </z> </a>
* </x> An unmatched closing of 'z' appears randomly in the document.
* This should be disregarded and structure of children and parents should
* not be influenced. Also un unclosed <a> tag appears at the start of
* the document
*/
@Test
void unclosedStartTagWithUnmatchedCloseOfDifferentTag() {
List<ASTElement> elements = vf.getNodes(ASTElement.class, TEST_UNCLOSED_START_TAG_WITH_UNMATCHED_CLOSE);
List<ASTElement> sortedElmnts = sortNodesByName(elements);
assertEquals(5, elements.size(), "5 tags expected");
assertEquals("a", sortedElmnts.get(0).getName(), "First element should be 'a'");
assertEquals("a", sortedElmnts.get(1).getName(), "Second element should be a");
assertEquals("b", sortedElmnts.get(2).getName(), "Third element should be b");
assertEquals("b", sortedElmnts.get(3).getName(), "Forth element should be b");
assertEquals("x", sortedElmnts.get(4).getName(), "Fifth element should be x");
// first a is empty and unclosed
assertTrue(sortedElmnts.get(0).isEmpty());
assertTrue(sortedElmnts.get(0).isUnclosed());
// second a not empty and closed
assertFalse(sortedElmnts.get(1).isEmpty());
assertFalse(sortedElmnts.get(1).isUnclosed());
// b empty and unclosed
assertTrue(sortedElmnts.get(2).isEmpty());
assertTrue(sortedElmnts.get(2).isUnclosed());
// b empty and unclosed
assertTrue(sortedElmnts.get(3).isEmpty());
assertTrue(sortedElmnts.get(3).isUnclosed());
// x not empty and closed
assertFalse(sortedElmnts.get(4).isEmpty());
assertFalse(sortedElmnts.get(4).isUnclosed());
}
/**
* will sort the AST element in list in alphabetical order and if tag name
* is the same it will sort against o1.getBeginColumn() +""+
* o1.getBeginLine(). so first criteria is the name, then the second is the
* column +""+line string.
*
* @param elements
* @return
*/
private List<ASTElement> sortNodesByName(List<ASTElement> elements) {
Collections.sort(elements, new Comparator<ASTElement>() {
@Override
public int compare(ASTElement o1, ASTElement o2) {
if (o1.getName() == null) {
return Integer.MIN_VALUE;
}
if (o2.getName() == null) {
return Integer.MAX_VALUE;
}
if (o1.getName().equals(o2.getName())) {
String o1Value = o1.getBeginColumn() + "" + o1.getBeginLine();
String o2Value = o2.getBeginColumn() + "" + o2.getBeginLine();
return o1Value.compareTo(o2Value);
}
return o1.getName().compareTo(o2.getName());
}
});
return elements;
}
@Test
void noQuoteAttrWithJspEL() {
List<ASTAttributeValue> attributes = vf.getNodes(ASTAttributeValue.class, TEST_NO_QUOTE_ATTR_WITH_EL);
assertEquals(1, attributes.size(), "One attribute expected!");
Iterator<ASTAttributeValue> iterator = attributes.iterator();
ASTAttributeValue attr = iterator.next();
ASTIdentifier id = attr.getFirstDescendantOfType(ASTIdentifier.class);
assertEquals("something", id.getImage(), "Expected to detect proper value for EL in attribute!");
}
private static final String TEST_SIMPLEST_HTML = "<html/>";
private static final String TEST_ELEMENT_AND_NAMESPACE = "<h:html MyNsPrefix:MyAttr='MyValue'/>";
private static final String TEST_CDATA = "<html><![CDATA[ some <cdata> ]] ]> ]]></html>";
private static final String TEST_DOCTYPE = "<?xml version=\"1.0\" standalone='yes'?>\n"
+ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "
+ "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" + "<greeting>Hello, world!</greeting>";
private static final String TEST_ATTRIBUTE_VALUE_CONTAINING_HASH = "<tag:if something=\"#yes#\" foo=\"CREATE\"> <a href=\"#\">foo</a> </tag:if>";
private static final String TEST_HTML_SCRIPT = "<html><head><script>Script!</script></head></html>";
private static final String TEST_EL_IN_TAG_ATTRIBUTE = "<apex:page action=\"{!foo}\">text</apex:page>";
private static final String TEST_EL_IN_TAG_ATTRIBUTE_WITH_COMMENT = "<apex:page action=\"{!/*comment here*/init}\">text</apex:page>";
private static final String TEST_EL_IN_TAG_ATTRIBUTE_WITH_COMMENT_SQ = "<apex:page action='{!/*comment here*/init}'>text</apex:page>";
private static final String TEST_EL_IN_HTML_SCRIPT = "<html><head><script>var text={!elInScript};</script></head></html>";
private static final String TEST_EL_IN_HTML_SCRIPT_WITH_COMMENT = "<html><head><script>var text={!/*junk1*/elInScript/*junk2*/};</script></head></html>";
private static final String TEST_QUOTED_EL_IN_HTML_SCRIPT = "<html><head><script>var text='textHere{!elInScript}';</script></head></html>";
private static final String TEST_IMPORT_JAVASCRIPT = "<html><head><script src=\"filename.js\" /></head></html>";
private static final String TEST_HTML_SCRIPT_WITH_ATTRIBUTE = "<html><head><script type=\"text/javascript\">Script!</script></head></html>";
private static final String TEST_COMPLEX_SCRIPT = "<HTML><BODY><!--Java Script-->"
+ "<SCRIPT language='JavaScript' type='text/javascript'>" + "<!--function calcDays(){"
+ " date1 = date1.split(\"-\"); date2 = date2.split(\"-\");"
+ " var sDate = new Date(date1[0]+\"/\"+date1[1]+\"/\"+date1[2]);"
+ " var eDate = new Date(date2[0]+\"/\"+date2[1]+\"/\"+date2[2]);" + " onload=calcDays;//-->"
+ "</SCRIPT></BODY></HTML>;";
private static final String TEST_INLINE_STYLE = "<html><head><style> div { color:red; } </style></head></html>";
private static final String TEST_TEXT_IN_TAG = "<a> some text </a>";
private static final String TEST_TAGS_NO_SPACE = "<a><b></a>";
private static final String TEST_TAGS_WITH_DOLLAR = "<a> $ <b> $ </a>";
private static final String TEST_TAGS_WITH_EL_WITHIN = "<a>{!expr1}{!expr2}</a>";
private static final String TEST_TEXT_AFTER_OPEN_AND_CLOSED_TAG = "<a> some text <b> some text </a>";
private static final String TEST_QUOTE_EL = "<tag:if something=\"{!something}\" > </tag:if>";
private static final String TEST_ATTR = "<tag:if something=\"yes|\" > </tag:if>";
private static final String TEST_EMPTY_ATTR = "<tag:if something= > <a href=\"http://someHost:/some_URL\" >foo</a> </tag:if>";
private static final String TEST_TAB_ATTR = "<tag:if something='\t' > </tag:if>";
private static final String TEST_UNCLOSED_SIMPLE = "<tag:someTag> <tag:if something=\"x\" > </tag:someTag>";
/**
* someTag is closed just once
*/
private static final String TEST_UNCLOSED_MULTIPLE_LEVELS = "<tag:x> <tag:someTag> <tag:someTag something=\"x\" > </tag:someTag> </tag:x>";
/**
* nested empty tags
*/
private static final String TEST_MULTIPLE_EMPTY_TAGS = "<html> <a1> <a2/> <b/> </a1> </html>";
/**
* multiple nested tags with some tags unclosed
*/
private static final String TEST_MULTIPLE_NESTED_TAGS = "<html> <a1> <a2> <a3> </a2> </a1> <b/> <a4/> </html>";
/**
* </x> will close before </a>, thus leaving <a> to remain unclosed
*/
private static final String TEST_UNCLOSED_END_AFTER_PARENT_CLOSE = "<x> <a> <b> <b> </x> </a> aa </x> bb </x>";
/**
* </z> is just a dangling closing tag not matching any parent. The parser
* should disregard it
*/
private static final String TEST_UNCLOSED_UNMATCHED_CLOSING_TAG = "<x> <a> <b> <b> </z> </a> </x>";
/**
* First <a> tag does not close. The first closing of </a> will match the
* second opening of a. Another rogue </z> is there for testing compliance
*/
private static final String TEST_UNCLOSED_START_TAG_WITH_UNMATCHED_CLOSE = "<a> <x> <a> <b> <b> </z> </a> </x>";
private static final String TEST_UNCLOSED_ATTR = "<tag:someTag> <tag:if something='x' > </tag:someTag>";
private static final String TEST_NO_QUOTE_ATTR_WITH_EL = "<apex:someTag something={!something} > foo </apex:someTag>";
}
| 34,236 | 43.812827 | 157 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/ApexClassPropertyTypesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.vf.DataType;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
import net.sourceforge.pmd.lang.vf.VfLanguageProperties;
class ApexClassPropertyTypesTest {
private static final Map<String, DataType> EXPECTED_DATA_TYPES;
static {
// Intentionally use the wrong case for property names to ensure that they can be found. The Apex class name
// must have the correct case since it is used to lookup the file. The Apex class name is guaranteed to be correct
// in the Visualforce page, but the property names are not
EXPECTED_DATA_TYPES = new HashMap<>();
EXPECTED_DATA_TYPES.put("ApexController.accOuntIdProp", DataType.Lookup);
EXPECTED_DATA_TYPES.put("ApexController.AcCountId", DataType.Lookup);
EXPECTED_DATA_TYPES.put("ApexController.AcCountname", DataType.Text);
// InnerController
// The class should be parsed to Unknown. It's not a valid expression on its own.
EXPECTED_DATA_TYPES.put("ApexController.innErController", DataType.Unknown);
EXPECTED_DATA_TYPES.put("ApexController.innErController.innErAccountIdProp", DataType.Lookup);
EXPECTED_DATA_TYPES.put("ApexController.innErController.innErAccountid", DataType.Lookup);
EXPECTED_DATA_TYPES.put("ApexController.innErController.innErAccountnAme", DataType.Text);
// Edge cases
// Invalid class should return null
EXPECTED_DATA_TYPES.put("unknownclass.invalidProperty", null);
// Invalid class property should return null
EXPECTED_DATA_TYPES.put("ApexController.invalidProperty", null);
/*
* It is possible to have a property and method with different types that resolve to the same Visualforce
* expression. An example is an Apex class with a property "public String Foo {get; set;}" and a method of
* "Integer getFoo() { return 1; }". These properties should map to {@link DataType#Unknown}.
*/
EXPECTED_DATA_TYPES.put("ApexController.ConflictingProp", DataType.Unknown);
}
@Test
void testApexClassIsProperlyParsed() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve("SomePage.page");
try (LanguageProcessorRegistry lpReg = VFTestUtils.fakeLpRegistry()) {
ApexClassPropertyTypes apexClassPropertyTypes = new ApexClassPropertyTypes(lpReg);
ObjectFieldTypesTest.validateDataTypes(EXPECTED_DATA_TYPES, apexClassPropertyTypes, vfPagePath,
VfLanguageProperties.APEX_DIRECTORIES_DESCRIPTOR.defaultValue());
}
}
@Test
void testInvalidDirectoryDoesNotCauseAnException() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve("SomePage.page");
FileId vfFileName = FileId.fromPath(vfPagePath);
List<String> paths = listOf(Paths.get("..", "classes-does-not-exist").toString());
try (LanguageProcessorRegistry lpReg = VFTestUtils.fakeLpRegistry()) {
ApexClassPropertyTypes apexClassPropertyTypes = new ApexClassPropertyTypes(lpReg);
assertNull(apexClassPropertyTypes.getDataType("ApexController.accOuntIdProp", vfFileName, paths));
}
}
}
| 3,937 | 47.617284 | 122 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/VfPageStyleTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
class VfPageStyleTest extends AbstractVfTest {
/**
* Test parsing of a EL expression.
*/
@Test
void testElExpression() {
List<ASTElExpression> expressions = vf.getNodes(ASTElExpression.class, VF_EL_EXPRESSION);
assertEquals(1, expressions.size(), "One expression expected!");
ASTElExpression expression = expressions.iterator().next();
ASTExpression exp = expression.getFirstChildOfType(ASTExpression.class);
ASTIdentifier id = exp.getFirstChildOfType(ASTIdentifier.class);
assertEquals("myBean", id.getImage(), "Correct expression content expected!");
ASTDotExpression dot = exp.getFirstChildOfType(ASTDotExpression.class);
ASTIdentifier dotid = dot.getFirstChildOfType(ASTIdentifier.class);
assertEquals("get", dotid.getImage(), "Correct expression content expected!");
ASTArguments arguments = exp.getFirstChildOfType(ASTArguments.class);
ASTExpression innerExpression = arguments.getFirstChildOfType(ASTExpression.class);
ASTLiteral literal = innerExpression.getFirstChildOfType(ASTLiteral.class);
assertEquals("\"{! World }\"", literal.getImage(), "Correct expression content expected!");
}
/**
* Test parsing of a EL expression in an attribute.
*/
@Test
void testElExpressionInAttribute() {
List<ASTElExpression> expressions = vf.getNodes(ASTElExpression.class, VF_EL_EXPRESSION_IN_ATTRIBUTE);
assertEquals(1, expressions.size(), "One expression expected!");
ASTElExpression expression = expressions.iterator().next();
ASTExpression exp = expression.getFirstChildOfType(ASTExpression.class);
ASTIdentifier id = exp.getFirstChildOfType(ASTIdentifier.class);
assertEquals("myValidator", id.getImage(), "Correct expression content expected!");
ASTDotExpression dot = exp.getFirstChildOfType(ASTDotExpression.class);
ASTIdentifier dotid = dot.getFirstChildOfType(ASTIdentifier.class);
assertEquals("find", dotid.getImage(), "Correct expression content expected!");
ASTArguments arguments = exp.getFirstChildOfType(ASTArguments.class);
ASTExpression innerExpression = arguments.getFirstChildOfType(ASTExpression.class);
ASTLiteral literal = innerExpression.getFirstChildOfType(ASTLiteral.class);
assertEquals("\"'vf'\"", literal.getImage(), "Correct expression content expected!");
}
private static final String VF_EL_EXPRESSION = "<html><title>Hello {!myBean.get(\"{! World }\") } .vf</title></html>";
private static final String VF_EL_EXPRESSION_IN_ATTRIBUTE = "<html> <f:validator type=\"get('type').{!myValidator.find(\"'vf'\")}\" /> </html>";
}
| 2,976 | 49.457627 | 148 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/VfParserTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
/**
* @author sergey.gorbaty
*/
class VfParserTest extends AbstractVfTest {
@Test
void testSingleDoubleQuoteAndEL() {
vf.parse("<span escape='false' attrib=\"{!call}\">${!'yes'}</span>");
}
@Test
void testSingleDoubleQuoteAndELFunction() {
vf.parse("<span escape='false' attrib=\"{!call}\">${!method}</span>");
}
@Test
void testSingleDoubleQuote() {
vf.parse("<span escape='false' attrib=\"{!call}\">${\"yes\"}</span>");
}
@Test
void testAttributeNameWithDot() {
vf.parse("<table-row keep-together.within-page=\"always\" >");
}
@Test
void testAttributeNameWithUnderscore() {
vf.parse("<table-row test_attribute=\"always\" >");
}
@Test
void testAttributeNameWithColon() {
vf.parse("<table-row test:attribute=\"always\" >");
}
@Test
void testAttributeNameWithInvalidSymbol() {
assertThrows(ParseException.class, () -> vf.parse("<table-row test&attribute=\"always\" >"));
}
@Test
void testAttributeNameWithInvalidDot() {
assertThrows(ParseException.class, () -> vf.parse("<table-row .class=\"always\" >"));
}
@Test
void testAttributeNameWithInvalidDotV2() {
assertThrows(ParseException.class, () -> vf.parse("<table-row test..attribute=\"always\" >"));
}
@Test
void testAttributeNameWithInvalidDotV3() {
assertThrows(ParseException.class, () -> vf.parse("<table-row test.attribute.=\"always\" >"));
}
}
| 1,794 | 25.014493 | 102 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/VfParsingHelper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
import net.sourceforge.pmd.lang.vf.VfLanguageModule;
public final class VfParsingHelper extends BaseParsingHelper<VfParsingHelper, ASTCompilationUnit> {
public static final VfParsingHelper DEFAULT = new VfParsingHelper(Params.getDefault());
public VfParsingHelper(Params params) {
super(VfLanguageModule.NAME, ASTCompilationUnit.class, params);
}
@Override
protected @NonNull LanguageProcessorRegistry loadLanguages(@NonNull Params params) {
// We need to register both apex and VF, the default is just to register VF
return VFTestUtils.fakeLpRegistry();
}
@Override
protected VfParsingHelper clone(Params params) {
return new VfParsingHelper(params);
}
}
| 1,087 | 31.969697 | 99 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/ASTExpressionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.util.treeexport.XmlTreeRenderer;
class ASTExpressionTest {
/**
* Slightly different scenarios which cause different AST, but should return the same results.
*/
private static final String[] SNIPPET_TEMPLATES = new String[] {
"{!%s}",
"<apex:outputText value=\"{!%s}\" escape=\"false\"/>",
"<script>function someFunc() {var foo = \"{!%s}\";}</script>"};
@Test
void testExpressionWithApexGetter() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyValue"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(1, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertTrue(map.containsKey("MyValue"), template);
assertTrue(map.get("MyValue") instanceof ASTIdentifier, template);
}
}
@Test
void testExpressionWithStandardController() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject__c.Text__c"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(1, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertTrue(map.containsKey("MyObject__c.Text__c"), template);
assertTrue(map.get("MyObject__c.Text__c") instanceof ASTIdentifier, template);
}
}
@Test
void testSelectOptions() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "userOptions.0"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(1, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertTrue(map.containsKey("userOptions.0"), template);
assertTrue(map.get("userOptions.0") instanceof ASTLiteral, template);
}
}
@Test
void testMultipleIdentifiers() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject__c.Text__c + ' this is a string' + MyObject__c.Text2__c"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(2, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertEquals(2, map.size(), template);
assertTrue(map.containsKey("MyObject__c.Text__c"), template);
assertTrue(map.get("MyObject__c.Text__c") instanceof ASTIdentifier, template);
assertTrue(map.containsKey("MyObject__c.Text2__c"), template);
assertTrue(map.get("MyObject__c.Text2__c") instanceof ASTIdentifier, template);
}
}
@Test
void testIdentifierWithRelation() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject1__c.MyObject2__r.Text__c"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(1, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertEquals(1, map.size(), template);
assertTrue(map.containsKey("MyObject1__c.MyObject2__r.Text__c"), template);
assertTrue(map.get("MyObject1__c.MyObject2__r.Text__c") instanceof ASTIdentifier, template);
}
}
@Test
void testMultipleIdentifiersWithRelation() throws ASTExpression.DataNodeStateException {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject1__c.MyObject2__r.Text__c + ' this is a string' + MyObject1__c.MyObject2__r.Text2__c"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(1, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
Map<VfTypedNode, String> identifiers = expression.getDataNodes();
assertEquals(2, identifiers.size(), template);
Map<String, Node> map = invertMap(identifiers);
assertEquals(2, map.size(), template);
assertTrue(map.containsKey("MyObject1__c.MyObject2__r.Text__c"), template);
assertTrue(map.get("MyObject1__c.MyObject2__r.Text__c") instanceof ASTIdentifier, template);
assertTrue(map.containsKey("MyObject1__c.MyObject2__r.Text2__c"), template);
assertTrue(map.get("MyObject1__c.MyObject2__r.Text2__c") instanceof ASTIdentifier, template);
}
}
/**
* The current implementation does not support expressing statements using array notation. This notation introduces
* complexities that may be addressed in a future release.
*/
@Test
void testExpressionWithArrayIndexingNotSupported() {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject__c['Name']"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(2, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
try {
expression.getDataNodes();
fail(template + " should have thrown");
} catch (ASTExpression.DataNodeStateException expected) {
// Intentionally left blank
}
}
}
@Test
void testIdentifierWithRelationIndexedAsArrayNotSupported() {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "MyObject1__c['MyObject2__r'].Text__c"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(2, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
try {
expression.getDataNodes();
fail(template + " should have thrown");
} catch (ASTExpression.DataNodeStateException expected) {
// Intentionally left blank
}
}
}
@Test
void testIdentifierWithComplexIndexedArrayNotSupported() {
for (String template : SNIPPET_TEMPLATES) {
ASTCompilationUnit compilationUnit = compile(String.format(template, "theLineItems[item.Id].UnitPrice"));
List<Node> nodes = getExpressions(compilationUnit);
assertEquals(2, nodes.size(), template);
ASTExpression expression = (ASTExpression) nodes.get(0);
try {
expression.getDataNodes();
fail(template + " should have thrown");
} catch (ASTExpression.DataNodeStateException expected) {
// Intentionally left blank
}
}
}
private static List<Node> getExpressions(ASTCompilationUnit compilationUnit) {
return compilationUnit.descendants(ASTExpression.class).toList(it -> it);
}
/**
* Invert the map to make it easier to unit test.
*/
private Map<String, Node> invertMap(Map<VfTypedNode, String> map) {
Map<String, Node> result = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
// Ensure no values have been lost
assertEquals(map.size(), result.size());
return result;
}
private ASTCompilationUnit compile(String snippet) {
return compile(snippet, false);
}
private ASTCompilationUnit compile(String snippet, boolean renderAST) {
ASTCompilationUnit node = VfParsingHelper.DEFAULT.parse(
"<apex:page>"
+ snippet
+ "</apex:page>"
);
if (renderAST) {
try {
new XmlTreeRenderer().renderSubtree(node, System.out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return node;
}
}
| 9,957 | 40.319502 | 178 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/AbstractVfTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public abstract class AbstractVfTest {
protected final VfParsingHelper vf =
VfParsingHelper.DEFAULT
.withResourceContext(getClass());
}
| 293 | 20 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegisterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class OpenTagRegisterTest {
private OpenTagRegister tagList;
private int elmId = 0;
@BeforeEach
void newRegister() {
tagList = new OpenTagRegister();
}
/**
* <a> <b> </a>
*/
@Test
void testSimpleNesting() {
ASTElement elm = element("a");
ASTElement elm2 = element("b");
tagList.openTag(elm);
tagList.openTag(elm2);
tagList.closeTag(elm);
assertFalse(elm.isUnclosed());
assertTrue(elm2.isUnclosed());
}
/**
* <a> <b> <b> </a>
*/
@Test
void doubleNesting() {
ASTElement elm = element("a");
ASTElement elm2 = element("b");
ASTElement elm3 = element("b");
tagList.openTag(elm);
tagList.openTag(elm2);
tagList.openTag(elm3);
tagList.closeTag(elm);
assertFalse(elm.isUnclosed());
assertTrue(elm2.isUnclosed());
assertTrue(elm3.isUnclosed());
}
/**
* <x> <a> <b> <b> </x> </a> </x>
*/
@Test
void unopenedTags() {
ASTElement elm = element("x");
ASTElement elm2 = element("a");
ASTElement elm3 = element("b");
ASTElement elm4 = element("b");
tagList.openTag(elm);
tagList.openTag(elm2);
tagList.openTag(elm3);
tagList.openTag(elm4);
tagList.closeTag(elm);
tagList.closeTag(elm2);
tagList.closeTag(elm3);
tagList.closeTag(elm);
assertFalse(elm.isUnclosed());
assertTrue(elm2.isUnclosed());
assertTrue(elm3.isUnclosed());
assertTrue(elm4.isUnclosed());
}
/**
* <x> <a> <b> <b> </z> </a> </x>
*
*/
@Test
void interleavedTags() {
ASTElement elm = element("x");
ASTElement elm2 = element("a");
ASTElement elm3 = element("b");
ASTElement elm4 = element("b");
ASTElement elm5 = element("z");
tagList.openTag(elm);
tagList.openTag(elm2);
tagList.openTag(elm3);
tagList.openTag(elm4); // open b
tagList.closeTag(elm5); // close z
tagList.closeTag(elm2); // close a
tagList.closeTag(elm); // close x
assertFalse(elm.isUnclosed()); // x is closed
assertFalse(elm2.isUnclosed()); // a is closed
assertTrue(elm3.isUnclosed());
assertTrue(elm4.isUnclosed());
// elm5 ???
}
/**
* <a> <x> <a> <b> <b> </z> </a>
* </x>
*/
@Test
void openedIsolatedTag() {
ASTElement a = element("a");
ASTElement x = element("x");
ASTElement a2 = element("a");
ASTElement b = element("b");
ASTElement b2 = element("b");
ASTElement z = element("z");
tagList.openTag(a);
tagList.openTag(x);
tagList.openTag(a2);
tagList.openTag(b);
tagList.openTag(b2);
tagList.closeTag(z); // close z
tagList.closeTag(a2); // close second a
tagList.closeTag(x); // close x
assertTrue(a.isUnclosed()); // first a is unclosed
assertFalse(x.isUnclosed()); // x is closed
assertFalse(a2.isUnclosed()); // a is closed
assertTrue(b.isUnclosed());
assertTrue(b2.isUnclosed());
}
private ASTElement element(String name) {
ASTElement elm = new ASTElement(elmId++);
elm.setName(name);
return elm;
}
}
| 3,904 | 25.385135 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/VfExpressionTypeVisitorTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.vf.DataType;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
import net.sourceforge.pmd.util.treeexport.XmlTreeRenderer;
class VfExpressionTypeVisitorTest {
private static final Map<String, DataType> EXPECTED_CUSTOM_FIELD_DATA_TYPES;
private static final Map<String, DataType> EXPECTED_APEX_DATA_TYPES;
static {
EXPECTED_CUSTOM_FIELD_DATA_TYPES = new HashMap<>();
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("CreatedDate", DataType.DateTime);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("DateTime__c", DataType.DateTime);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("Checkbox__c", DataType.Checkbox);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("Name", DataType.Text);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("Text__c", DataType.Text);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("TextArea__c", DataType.TextArea);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("LongTextArea__c", DataType.LongTextArea);
EXPECTED_CUSTOM_FIELD_DATA_TYPES.put("Picklist__c", DataType.Picklist);
EXPECTED_APEX_DATA_TYPES = new HashMap<>();
EXPECTED_APEX_DATA_TYPES.put("AccountIdProp", DataType.Lookup);
EXPECTED_APEX_DATA_TYPES.put("AccountId", DataType.Lookup);
EXPECTED_APEX_DATA_TYPES.put("InnerAccountId", DataType.Lookup);
EXPECTED_APEX_DATA_TYPES.put("InnerAccountIdProp", DataType.Lookup);
EXPECTED_APEX_DATA_TYPES.put("AccountName", DataType.Text);
EXPECTED_APEX_DATA_TYPES.put("InnerAccountName", DataType.Text);
EXPECTED_APEX_DATA_TYPES.put("ConflictingProp", DataType.Unknown);
}
/**
* Strings that use dot notation(Account.CreatedDate) result in ASTIdentifier nodes
*/
@Test
void testXpathQueryForCustomFieldIdentifiers() {
Node rootNode = compile("StandardAccount.page");
for (Map.Entry<String, DataType> entry : EXPECTED_CUSTOM_FIELD_DATA_TYPES.entrySet()) {
List<ASTIdentifier> nodes = getIdentifiers(rootNode, entry);
// Each string appears twice, it is set on a "value" attribute and inline
assertEquals(2, nodes.size(), entry.getKey());
for (Node node : nodes) {
assertEquals(entry.getKey(), node.getImage());
assertTrue(node instanceof ASTIdentifier, node.getClass().getSimpleName());
ASTIdentifier identifier = (ASTIdentifier) node;
assertEquals(entry.getValue(), identifier.getDataType(), entry.getKey());
}
}
}
/**
* Strings that use array notation, Account['CreatedDate') don't have a DataType added. This type of notation
* creates ambiguous situations with Apex methods that return Maps. This may be addressed in a future release.
*/
@Test
void testXpathQueryForCustomFieldLiteralsHaveNullDataType() {
Node rootNode = compile("StandardAccount.page");
for (Map.Entry<String, DataType> entry : EXPECTED_CUSTOM_FIELD_DATA_TYPES.entrySet()) {
List<ASTLiteral> nodes = rootNode.descendants(ASTLiteral.class)
// Literals are surrounded by apostrophes
.filterMatching(ASTLiteral::getImage, "'" + entry.getKey() + "'")
.filterMatching(ASTLiteral::getDataType, null)
.toList();
// Each string appears twice, it is set on a "value" attribute and inline
assertEquals(2, nodes.size(), entry.getKey());
for (Node node : nodes) {
assertEquals(String.format("'%s'", entry.getKey()), node.getImage());
assertTrue(node instanceof ASTLiteral, node.getClass().getSimpleName());
ASTLiteral literal = (ASTLiteral) node;
assertNull(literal.getDataType(), entry.getKey());
}
}
}
/**
* Nodes where the DataType can't be determined should have a null DataType
*/
@Test
void testDataTypeForCustomFieldsNotFound() {
Node rootNode = compile("StandardAccount.page");
checkNodes(rootNode.descendants(ASTIdentifier.class)
.filterMatching(ASTIdentifier::getImage, "NotFoundField__c"));
checkNodes(rootNode.descendants(ASTLiteral.class)
.filterMatching(ASTLiteral::getImage, "'NotFoundField__c'"));
}
private void checkNodes(NodeStream<? extends VfTypedNode> nodeStream) {
// Each string appears twice, it is set on a "value" attribute and inline
List<? extends VfTypedNode> nodes = nodeStream.toList();
assertEquals(2, nodes.size());
for (VfTypedNode node : nodes) {
assertNull(node.getDataType());
}
}
/**
* Apex properties result in ASTIdentifier nodes
*/
@Test
void testXpathQueryForProperties() {
Node rootNode = compile("ApexController.page");
for (Map.Entry<String, DataType> entry : EXPECTED_APEX_DATA_TYPES.entrySet()) {
List<ASTIdentifier> nodes = getIdentifiers(rootNode, entry);
// Each string appears twice, it is set on a "value" attribute and inline
assertEquals(2, nodes.size(), entry.getKey());
for (Node node : nodes) {
assertEquals(entry.getKey(), node.getImage());
assertTrue(node instanceof ASTIdentifier, node.getClass().getSimpleName());
ASTIdentifier identifier = (ASTIdentifier) node;
assertEquals(entry.getValue(), identifier.getDataType(), entry.getKey());
}
}
}
private List<ASTIdentifier> getIdentifiers(Node rootNode, Entry<String, DataType> entry) {
return rootNode.descendants(ASTIdentifier.class)
.filterMatching(ASTIdentifier::getImage, entry.getKey())
.filterMatching(ASTIdentifier::getDataType, entry.getValue())
.toList();
}
/**
* Nodes where the DataType can't be determined should have a null DataType
*/
@Test
void testDataTypeForApexPropertiesNotFound() {
Node rootNode = compile("ApexController.page");
// Each string appears twice, it is set on a "value" attribute and inline
checkNodes(rootNode.descendants(ASTIdentifier.class)
.filterMatching(ASTIdentifier::getImage, "NotFoundProp"));
}
private Node compile(String pageName) {
return compile(pageName, false);
}
private Node compile(String pageName, boolean renderAST) {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve(pageName);
return compile(vfPagePath, renderAST);
}
private Node compile(Path vfPagePath, boolean renderAST) {
Node node = VfParsingHelper.DEFAULT.parseFile(vfPagePath);
assertNotNull(node);
if (renderAST) {
try {
new XmlTreeRenderer().renderSubtree(node, System.out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return node;
}
}
| 7,928 | 41.629032 | 121 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/ast/ObjectFieldTypesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.vf.DataType;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
import net.sourceforge.pmd.lang.vf.VfLanguageProperties;
class ObjectFieldTypesTest {
private static final Map<String, DataType> EXPECTED_SFDX_DATA_TYPES;
private static final Map<String, DataType> EXPECTED_MDAPI_DATA_TYPES;
static {
EXPECTED_SFDX_DATA_TYPES = new HashMap<>();
EXPECTED_SFDX_DATA_TYPES.put("Account.Checkbox__c", DataType.Checkbox);
EXPECTED_SFDX_DATA_TYPES.put("Account.DateTime__c", DataType.DateTime);
EXPECTED_SFDX_DATA_TYPES.put("Account.LongTextArea__c", DataType.LongTextArea);
EXPECTED_SFDX_DATA_TYPES.put("Account.Picklist__c", DataType.Picklist);
EXPECTED_SFDX_DATA_TYPES.put("Account.Text__c", DataType.Text);
EXPECTED_SFDX_DATA_TYPES.put("Account.TextArea__c", DataType.TextArea);
// Edge Cases
// Invalid property should return null
EXPECTED_SFDX_DATA_TYPES.put("Account.DoesNotExist__c", null);
EXPECTED_MDAPI_DATA_TYPES = new HashMap<>();
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDCheckbox__c", DataType.Checkbox);
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDDateTime__c", DataType.DateTime);
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDLongTextArea__c", DataType.LongTextArea);
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDPicklist__c", DataType.Picklist);
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDText__c", DataType.Text);
EXPECTED_MDAPI_DATA_TYPES.put("Account.MDTextArea__c", DataType.TextArea);
// Edge Cases
// Invalid property should return null
EXPECTED_MDAPI_DATA_TYPES.put("Account.DoesNotExist__c", null);
}
/**
* Verify that CustomFields stored in sfdx project format are correctly parsed
*/
@Test
void testSfdxAccountIsProperlyParsed() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf).resolve("SomePage.page");
ObjectFieldTypes objectFieldTypes = new ObjectFieldTypes();
validateSfdxAccount(objectFieldTypes, vfPagePath, VfLanguageProperties.OBJECTS_DIRECTORIES_DESCRIPTOR.defaultValue());
}
/**
* Verify that CustomFields stored in mdapi format are correctly parsed
*/
@Test
void testMdapiAccountIsProperlyParsed() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.MDAPI, VFTestUtils.MetadataType.Vf).resolve("SomePage.page");
ObjectFieldTypes objectFieldTypes = new ObjectFieldTypes();
validateMDAPIAccount(objectFieldTypes, vfPagePath, VfLanguageProperties.OBJECTS_DIRECTORIES_DESCRIPTOR.defaultValue());
}
/**
* Verify that fields are found across multiple directories
*/
@Test
void testFieldsAreFoundInMultipleDirectories() {
ObjectFieldTypes objectFieldTypes;
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve("SomePage.page");
List<String> paths = Arrays.asList(VfLanguageProperties.OBJECTS_DIRECTORIES_DESCRIPTOR.defaultValue().get(0),
VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.MDAPI, VFTestUtils.MetadataType.Objects).toString());
objectFieldTypes = new ObjectFieldTypes();
validateSfdxAccount(objectFieldTypes, vfPagePath, paths);
validateMDAPIAccount(objectFieldTypes, vfPagePath, paths);
Collections.reverse(paths);
objectFieldTypes = new ObjectFieldTypes();
validateSfdxAccount(objectFieldTypes, vfPagePath, paths);
validateMDAPIAccount(objectFieldTypes, vfPagePath, paths);
}
@Test
void testInvalidDirectoryDoesNotCauseAnException() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf).resolve("SomePage.page");
FileId vfFileName = FileId.fromPath(vfPagePath);
List<String> paths = Arrays.asList(Paths.get("..", "objects-does-not-exist").toString());
ObjectFieldTypes objectFieldTypes = new ObjectFieldTypes();
assertNull(objectFieldTypes.getDataType("Account.DoesNotExist__c", vfFileName, paths));
}
/**
* Validate the expected results when the Account Fields are stored in decomposed sfdx format
*/
private void validateSfdxAccount(ObjectFieldTypes objectFieldTypes, Path vfPagePath, List<String> paths) {
validateDataTypes(EXPECTED_SFDX_DATA_TYPES, objectFieldTypes, vfPagePath, paths);
}
/**
* Validate the expected results when the Account Fields are stored in a single file MDAPI format
*/
private void validateMDAPIAccount(ObjectFieldTypes objectFieldTypes, Path vfPagePath, List<String> paths) {
validateDataTypes(EXPECTED_MDAPI_DATA_TYPES, objectFieldTypes, vfPagePath, paths);
}
/**
* Verify that return values of {@link SalesforceFieldTypes#getDataType(String, FileId, List)} using the keys of
* {@code expectedDataTypes} matches the values of {@code expectedDataTypes}
*/
static void validateDataTypes(Map<String, DataType> expectedDataTypes, SalesforceFieldTypes fieldTypes,
Path vfPagePath, List<String> paths) {
FileId vfFileName = FileId.fromPath(vfPagePath);
for (Map.Entry<String, DataType> entry : expectedDataTypes.entrySet()) {
assertEquals(entry.getValue(), fieldTypes.getDataType(entry.getKey(), vfFileName, paths), entry.getKey());
}
}
}
| 6,143 | 45.195489 | 157 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/cpd/VfTokenizerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.VfTokenizer;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class VfTokenizerTest extends CpdTextComparisonTest {
VfTokenizerTest() {
super(".page");
}
@Override
public Tokenizer newTokenizer(Properties properties) {
VfTokenizer tokenizer = new VfTokenizer();
return tokenizer;
}
@Test
void testTokenize() {
doTest("SampleUnescapeElWithTab");
}
}
| 697 | 20.151515 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/rule/security/VfHtmlStyleTagXssTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class VfHtmlStyleTagXssTest extends PmdRuleTst {
// no additional unit tests
}
| 278 | 22.25 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/rule/security/VfUnescapeElTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.vf.VFTestUtils;
import net.sourceforge.pmd.lang.vf.ast.VfParsingHelper;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class VfUnescapeElTest extends PmdRuleTst {
private static final String EXPECTED_RULE_MESSAGE = "Avoid unescaped user controlled content in EL";
/**
* Verify that CustomFields stored in sfdx project format are correctly parsed
*/
@Test
void testSfdxCustomFields() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve("StandardAccount.page");
Report report = runRule(vfPagePath);
List<RuleViolation> ruleViolations = report.getViolations();
assertEquals(20, ruleViolations.size(), "Number of violations");
int firstLineWithErrors = 14;
for (int i = 0; i < ruleViolations.size(); i++) {
RuleViolation ruleViolation = ruleViolations.get(i);
assertEquals(EXPECTED_RULE_MESSAGE, ruleViolation.getDescription());
int expectedLineNumber = firstLineWithErrors + i;
if (ruleViolations.size() + firstLineWithErrors - 1 == expectedLineNumber) {
// The last line has two errors on the same page
expectedLineNumber = expectedLineNumber - 1;
}
assertEquals(expectedLineNumber, ruleViolation.getBeginLine(), "Line Number");
}
}
/**
* Verify that CustomFields stored in mdapi format are correctly parsed
*/
@Test
void testMdapiCustomFields() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.MDAPI, VFTestUtils.MetadataType.Vf).resolve("StandardAccount.page");
Report report = runRule(vfPagePath);
List<RuleViolation> ruleViolations = report.getViolations();
assertEquals(6, ruleViolations.size(), "Number of violations");
int firstLineWithErrors = 8;
for (int i = 0; i < ruleViolations.size(); i++) {
RuleViolation ruleViolation = ruleViolations.get(i);
assertEquals(EXPECTED_RULE_MESSAGE, ruleViolation.getDescription());
assertEquals(firstLineWithErrors + i, ruleViolation.getBeginLine(), "Line Number");
}
}
/**
* Tests a page with a single Apex controller
*/
@Test
void testApexController() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf).resolve("ApexController.page");
Report report = runRule(vfPagePath);
List<RuleViolation> ruleViolations = report.getViolations();
assertEquals(2, ruleViolations.size(), "Number of violations");
int firstLineWithErrors = 9;
for (int i = 0; i < ruleViolations.size(); i++) {
// There should start at line 9
RuleViolation ruleViolation = ruleViolations.get(i);
assertEquals(EXPECTED_RULE_MESSAGE, ruleViolation.getDescription());
assertEquals(firstLineWithErrors + i, ruleViolation.getBeginLine(), "Line Number");
}
}
/**
* Tests a page with a standard controller and two Apex extensions
*/
@Test
void testExtensions() {
Path vfPagePath = VFTestUtils.getMetadataPath(this, VFTestUtils.MetadataFormat.SFDX, VFTestUtils.MetadataType.Vf)
.resolve(Paths.get("StandardAccountWithExtensions.page"));
Report report = runRule(vfPagePath);
List<RuleViolation> ruleViolations = report.getViolations();
assertEquals(8, ruleViolations.size());
int firstLineWithErrors = 9;
for (int i = 0; i < ruleViolations.size(); i++) {
RuleViolation ruleViolation = ruleViolations.get(i);
assertEquals(EXPECTED_RULE_MESSAGE, ruleViolation.getDescription());
assertEquals(firstLineWithErrors + i, ruleViolation.getBeginLine());
}
}
/**
* Runs a rule against a Visualforce page on the file system.
*/
private Report runRule(Path vfPagePath) {
Rule rule = findRule("category/vf/security.xml", "VfUnescapeEl");
return VfParsingHelper.DEFAULT.executeRuleOnFile(rule, vfPagePath);
}
}
| 4,672 | 39.991228 | 155 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/rule/security/VfHtmlXssStyleTagUrlPatternMatchingTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/***
* Unit tests to focus on regex pattern used to identify URL methods within style tags
*/
class VfHtmlXssStyleTagUrlPatternMatchingTest {
@Test
void testUrlMethodPatternMatchForPositive() {
final String sampleString = "div { background: url(blah";
assertTrue(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForCaseInsensitive() {
final String sampleString = "div { background: uRl(";
assertTrue(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForWhitespaceAfterUrl() {
final String sampleString = "div { background: url (";
assertTrue(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForClosedUrl() {
final String sampleString = "div { background: url('myUrl')";
assertFalse(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should not be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForClosedUrlWithNoContent() {
final String sampleString = "div { background: url() ";
assertFalse(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should not be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForUrlNoBracket() {
final String sampleString = "div { background: url";
assertFalse(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should not be considered as starting a URL method: " + sampleString);
}
@Test
void testUrlMethodPatternMatchForNoUrl() {
final String sampleString = "div { background: myStyle('";
assertFalse(VfHtmlStyleTagXssRule.isWithinUrlMethod(sampleString), "Sample should not be considered as starting a URL method: " + sampleString);
}
}
| 2,462 | 40.05 | 152 | java |
pmd | pmd-master/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/rule/security/VfCsrfTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class VfCsrfTest extends PmdRuleTst {
// no additional unit tests
}
| 267 | 21.333333 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/VfHandler.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.vf.ast.VfParser;
public class VfHandler implements LanguageVersionHandler {
private final VfLanguageProperties properties;
public VfHandler(VfLanguageProperties properties) {
this.properties = properties;
}
@Override
public Parser getParser() {
return new VfParser(properties);
}
}
| 584 | 23.375 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/VfLanguageProperties.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import java.io.File;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* @author Clément Fournier
*/
public class VfLanguageProperties extends LanguagePropertyBundle {
static final List<String> DEFAULT_APEX_DIRECTORIES = Collections.singletonList(".." + File.separator + "classes");
/**
* Directory that contains Apex classes that may be referenced from a Visualforce page.
*
* <p>Env variable is {@code PMD_VF_APEXDIRECTORIES}.
*/
public static final PropertyDescriptor<List<String>> APEX_DIRECTORIES_DESCRIPTOR =
PropertyFactory.stringListProperty("apexDirectories")
.desc("Location of Apex Class directories. Absolute or relative to the Visualforce directory.")
.defaultValue(DEFAULT_APEX_DIRECTORIES)
.delim(',')
.build();
static final List<String> DEFAULT_OBJECT_DIRECTORIES = Collections.singletonList(".." + File.separator + "objects");
/**
* Directory that contains Object definitions that may be referenced from a Visualforce page.
*
* <p>Env variable is {@code PMD_VF_OBJECTSDIRECTORIES}.
*/
public static final PropertyDescriptor<List<String>> OBJECTS_DIRECTORIES_DESCRIPTOR =
PropertyFactory.stringListProperty("objectsDirectories")
.desc("Location of Custom Object directories. Absolute or relative to the Visualforce directory.")
.defaultValue(DEFAULT_OBJECT_DIRECTORIES)
.delim(',')
.build();
public VfLanguageProperties() {
super(VfLanguageModule.getInstance());
definePropertyDescriptor(APEX_DIRECTORIES_DESCRIPTOR);
definePropertyDescriptor(OBJECTS_DIRECTORIES_DESCRIPTOR);
}
}
| 2,102 | 38.679245 | 121 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/DataType.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import apex.jorje.semantic.symbol.type.BasicType;
/**
* Represents all data types that can be referenced from a Visualforce page. This enum consolidates the data types
* available to CustomFields and Apex. It uses the naming convention of CustomFields.
*
* See https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_field_types.htm#meta_type_fieldtype
*/
public enum DataType {
AutoNumber(false),
Checkbox(false, "Boolean"),
Currency(false, "Currency"),
Date(false, "Date"),
DateTime(false, "Datetime"),
Email(false),
EncryptedText(true),
ExternalLookup(true),
File(false),
Hierarchy(false),
Html(false),
IndirectLookup(false),
Location(false),
LongTextArea(true),
Lookup(false, "ID"),
MasterDetail(false),
MetadataRelationship(false),
MultiselectPicklist(true),
Note(true),
Number(false, "Decimal", "Double", "Integer", "Long"),
Percent(false),
Phone(false),
Picklist(true),
Summary(false),
Text(true, "String"),
TextArea(true),
Time(false, "Time"),
Url(false),
/**
* Indicates that Metatada was found, but it's type was not mappable. This could because it is a type which isn't
* mapped, or it was an edge case where the type was ambiguously defined in the Metadata.
*/
Unknown(true);
private static final Logger LOG = LoggerFactory.getLogger(DataType.class);
/**
* True if this field is an XSS risk
*/
public final boolean requiresEscaping;
/**
* The set of primitive type names that map to this type. Multiple types can map to a single instance of this enum.
* Note: these strings are not case-normalized.
*/
private final Set<String> basicTypeNames;
/**
* A map of the lower-case-normalized enum name to its instance. The case metadata is not guaranteed to have the correct
* case.
*/
private static final Map<String, DataType> CASE_NORMALIZED_MAP = new HashMap<>();
/**
* A map of the lower-case-normalized primitive type names to DataType. Multiple types may map to one DataType.
*/
private static final Map<String, DataType> BASIC_TYPE_MAP = new HashMap<>();
static {
for (DataType dataType : DataType.values()) {
CASE_NORMALIZED_MAP.put(dataType.name().toLowerCase(Locale.ROOT), dataType);
for (String typeName : dataType.basicTypeNames) {
BASIC_TYPE_MAP.put(typeName.toLowerCase(Locale.ROOT), dataType);
}
}
}
/**
* Map to correct instance, returns {@code Unknown} if the value can't be mapped.
*/
public static DataType fromString(String value) {
value = value != null ? value : "";
DataType dataType = CASE_NORMALIZED_MAP.get(value.toLowerCase(Locale.ROOT));
if (dataType == null) {
dataType = DataType.Unknown;
LOG.debug("Unable to determine DataType of {}", value);
}
return dataType;
}
/**
* Map to correct instance, returns {@code Unknown} if the value can't be mapped.
*
* @deprecated Use {@link #fromTypeName(String)} instead.
*/
@Deprecated
public static DataType fromBasicType(BasicType value) {
if (value != null) {
switch (value) {
case BOOLEAN:
return Checkbox;
case CURRENCY:
return Currency;
case DATE:
return Date;
case DATE_TIME:
return DateTime;
case ID:
return Lookup;
case DECIMAL:
case DOUBLE:
case INTEGER:
case LONG:
return Number;
case STRING:
return Text;
case TIME:
return Time;
default:
break;
}
}
LOG.debug("Unable to determine DataType of {}", value);
return Unknown;
}
/**
* Map to correct instance, returns {@code Unknown} if the value can't be mapped.
*/
public static DataType fromTypeName(String value) {
value = value != null ? value : "";
DataType dataType = BASIC_TYPE_MAP.get(value.toLowerCase(Locale.ROOT));
if (dataType == null) {
dataType = DataType.Unknown;
LOG.debug("Unable to determine DataType of {}", value);
}
return dataType;
}
DataType(boolean requiresEscaping) {
this(requiresEscaping, null);
}
DataType(boolean requiresEscaping, String... basicTypeNames) {
this.requiresEscaping = requiresEscaping;
this.basicTypeNames = new HashSet<>();
if (basicTypeNames != null) {
this.basicTypeNames.addAll(Arrays.asList(basicTypeNames));
}
}
}
| 5,189 | 29.174419 | 124 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/VfLanguageModule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.List;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* @author sergey.gorbaty
*/
public class VfLanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "Salesforce VisualForce";
public static final String TERSE_NAME = "vf";
@InternalApi
public static final List<String> EXTENSIONS = listOf("page", "component");
public VfLanguageModule() {
super(createMetdata(),
p -> new VfHandler((VfLanguageProperties) p));
}
private static LanguageMetadata createMetdata() {
LanguageMetadata languageMetadata =
LanguageMetadata.withId(TERSE_NAME).name(NAME)
.extensions(EXTENSIONS)
.dependsOnLanguage(ApexLanguageModule.TERSE_NAME);
// use the same versions as in Apex
// need to create a temporary apex module, since the global language registry is not initialized yet
ApexLanguageModule temporaryApexModule = new ApexLanguageModule();
LanguageVersion defaultApexVersion = temporaryApexModule.getDefaultVersion();
for (LanguageVersion languageVersion : temporaryApexModule.getVersions()) {
if (!defaultApexVersion.equals(languageVersion)) {
languageMetadata.addVersion(languageVersion.getVersion());
}
}
languageMetadata.addDefaultVersion(defaultApexVersion.getVersion());
return languageMetadata;
}
@Override
public LanguagePropertyBundle newPropertyBundle() {
return new VfLanguageProperties();
}
public static Language getInstance() {
return LanguageRegistry.PMD.getLanguageByFullName(NAME);
}
}
| 2,237 | 35.688525 | 108 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfAstInternals.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* This is internal API, and can be changed at any time.
*/
@InternalApi
public final class VfAstInternals {
private VfAstInternals() {
// utility class
}
public static void setDataType(VfTypedNode node, DataType dataType) {
((AbstractVFDataNode) node).setDataType(dataType);
}
}
| 547 | 21.833333 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/AbstractVFDataNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* Represents a node that displays a piece of data.
*/
abstract class AbstractVFDataNode extends AbstractVfNode implements VfTypedNode {
private DataType dataType;
AbstractVFDataNode(int id) {
super(id);
}
@Override
public DataType getDataType() {
return dataType;
}
void setDataType(DataType dataType) {
this.dataType = dataType;
}
}
| 576 | 18.896552 | 81 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfTypedNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* Represents a node that displays a piece of data.
*/
public interface VfTypedNode extends VfNode {
/**
* Returns the data type this node refers to. A null value indicates that no matching Metadata was found for this
* node. null differs from {@link DataType#Unknown} which indicates that Metadata was found but it wasn't mappable
* to one of the enums.
*
* <p>Example XPath 1.0 and 2.0: {@code //Identifier[@DataType='DateTime']}
*/
DataType getDataType();
}
| 681 | 28.652174 | 118 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTElExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTElExpression extends AbstractVfNode {
ASTElExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 402 | 22.705882 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTLiteral.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTLiteral extends AbstractVFDataNode {
ASTLiteral(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 397 | 21.111111 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/SalesforceFieldTypes.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* Responsible for storing a mapping of Fields that can be referenced from Visualforce to the type of the field. The
* fields are identified by in a case insensitive manner.
*/
abstract class SalesforceFieldTypes {
/**
* Cache of lowercase variable names to the variable type declared in the field's metadata file.
*/
private final Map<String, DataType> variableNameToVariableType;
/**
* Keep track of which variables were already processed. Avoid processing if a page repeatedly asks for an entry
* which we haven't previously found.
*/
private final Set<String> variableNameProcessed;
SalesforceFieldTypes() {
this.variableNameToVariableType = new HashMap<>();
this.variableNameProcessed = new HashSet<>();
}
/**
*
* @param expression expression literal as declared in the Visualforce page
* @param vfFileName file name of the Visualforce page that contains expression. Used to resolve relative paths
* included in {@code metadataDirectories}
* @param metadataDirectories absolute or relative list of directories that may contain the metadata corresponding
* to {@code expression}
* @return the DataType if it can be determined, else null
*/
public DataType getDataType(String expression, FileId vfFileName, List<String> metadataDirectories) {
String lowerExpression = expression.toLowerCase(Locale.ROOT);
if (variableNameToVariableType.containsKey(lowerExpression)) {
// The expression has been previously retrieved
return variableNameToVariableType.get(lowerExpression);
} else if (variableNameProcessed.contains(lowerExpression)) {
// The expression has been previously requested, but was not found
return null;
} else {
// todo that could be done in the caller
Path vfFilePath = Paths.get(vfFileName.getAbsolutePath());
List<Path> resolvedPaths = new ArrayList<>();
for (String metadataDirectory : metadataDirectories) {
if (Paths.get(metadataDirectory).isAbsolute()) {
resolvedPaths.add(Paths.get(metadataDirectory));
} else {
resolvedPaths.add(vfFilePath.getParent().resolve(metadataDirectory));
}
}
findDataType(expression, resolvedPaths);
variableNameProcessed.add(lowerExpression);
return variableNameToVariableType.get(lowerExpression);
}
}
/**
* Stores {@link DataType} in a map using lower cased {@code expression} as the key.
* @param expression expression literal as declared in the Visualforce page
* @param dataType identifier determined for
* @return the previous value associated with {@code key}, or {@code null} if there was no mapping for {@code key}.
*/
protected DataType putDataType(String expression, DataType dataType) {
return variableNameToVariableType.put(expression.toLowerCase(Locale.ROOT), dataType);
}
/**
* @return true if the expression has previously been stored via {@link #putDataType(String, DataType)}
*/
protected boolean containsExpression(String expression) {
return variableNameToVariableType.containsKey(expression.toLowerCase(Locale.ROOT));
}
/**
* Subclasses should attempt to find the {@code DataType} of {@code expression} within
* {@code metadataDirectories}. The subclass should store the value by invoking
* {@link #putDataType(String, DataType)}.
*
* @param expression expression as defined in the Visualforce page, case is preserved
* @param metadataDirectories list of directories that may contain the metadata corresponding to {@code expression}
*/
protected abstract void findDataType(String expression, List<Path> metadataDirectories);
}
| 4,417 | 41.480769 | 119 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTDeclaration.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTDeclaration extends AbstractVfNode {
private String name;
ASTDeclaration(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 550 | 18.678571 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTContent.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTContent extends AbstractVfNode {
ASTContent(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 393 | 20.888889 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.ast.Node;
public final class ASTExpression extends AbstractVfNode {
private static final Logger LOG = LoggerFactory.getLogger(ASTExpression.class);
ASTExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
private void logWarning(String warning, Node node) {
LOG.warn("{}: {}\n{}",
node.getReportLocation().startPosToStringWithFile(),
warning,
node);
}
/**
* <p>
* An Expression can contain one or more strings that map to a piece of data. This method maps the string
* from the Visualforce page to terminal AST node that the string represents. The terminal node will be either an
* ASTIdentifier or ASTLiteral. It is the terminal node that is most important since it represents the type of data
* that will be displayed in the page.
* </p>
* <p>
* The string representation can be reconstructed by starting at the {@code Identifier} node and traversing its
* siblings until a node other than a {@code DotExpression} is encountered. Some more advanced situations aren't
* currently handled by this method. The method will throw an exception in such cases.
* </p>
* <pre>{@code
* <apex:outputText value="{!MyValue}" /> results in AST
* <Identifier Image='MyValue'/>
* The method would return key=ASTIdentifier(Image='MyValue'), value="MyValue"
* }</pre>
* <pre>{@code
* <apex:outputText value="{!MyObject__c.Text__c}" /> results in AST (It's important to notice that DotExpression is
* a sibling of Identifier.
* <Identifier Image='MyObject__c'/>
* <DotExpression Image=''>
* <Identifier Image='Text__c'/>
* </DotExpression>
* This method would return key=ASTIdentifier(Image='Text__c'), value="MyObject__c.Text__c"
* }</pre>
*
* THE FOLLOWING SITUATIONS ARE NOT HANDLED AND WILL THROW AN EXCEPTION.
* This syntax causes ambiguities with Apex Controller methods that return Maps versus accessing a CustomObject's
* field via array notation. This may be addressed in a future release.
*
* <pre>{@code
* <apex:outputText value="{!MyObject__c['Text__c']}" /> results in AST
* <Identifier Image='MyObject__c'/>
* <Expression Image=''>
* <Literal Image=''Text__c''>
* </Expression>
* <apex:outputText value="{!MyObject__c[AnotherObject__c.Id]}" /> results in AST
* <Identifier Image='MyObject__c'/>
* <Expression Image=''>
* <Identifier Image='AnotherObject__c'/>
* <DotExpression Image=''>
* <Identifier Image='Id'/>
* </DotExpression>
* </Identifier>
* </Expression>
* }</pre>
*
* @throws DataNodeStateException if the results of this method could have been incorrect. Callers should typically
* not rethrow this exception, as it will happen often and doesn't represent a terminal exception.
*/
public Map<VfTypedNode, String> getDataNodes() throws DataNodeStateException {
Map<VfTypedNode, String> result = new IdentityHashMap<>();
int numChildren = getNumChildren();
List<ASTIdentifier> identifiers = findChildrenOfType(ASTIdentifier.class);
for (ASTIdentifier identifier : identifiers) {
@SuppressWarnings("PMD.LooseCoupling") // see #1218 - we are calling getLast() which is LinkedList specific
LinkedList<VfTypedNode> identifierNodes = new LinkedList<>();
// The Identifier is the first item that makes up the string
identifierNodes.add(identifier);
int index = identifier.getIndexInParent();
// Iterate through the rest of the children looking for ASTDotExpression nodes.
// The Image value of these nodes will be used to reconstruct the string. Any other node encountered will
// cause the while loop to break. The content of identifierNodes is used to construct the string and map
// it to the last element in identifierNodes.
index++;
while (index < numChildren) {
final Node node = getChild(index);
if (node instanceof ASTDotExpression) {
// The next part of the identifier will constructed from dot or array notation
if (node.getNumChildren() == 1) {
final Node expressionChild = node.getChild(0);
if (expressionChild instanceof ASTIdentifier || expressionChild instanceof ASTLiteral) {
identifierNodes.add((VfTypedNode) expressionChild);
} else {
// This should never happen
logWarning("Node expected to be Identifier or Literal", node);
throw new DataNodeStateException();
}
} else {
// This should never happen
logWarning("More than one child found for ASTDotExpression", node);
throw new DataNodeStateException();
}
} else if (node instanceof ASTExpression) {
// Not currently supported. This can occur in a couple of cases that may be supported in the future.
// 1. Custom Field using array notation. MyObject__c['Text__c']
// 2. An Apex method that returns a map. ControllerMethod['KeyForMap']
throw new DataNodeStateException();
} else {
// Any other node type is not considered part of the identifier and breaks out of the loop
break;
}
index++;
}
// Convert the list of nodes to a string representation, store the last node in the list as the map's key
String idString = String.join(".", identifierNodes.stream()
.map(i -> i.getImage())
.collect(Collectors.toList()));
result.put(identifierNodes.getLast(), idString);
}
return result;
}
/**
* Thrown in cases where the the Identifiers in this node aren't ALL successfully parsed in a call to
* {@link #getDataNodes()}
*/
public static final class DataNodeStateException extends Exception {
}
}
| 6,942 | 43.793548 | 120 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeParserAdapter;
import net.sourceforge.pmd.lang.vf.VfLanguageProperties;
/**
* Parser for the VisualForce language.
*/
public final class VfParser extends JjtreeParserAdapter<ASTCompilationUnit> {
private VfLanguageProperties vfProperties;
public VfParser(VfLanguageProperties vfProperties) {
this.vfProperties = vfProperties;
}
private static final TokenDocumentBehavior TOKEN_BEHAVIOR = new TokenDocumentBehavior(VfTokenKinds.TOKEN_NAMES);
@Override
protected TokenDocumentBehavior tokenBehavior() {
return TOKEN_BEHAVIOR;
}
@Override
protected ASTCompilationUnit parseImpl(CharStream cs, ParserTask task) throws ParseException {
ASTCompilationUnit root = new VfParserImpl(cs).CompilationUnit().makeTaskInfo(task);
// Add type information to the AST
VfExpressionTypeVisitor visitor = new VfExpressionTypeVisitor(task, vfProperties);
visitor.visit(root, null);
return root;
}
}
| 1,372 | 30.930233 | 116 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/OpenTagRegister.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* Utility class to keep track of unclosed tags. The mechanism is rather simple.
* If a end tag (</x>) is encountered, it will iterate through the open
* tag list and it will mark the first tag named 'x' as closed. If other tags
* have been opened after 'x' ( <x> <y> <z> </x>) it
* will mark y and z as unclosed.
*
* @author Victor Bucutea
*
*/
@InternalApi
class OpenTagRegister {
private List<ASTElement> tagList = new ArrayList<>();
public void openTag(ASTElement elm) {
if (elm == null || StringUtils.isBlank(elm.getName())) {
throw new IllegalStateException("Tried to open a tag with empty name");
}
tagList.add(elm);
}
/**
*
* @param closingTagName
* @return true if a matching tag was found. False if no tag with this name
* was ever opened ( or registered )
*/
public boolean closeTag(String closingTagName) {
if (StringUtils.isBlank(closingTagName)) {
throw new IllegalStateException("Tried to close a tag with empty name");
}
int lastRegisteredTagIdx = tagList.size() - 1;
/*
* iterate from top to bottom and look for the last tag with the same
* name as element
*/
boolean matchingTagFound = false;
List<ASTElement> processedElements = new ArrayList<>();
for (int i = lastRegisteredTagIdx; i >= 0; i--) {
ASTElement parent = tagList.get(i);
String parentName = parent.getName();
processedElements.add(parent);
if (parentName.equals(closingTagName)) {
// mark this tag as being closed
parent.setUnclosed(false);
// tag has children it cannot be empty
parent.setEmpty(false);
matchingTagFound = true;
break;
} else {
// only mark as unclosed if tag is not
// empty (e.g. <tag/> is empty and properly closed)
if (!parent.isEmpty()) {
parent.setUnclosed(true);
}
parent.setEmpty(true);
}
}
/*
* remove all processed tags. We should look for rogue tags which have
* no start (unopened tags) e.g. " <a> <b> <b> </z> </a>" if "</z>" has
* no open tag in the list (and in the whole document) we will consider
* </a> as the closing tag for <a>.If on the other hand tags are
* interleaved: <x> <a> <b> <b> </x> </a> then we will consider </x> the
* closing tag of <x> and </a> a rogue tag or the closing tag of a
* potentially open <a> parent tag ( but not the one after the <x> )
*/
if (matchingTagFound) {
tagList.removeAll(processedElements);
}
return matchingTagFound;
}
public void closeTag(ASTElement z) {
closeTag(z.getName());
}
}
| 3,269 | 32.367347 | 84 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTNegationExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTNegationExpression extends AbstractVfNode {
ASTNegationExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 414 | 23.411765 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfExpressionTypeVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.vf.DataType;
import net.sourceforge.pmd.lang.vf.VfLanguageProperties;
/**
* Visits {@link ASTExpression} nodes and stores type information for
* {@link net.sourceforge.pmd.lang.vf.ast.ASTIdentifier} children that represent an IdentifierDotted construct. An
* IdentifierDotted is of the form {@code MyObject__c.MyField__c}.
*/
class VfExpressionTypeVisitor extends VfVisitorBase<Void, Void> {
private static final Logger LOG = LoggerFactory.getLogger(VfExpressionTypeVisitor.class);
private static final String APEX_PAGE = "apex:page";
private static final String CONTROLLER_ATTRIBUTE = "controller";
private static final String STANDARD_CONTROLLER_ATTRIBUTE = "standardcontroller";
private static final String EXTENSIONS_ATTRIBUTE = "extensions";
private final ApexClassPropertyTypes apexClassPropertyTypes;
private final ObjectFieldTypes objectFieldTypes;
private final FileId fileId;
private String standardControllerName;
/**
* List of all Apex Class names that the VF page might refer to. These values come from either the
* {@code controller} or {@code extensions} attribute.
*/
private final List<String> apexClassNames;
// todo make those lists of Path
private final List<String> apexDirectories;
private final List<String> objectsDirectories;
VfExpressionTypeVisitor(ParserTask task, VfLanguageProperties vfProperties) {
this.fileId = task.getTextDocument().getFileId();
this.apexDirectories = vfProperties.getProperty(VfLanguageProperties.APEX_DIRECTORIES_DESCRIPTOR);
this.objectsDirectories = vfProperties.getProperty(VfLanguageProperties.OBJECTS_DIRECTORIES_DESCRIPTOR);
this.apexClassNames = new ArrayList<>();
this.apexClassPropertyTypes = new ApexClassPropertyTypes(task.getLpRegistry());
this.objectFieldTypes = new ObjectFieldTypes();
}
@Override
public Void visit(ASTCompilationUnit node, Void data) {
if (apexDirectories.isEmpty() && objectsDirectories.isEmpty()) {
// Skip visiting if there aren't any directories to look in
return data;
}
return super.visit(node, data);
}
/**
* Gather names of Controller, Extensions, and StandardController. Each of these may contain the identifier
* referenced from the Visualforce page.
*/
@Override
public Void visit(ASTElement node, Void data) {
if (APEX_PAGE.equalsIgnoreCase(node.getName())) {
for (ASTAttribute attr : node.children(ASTAttribute.class)) {
String lowerAttr = attr.getName().toLowerCase(Locale.ROOT);
if (CONTROLLER_ATTRIBUTE.equals(lowerAttr)) {
// Controller Name should always take precedence
apexClassNames.add(0, getAttrValue(attr));
break;
} else if (STANDARD_CONTROLLER_ATTRIBUTE.equals(lowerAttr)) {
standardControllerName = getAttrValue(attr).toLowerCase(Locale.ROOT);
} else if (EXTENSIONS_ATTRIBUTE.equalsIgnoreCase(lowerAttr)) {
for (String extension : getAttrValue(attr).split(",")) {
apexClassNames.add(extension.trim());
}
}
}
}
return super.visit(node, data);
}
private static String getAttrValue(ASTAttribute attr) {
return attr.firstChild(ASTAttributeValue.class)
.firstChild(ASTText.class)
.getImage();
}
/**
* Invoke {@link ASTExpression#getDataNodes()} on all children of {@code node} and attempt to determine the
* {@link DataType} by looking at Apex or CustomField metadata.
*/
@Override
public Void visit(ASTElExpression node, Void data) {
for (Map.Entry<VfTypedNode, String> entry : getDataNodeNames(node).entrySet()) {
String name = entry.getValue();
DataType type = null;
String[] parts = name.split("\\.");
// Apex extensions take precedence over Standard controllers.
// The example below will display "Name From Inner Class" instead of the Account name
// public class AccountExtension {
// public AccountExtension(ApexPages.StandardController controller) {
// }
//
// public InnerClass getAccount() {
// return new InnerClass();
// }
//
// public class InnerClass {
// public String getName() {
// return 'Name From Inner Class';
// }
// }
// }
//<apex:page standardController="Account" extensions="AccountExtension">
// <apex:outputText value="{!Account.Name}" escape="false"/>
//</apex:page>
// Try to find the identifier in an Apex class
for (String apexClassName : apexClassNames) {
String fullName = apexClassName + "." + name;
type = apexClassPropertyTypes.getDataType(fullName, fileId, apexDirectories);
if (type != null) {
break;
}
}
// Try to find the identifier in a CustomField if it wasn't found in an Apex class and the identifier corresponds
// to the StandardController.
if (type == null) {
if (parts.length >= 2 && standardControllerName != null && standardControllerName.equalsIgnoreCase(parts[0])) {
type = objectFieldTypes.getDataType(name, fileId, objectsDirectories);
}
}
if (type != null) {
VfAstInternals.setDataType(entry.getKey(), type);
} else {
LOG.debug("Unable to determine type for: {}", name);
}
}
return super.visit(node, data);
}
/**
* Invoke {@link ASTExpression#getDataNodes()} for all {@link ASTExpression} children of {@code node} and return
* the consolidated results.
*/
private Map<VfTypedNode, String> getDataNodeNames(ASTElExpression node) {
Map<VfTypedNode, String> dataNodeToName = new IdentityHashMap<>();
for (ASTExpression expression : node.children(ASTExpression.class)) {
try {
dataNodeToName.putAll(expression.getDataNodes());
} catch (ASTExpression.DataNodeStateException ignored) {
// Intentionally left blank
}
}
return dataNodeToName;
}
}
| 7,111 | 39.873563 | 127 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTDoctypeDeclaration.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTDoctypeDeclaration extends AbstractVfNode {
/**
* Name of the document type. Cannot be null.
*/
private String name;
ASTDoctypeDeclaration(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 630 | 19.354839 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTText.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTText extends AbstractVfNode {
ASTText(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 387 | 20.555556 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfParserVisitorAdapter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
@Deprecated
@DeprecatedUntil700
public class VfParserVisitorAdapter extends VfVisitorBase<Object, Object> implements VfParserVisitor {
}
| 327 | 22.428571 | 102 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTDotExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTDotExpression extends AbstractVfNode {
ASTDotExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 405 | 21.555556 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTAttribute.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTAttribute extends AbstractVfNode {
private String name;
ASTAttribute(int id) {
super(id);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
/**
* @return boolean - true if the element has a namespace-prefix, false
* otherwise
*/
public boolean isHasNamespacePrefix() {
return name.indexOf(':') >= 0;
}
/**
* @return String - the part of the name that is before the (first) colon
* (":")
*/
public String getNamespacePrefix() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(0, colonIndex) : "";
}
/**
* @return String - The part of the name that is after the first colon
* (":"). If the name does not contain a colon, the full name is
* returned.
*/
public String getLocalName() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(colonIndex + 1) : name;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,380 | 23.660714 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfParserVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
@Deprecated
@DeprecatedUntil700
public interface VfParserVisitor extends VfVisitor<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-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ApexClassPropertyTypes.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.apex.ApexLanguageModule;
import net.sourceforge.pmd.lang.apex.ApexLanguageProcessor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* Responsible for storing a mapping of Apex Class properties that can be referenced from Visualforce to the type of the
* property.
*/
class ApexClassPropertyTypes extends SalesforceFieldTypes {
private static final Logger LOG = LoggerFactory.getLogger(ApexClassPropertyTypes.class);
private static final String APEX_CLASS_FILE_SUFFIX = ".cls";
private final ApexLanguageProcessor apexProcessor;
private final LanguageProcessorRegistry lpReg;
ApexClassPropertyTypes(LanguageProcessorRegistry lpReg) {
this.apexProcessor = (ApexLanguageProcessor) lpReg.getProcessor(ApexLanguageModule.getInstance());
this.lpReg = lpReg;
}
/**
* Looks in {@code apexDirectories} for an Apex property identified by {@code expression}.
*/
@Override
public void findDataType(String expression, List<Path> apexDirectories) {
String[] parts = expression.split("\\.");
if (parts.length >= 2) {
// Load the class and parse it
String className = parts[0];
for (Path apexDirectory : apexDirectories) {
Path apexFilePath = apexDirectory.resolve(className + APEX_CLASS_FILE_SUFFIX);
if (Files.exists(apexFilePath) && Files.isRegularFile(apexFilePath)) {
Node node = parseApex(expression, apexFilePath);
ApexClassPropertyTypesVisitor visitor = new ApexClassPropertyTypesVisitor();
node.acceptVisitor(visitor, null);
for (Pair<String, String> variable : visitor.getVariables()) {
putDataType(variable.getKey(), DataType.fromTypeName(variable.getValue()));
}
if (containsExpression(expression)) {
// Break out of the loop if a variable was found
break;
}
}
}
}
}
Node parseApex(Path apexFilePath) {
LanguageVersion languageVersion = apexProcessor.getLanguageVersion();
try (TextFile file = TextFile.forPath(apexFilePath, StandardCharsets.UTF_8, languageVersion);
TextDocument textDocument = TextDocument.create(file)) {
Parser parser = apexProcessor.services().getParser();
ParserTask task = new ParserTask(textDocument, SemanticErrorReporter.noop(), lpReg);
return parser.parse(task);
} catch (IOException e) {
throw new ContextedRuntimeException(e).addContextValue("apexFilePath", apexFilePath);
}
}
private Node parseApex(String contextExpr, Path apexFilePath) {
try {
return parseApex(apexFilePath);
} catch (ContextedRuntimeException e) {
throw e.addContextValue("expression", contextExpr);
}
}
@Override
protected DataType putDataType(String name, DataType dataType) {
DataType previousType = super.putDataType(name, dataType);
if (previousType != null && !previousType.equals(dataType)) {
// It is possible to have a property and method with different types that appear the same to this code. An
// example is an Apex class with a property "public String Foo {get; set;}" and a method of
// "Integer getFoo() { return 1; }". In this case set the value as Unknown because we can't be sure which it
// is. This code could be more complex in an attempt to determine if all the types are safe from escaping,
// but we will allow a false positive in order to let the user know that the code could be refactored to be
// more clear.
super.putDataType(name, DataType.Unknown);
LOG.warn("Conflicting types for {}. CurrentType={}, PreviousType={}",
name, dataType, previousType);
}
return previousType;
}
}
| 4,934 | 41.543103 | 120 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ObjectFieldTypes.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import net.sourceforge.pmd.lang.vf.DataType;
/**
* Responsible for storing a mapping of Fields that can be referenced from Visualforce to the type of the field.
*/
class ObjectFieldTypes extends SalesforceFieldTypes {
private static final Logger LOG = LoggerFactory.getLogger(ObjectFieldTypes.class);
public static final String CUSTOM_OBJECT_SUFFIX = "__c";
private static final String FIELDS_DIRECTORY = "fields";
private static final String MDAPI_OBJECT_FILE_SUFFIX = ".object";
private static final String SFDX_FIELD_FILE_SUFFIX = ".field-meta.xml";
private static final Map<String, DataType> STANDARD_FIELD_TYPES;
static {
STANDARD_FIELD_TYPES = new HashMap<>();
STANDARD_FIELD_TYPES.put("createdbyid", DataType.Lookup);
STANDARD_FIELD_TYPES.put("createddate", DataType.DateTime);
STANDARD_FIELD_TYPES.put("id", DataType.Lookup);
STANDARD_FIELD_TYPES.put("isdeleted", DataType.Checkbox);
STANDARD_FIELD_TYPES.put("lastmodifiedbyid", DataType.Lookup);
STANDARD_FIELD_TYPES.put("lastmodifieddate", DataType.DateTime);
STANDARD_FIELD_TYPES.put("name", DataType.Text);
STANDARD_FIELD_TYPES.put("systemmodstamp", DataType.DateTime);
}
/**
* Keep track of which ".object" files have already been processed. All fields are processed at once. If an object
* file has been processed
*/
private final Set<String> objectFileProcessed;
// XML Parsing objects
private final DocumentBuilder documentBuilder;
private final XPathExpression customObjectFieldsExpression;
private final XPathExpression customFieldFullNameExpression;
private final XPathExpression customFieldTypeExpression;
private final XPathExpression sfdxCustomFieldFullNameExpression;
private final XPathExpression sfdxCustomFieldTypeExpression;
ObjectFieldTypes() {
this.objectFileProcessed = new HashSet<>();
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(false);
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setIgnoringComments(true);
documentBuilderFactory.setIgnoringElementContentWhitespace(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilderFactory.setCoalescing(false);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
try {
XPath xPath = XPathFactory.newInstance().newXPath();
this.customObjectFieldsExpression = xPath.compile("/CustomObject/fields");
this.customFieldFullNameExpression = xPath.compile("fullName/text()");
this.customFieldTypeExpression = xPath.compile("type/text()");
this.sfdxCustomFieldFullNameExpression = xPath.compile("/CustomField/fullName/text()");
this.sfdxCustomFieldTypeExpression = xPath.compile("/CustomField/type/text()");
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* Looks in {@code objectsDirectories} for a custom field identified by {@code expression}.
*/
@Override
protected void findDataType(String expression, List<Path> objectsDirectories) {
// The expression should be in the form <objectName>.<fieldName>
String[] parts = expression.split("\\.");
if (parts.length == 1) {
throw new RuntimeException("Malformed identifier: " + expression);
} else if (parts.length == 2) {
String objectName = parts[0];
String fieldName = parts[1];
addStandardFields(objectName);
// Attempt to find a metadata file that contains the custom field. The information will be located in a
// file located at <objectDirectory>/<objectName>.object or in an file located at
// <objectDirectory>/<objectName>/fields/<fieldName>.field-meta.xml. The list of object directories
// defaults to the [<vfFileName>/../objects] but can be overridden by the user.
for (Path objectsDirectory : objectsDirectories) {
Path sfdxCustomFieldPath = getSfdxCustomFieldPath(objectsDirectory, objectName, fieldName);
if (sfdxCustomFieldPath != null) {
// SFDX Format
parseSfdxCustomField(objectName, sfdxCustomFieldPath);
} else {
// MDAPI Format
String fileName = objectName + MDAPI_OBJECT_FILE_SUFFIX;
Path mdapiPath = objectsDirectory.resolve(fileName);
if (Files.exists(mdapiPath) && Files.isRegularFile(mdapiPath)) {
parseMdapiCustomObject(mdapiPath);
}
}
if (containsExpression(expression)) {
// Break out of the loop if a variable was found
break;
}
}
} else {
// TODO: Support cross object relationships, these are expressions that contain "__r"
LOG.debug("Expression does not have two parts: {}", expression);
}
}
/**
* Sfdx projects decompose custom fields into individual files. This method will return the individual file that
* corresponds to <objectName>.<fieldName> if it exists.
*
* @return path to the metadata file for the Custom Field or null if not found
*/
private Path getSfdxCustomFieldPath(Path objectsDirectory, String objectName, String fieldName) {
Path fieldsDirectoryPath = Paths.get(objectsDirectory.toString(), objectName, FIELDS_DIRECTORY);
if (Files.exists(fieldsDirectoryPath) && Files.isDirectory(fieldsDirectoryPath)) {
Path sfdxFieldPath = Paths.get(fieldsDirectoryPath.toString(), fieldName + SFDX_FIELD_FILE_SUFFIX);
if (Files.exists(sfdxFieldPath) && Files.isRegularFile(sfdxFieldPath)) {
return sfdxFieldPath;
}
}
return null;
}
/**
* Determine the type of the custom field.
*/
private void parseSfdxCustomField(String customObjectName, Path sfdxCustomFieldPath) {
try {
Document document = documentBuilder.parse(sfdxCustomFieldPath.toFile());
Node fullNameNode = (Node) sfdxCustomFieldFullNameExpression.evaluate(document, XPathConstants.NODE);
Node typeNode = (Node) sfdxCustomFieldTypeExpression.evaluate(document, XPathConstants.NODE);
String type = typeNode.getNodeValue();
DataType dataType = DataType.fromString(type);
String key = customObjectName + "." + fullNameNode.getNodeValue();
putDataType(key, dataType);
} catch (IOException | SAXException | XPathExpressionException e) {
throw new ContextedRuntimeException(e)
.addContextValue("customObjectName", customObjectName)
.addContextValue("sfdxCustomFieldPath", sfdxCustomFieldPath);
}
}
/**
* Parse the custom object path and determine the type of all of its custom fields.
*/
private void parseMdapiCustomObject(Path mdapiObjectFile) {
String fileName = mdapiObjectFile.getFileName().toString();
String customObjectName = fileName.substring(0, fileName.lastIndexOf(MDAPI_OBJECT_FILE_SUFFIX));
if (!objectFileProcessed.contains(customObjectName)) {
try {
Document document = documentBuilder.parse(mdapiObjectFile.toFile());
NodeList fieldsNodes = (NodeList) customObjectFieldsExpression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < fieldsNodes.getLength(); i++) {
Node fieldsNode = fieldsNodes.item(i);
Node fullNameNode = (Node) customFieldFullNameExpression.evaluate(fieldsNode, XPathConstants.NODE);
if (fullNameNode == null) {
throw new RuntimeException("fullName evaluate failed for " + customObjectName + " " + fieldsNode.getTextContent());
}
String name = fullNameNode.getNodeValue();
if (endsWithIgnoreCase(name, CUSTOM_OBJECT_SUFFIX)) {
Node typeNode = (Node) customFieldTypeExpression.evaluate(fieldsNode, XPathConstants.NODE);
if (typeNode == null) {
throw new RuntimeException("type evaluate failed for object=" + customObjectName + ", field=" + name + " " + fieldsNode.getTextContent());
}
String type = typeNode.getNodeValue();
DataType dataType = DataType.fromString(type);
String key = customObjectName + "." + fullNameNode.getNodeValue();
putDataType(key, dataType);
}
}
} catch (IOException | SAXException | XPathExpressionException e) {
throw new ContextedRuntimeException(e)
.addContextValue("customObjectName", customObjectName)
.addContextValue("mdapiObjectFile", mdapiObjectFile);
}
objectFileProcessed.add(customObjectName);
}
}
/**
* Add the set of standard fields which aren't present in the metadata file, but may be refernced from the
* visualforce page.
*/
private void addStandardFields(String customObjectName) {
for (Map.Entry<String, DataType> entry : STANDARD_FIELD_TYPES.entrySet()) {
putDataType(customObjectName + "." + entry.getKey(), entry.getValue());
}
}
/**
* Null safe endsWithIgnoreCase
*/
private boolean endsWithIgnoreCase(String str, String suffix) {
return str != null && str.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT));
}
@Override
protected DataType putDataType(String name, DataType dataType) {
DataType previousType = super.putDataType(name, dataType);
if (previousType != null && !previousType.equals(dataType)) {
// It should not be possible to have conflicting types for CustomFields
throw new RuntimeException("Conflicting types for "
+ name
+ ". CurrentType="
+ dataType
+ ", PreviousType="
+ previousType);
}
return previousType;
}
}
| 12,022 | 45.782101 | 166 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTAttributeValue.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTAttributeValue extends AbstractVfNode {
ASTAttributeValue(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 407 | 21.666667 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/AbstractVfNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.AbstractJjtreeNode;
abstract class AbstractVfNode extends AbstractJjtreeNode<AbstractVfNode, VfNode> implements VfNode {
protected AbstractVfNode(int id) {
super(id);
}
@Override // override to make protected member accessible to parser
protected void setImage(String image) {
super.setImage(image);
}
@Override
public String getXPathNodeName() {
return VfParserImplTreeConstants.jjtNodeName[id];
}
protected abstract <P, R> R acceptVfVisitor(VfVisitor<? 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 VfVisitor) {
return acceptVfVisitor((VfVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
}
| 1,128 | 28.710526 | 100 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfVisitorBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import net.sourceforge.pmd.lang.ast.AstVisitorBase;
public abstract class VfVisitorBase<P, R> extends AstVisitorBase<P, R> implements VfVisitor<P, R> {
}
| 286 | 22.916667 | 99 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTDoctypeExternalId.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTDoctypeExternalId extends AbstractVfNode {
/**
* URI of the external entity. Cannot be null.
*/
private String uri;
/**
* Public ID of the external entity. This is optional.
*/
private String publicId;
ASTDoctypeExternalId(int id) {
super(id);
}
public boolean isHasPublicId() {
return null != publicId;
}
public String getUri() {
return uri;
}
void setUri(String uri) {
this.uri = uri;
}
/**
* @return Returns the publicId (or an empty string if there is none for
* this external entity id).
*/
public String getPublicId() {
return null == publicId ? "" : publicId;
}
void setPublicId(String publicId) {
this.publicId = publicId;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,109 | 20.346154 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTHtmlScript.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTHtmlScript extends AbstractVfNode {
ASTHtmlScript(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 399 | 21.222222 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTIdentifier.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTIdentifier extends AbstractVFDataNode {
ASTIdentifier(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 403 | 21.444444 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTCData.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTCData extends AbstractVfNode {
ASTCData(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 389 | 20.666667 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/VfNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.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 VfNode extends JjtreeNode<VfNode> {
/**
* Accept the visitor.
*
* @deprecated Use {@link #acceptVisitor(AstVisitor, Object)}
*/
@Deprecated
@DeprecatedUntil700
default Object jjtAccept(VfParserVisitor visitor, Object data) {
return acceptVisitor(visitor, data);
}
}
| 630 | 24.24 | 79 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTElement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTElement extends AbstractVfNode {
/**
* Name of the element-tag. Cannot be null.
*/
private String name;
/**
* Flag indicating that the element consists of one tag ("<... />").
*/
private boolean empty; //
/**
* Flag indicating that the parser did not find a proper ending marker or
* ending tag for this element.
*/
private boolean unclosed;
ASTElement(int id) {
super(id);
}
/**
* @return boolean - true if the element has a namespace-prefix, false
* otherwise
*/
public boolean isHasNamespacePrefix() {
return name.indexOf(':') >= 0;
}
/**
* @return String - the part of the name that is before the (first) colon
* (":")
*/
public String getNamespacePrefix() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(0, colonIndex) : "";
}
/**
* @return String - The part of the name that is after the first colon
* (":"). If the name does not contain a colon, the full name is
* returned.
*/
public String getLocalName() {
int colonIndex = name.indexOf(':');
return colonIndex >= 0 ? name.substring(colonIndex + 1) : name;
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
public boolean isEmpty() {
return empty;
}
public boolean isUnclosed() {
return unclosed;
}
void setUnclosed(boolean unclosed) {
this.unclosed = unclosed;
}
void setEmpty(boolean empty) {
this.empty = empty;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,998 | 22.517647 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTArguments.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
public final class ASTArguments extends AbstractVfNode {
ASTArguments(int id) {
super(id);
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 397 | 21.111111 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ApexClassPropertyTypesVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.ast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import net.sourceforge.pmd.lang.apex.ast.ASTMethod;
import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode;
import net.sourceforge.pmd.lang.apex.ast.ASTProperty;
import net.sourceforge.pmd.lang.apex.ast.ASTUserClass;
import net.sourceforge.pmd.lang.apex.ast.ApexVisitorBase;
/**
* Visits an Apex class to determine a mapping of referenceable expressions to expression type.
*/
final class ApexClassPropertyTypesVisitor extends ApexVisitorBase<Void, Void> {
/**
* Prefix for standard bean type getters, i.e. getFoo
*/
private static final String BEAN_GETTER_PREFIX = "get";
/**
* This is the prefix assigned to automatic get/set properties such as String myProp { get; set; }
*/
private static final String PROPERTY_PREFIX_ACCESSOR = "__sfdc_";
private static final String RETURN_TYPE_VOID = "void";
/**
* Pairs of (variableName, typeName)
*/
private final List<Pair<String, String>> variables;
ApexClassPropertyTypesVisitor() {
this.variables = new ArrayList<>();
}
public List<Pair<String, String>> getVariables() {
return this.variables;
}
/**
* Stores the return type of the method in {@link #variables} if the method is referenceable from a
* Visualforce page.
*/
@Override
public Void visit(ASTMethod node, Void data) {
if (node.getArity() == 0
&& isVisibleToVisualForce(node)
&& !RETURN_TYPE_VOID.equalsIgnoreCase(node.getReturnType())
&& (node.hasRealLoc() || node.getFirstParentOfType(ASTProperty.class) != null)) {
StringBuilder sb = new StringBuilder();
List<ASTUserClass> parents = node.getParentsOfType(ASTUserClass.class);
Collections.reverse(parents);
for (ASTUserClass parent : parents) {
sb.append(parent.getImage()).append(".");
}
String name = node.getImage();
for (String prefix : new String[]{BEAN_GETTER_PREFIX, PROPERTY_PREFIX_ACCESSOR}) {
if (name.startsWith(prefix)) {
name = name.substring(prefix.length());
}
}
sb.append(name);
variables.add(Pair.of(sb.toString(), node.getReturnType()));
}
return visitApexNode(node, data);
}
/**
* Used to filter out methods that aren't visible to the Visualforce page.
*
* @return true if the method is visible to Visualforce.
*/
private boolean isVisibleToVisualForce(ASTMethod node) {
ASTModifierNode modifier = node.getFirstChildOfType(ASTModifierNode.class);
return modifier.isGlobal() | modifier.isPublic();
}
}
| 2,978 | 33.241379 | 103 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/ast/ASTCompilationUnit.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.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 ASTCompilationUnit extends AbstractVfNode implements RootNode {
private AstInfo<ASTCompilationUnit> astInfo;
ASTCompilationUnit(int id) {
super(id);
}
@Override
public AstInfo<ASTCompilationUnit> getAstInfo() {
return astInfo;
}
ASTCompilationUnit makeTaskInfo(ParserTask task) {
this.astInfo = new AstInfo<>(task, this);
return this;
}
@Override
protected <P, R> R acceptVfVisitor(VfVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 858 | 24.264706 | 91 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/rule/AbstractVfRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.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.vf.ast.VfParserVisitor;
public abstract class AbstractVfRule extends AbstractRule implements VfParserVisitor {
@Override
public void apply(Node target, RuleContext ctx) {
target.acceptVisitor(this, ctx);
}
}
| 526 | 26.736842 | 86 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/rule/security/VfCsrfRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import java.util.List;
import java.util.Locale;
import net.sourceforge.pmd.lang.vf.ast.ASTAttribute;
import net.sourceforge.pmd.lang.vf.ast.ASTElExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTElement;
import net.sourceforge.pmd.lang.vf.ast.ASTIdentifier;
import net.sourceforge.pmd.lang.vf.rule.AbstractVfRule;
/**
* @author sergey.gorbaty
*
*/
public class VfCsrfRule extends AbstractVfRule {
private static final String APEX_PAGE = "apex:page";
@Override
public Object visit(ASTElement node, Object data) {
if (APEX_PAGE.equalsIgnoreCase(node.getName())) {
List<ASTAttribute> attribs = node.findChildrenOfType(ASTAttribute.class);
boolean controller = false;
boolean isEl = false;
ASTElExpression valToReport = null;
for (ASTAttribute attr : attribs) {
switch (attr.getName().toLowerCase(Locale.ROOT)) {
case "action":
ASTElExpression value = attr.getFirstDescendantOfType(ASTElExpression.class);
if (value != null) {
if (doesElContainIdentifiers(value)) {
isEl = true;
valToReport = value;
}
}
break;
case "controller":
controller = true;
break;
default:
break;
}
}
if (controller && isEl && valToReport != null) {
addViolation(data, valToReport);
}
}
return super.visit(node, data);
}
private boolean doesElContainIdentifiers(ASTElExpression value) {
return value.getFirstDescendantOfType(ASTIdentifier.class) != null;
}
}
| 1,980 | 29.476923 | 97 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/rule/security/VfUnescapeElRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.vf.ast.ASTAttribute;
import net.sourceforge.pmd.lang.vf.ast.ASTContent;
import net.sourceforge.pmd.lang.vf.ast.ASTElExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTElement;
import net.sourceforge.pmd.lang.vf.ast.ASTExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTHtmlScript;
import net.sourceforge.pmd.lang.vf.ast.ASTLiteral;
import net.sourceforge.pmd.lang.vf.ast.ASTText;
import net.sourceforge.pmd.lang.vf.rule.AbstractVfRule;
import net.sourceforge.pmd.lang.vf.rule.security.internal.ElEscapeDetector;
/**
* @author sergey.gorbaty February 2017
*
*/
public class VfUnescapeElRule extends AbstractVfRule {
private static final String A_CONST = "a";
private static final String APEXIFRAME_CONST = "apex:iframe";
private static final String IFRAME_CONST = "iframe";
private static final String HREF = "href";
private static final String SRC = "src";
private static final String APEX_PARAM = "apex:param";
private static final String VALUE = "value";
private static final String ITEM_VALUE = "itemvalue";
private static final String ESCAPE = "escape";
private static final String ITEM_ESCAPED = "itemescaped";
private static final String APEX_OUTPUT_TEXT = "apex:outputtext";
private static final String APEX_PAGE_MESSAGE = "apex:pagemessage";
private static final String APEX_PAGE_MESSAGES = "apex:pagemessages";
private static final String APEX_SELECT_OPTION = "apex:selectoption";
private static final String FALSE = "false";
private static final Pattern ON_EVENT = Pattern.compile("^on(\\w)+$");
private static final Pattern PLACEHOLDERS = Pattern.compile("\\{(\\w|,|\\.|'|:|\\s)*\\}");
private static final Set<ElEscapeDetector.Escaping> JSENCODE_JSINHTMLENCODE = EnumSet.of(ElEscapeDetector.Escaping.JSENCODE, ElEscapeDetector.Escaping.JSINHTMLENCODE);
private static final Set<ElEscapeDetector.Escaping> ANY_ENCODE = EnumSet.of(ElEscapeDetector.Escaping.ANY);
@Override
public Object visit(ASTHtmlScript node, Object data) {
checkIfCorrectlyEscaped(node, data);
return super.visit(node, data);
}
private void checkIfCorrectlyEscaped(ASTHtmlScript node, Object data) {
// churn thru every child just once instead of twice
for (int i = 0; i < node.getNumChildren(); i++) {
Node n = node.getChild(i);
if (n instanceof ASTElExpression) {
processElInScriptContext((ASTElExpression) n, data);
}
}
}
private void processElInScriptContext(ASTElExpression elExpression, Object data) {
if (!properlyEscaped(elExpression)) {
addViolation(data, elExpression);
}
}
private boolean properlyEscaped(ASTElExpression el) {
// Find the first Expression-type child of this top-level node.
ASTExpression expression = el.getFirstChildOfType(ASTExpression.class);
// If no such node was found, then there's nothing to escape, so we're fine.
return expression == null
// Otherwise, we should pass the expression node into our recursive checker.
|| ElEscapeDetector.expressionRecursivelyValid(expression, JSENCODE_JSINHTMLENCODE);
}
@Override
public Object visit(ASTElement node, Object data) {
if (doesTagSupportEscaping(node)) {
checkApexTagsThatSupportEscaping(node, data);
} else {
checkLimitedFlags(node, data);
checkAllOnEventTags(node, data);
}
return super.visit(node, data);
}
private void checkLimitedFlags(ASTElement node, Object data) {
switch (node.getName().toLowerCase(Locale.ROOT)) {
case IFRAME_CONST:
case APEXIFRAME_CONST:
case A_CONST:
break;
default:
return;
}
final List<ASTAttribute> attributes = node.findChildrenOfType(ASTAttribute.class);
boolean isEL = false;
final Set<ASTElExpression> toReport = new HashSet<>();
for (ASTAttribute attr : attributes) {
String name = attr.getName().toLowerCase(Locale.ROOT);
// look for onevents
if (HREF.equalsIgnoreCase(name) || SRC.equalsIgnoreCase(name)) {
boolean startingWithSlashText = false;
final ASTText attrText = attr.getFirstDescendantOfType(ASTText.class);
if (attrText != null) {
if (0 == attrText.getIndexInParent()) {
String lowerCaseImage = attrText.getImage().toLowerCase(Locale.ROOT);
if (lowerCaseImage.startsWith("/") || lowerCaseImage.startsWith("http")
|| lowerCaseImage.startsWith("mailto")) {
startingWithSlashText = true;
}
}
}
if (!startingWithSlashText) {
final List<ASTElExpression> elsInVal = attr.findDescendantsOfType(ASTElExpression.class);
for (ASTElExpression el : elsInVal) {
if (startsWithSlashLiteral(el)) {
break;
}
if (ElEscapeDetector.startsWithSafeResource(el)) {
break;
}
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(el, ElEscapeDetector.Escaping.URLENCODE)) {
isEL = true;
toReport.add(el);
}
}
}
}
}
if (isEL) {
for (ASTElExpression expr : toReport) {
addViolation(data, expr);
}
}
}
private void checkAllOnEventTags(ASTElement node, Object data) {
final List<ASTAttribute> attributes = node.findChildrenOfType(ASTAttribute.class);
boolean isEL = false;
final Set<ASTElExpression> toReport = new HashSet<>();
for (ASTAttribute attr : attributes) {
String name = attr.getName().toLowerCase(Locale.ROOT);
// look for onevents
if (ON_EVENT.matcher(name).matches()) {
final List<ASTElExpression> elsInVal = attr.findDescendantsOfType(ASTElExpression.class);
for (ASTElExpression el : elsInVal) {
if (ElEscapeDetector.startsWithSafeResource(el)) {
continue;
}
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(el, ANY_ENCODE)) {
isEL = true;
toReport.add(el);
}
}
}
}
if (isEL) {
for (ASTElExpression expr : toReport) {
addViolation(data, expr);
}
}
}
private boolean startsWithSlashLiteral(final ASTElExpression elExpression) {
final ASTExpression expression = elExpression.getFirstChildOfType(ASTExpression.class);
if (expression != null) {
final ASTLiteral literal = expression.getFirstChildOfType(ASTLiteral.class);
if (literal != null && literal.getIndexInParent() == 0) {
String lowerCaseLiteral = literal.getImage().toLowerCase(Locale.ROOT);
if (lowerCaseLiteral.startsWith("'/") || lowerCaseLiteral.startsWith("\"/")
|| lowerCaseLiteral.startsWith("'http")
|| lowerCaseLiteral.startsWith("\"http")) {
return true;
}
}
}
return false;
}
private void checkApexTagsThatSupportEscaping(ASTElement node, Object data) {
final List<ASTAttribute> attributes = node.findChildrenOfType(ASTAttribute.class);
final Set<ASTElExpression> toReport = new HashSet<>();
boolean isUnescaped = false;
boolean isEL = false;
boolean hasPlaceholders = false;
for (ASTAttribute attr : attributes) {
String name = attr.getName().toLowerCase(Locale.ROOT);
switch (name) {
case ESCAPE:
case ITEM_ESCAPED:
final ASTText text = attr.getFirstDescendantOfType(ASTText.class);
if (text != null) {
if (FALSE.equalsIgnoreCase(text.getImage())) {
isUnescaped = true;
}
}
break;
case VALUE:
case ITEM_VALUE:
final List<ASTElExpression> elsInVal = attr.findDescendantsOfType(ASTElExpression.class);
for (ASTElExpression el : elsInVal) {
if (ElEscapeDetector.startsWithSafeResource(el)) {
continue;
}
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(el,
ElEscapeDetector.Escaping.HTMLENCODE)) {
isEL = true;
toReport.add(el);
}
}
final ASTText textValue = attr.getFirstDescendantOfType(ASTText.class);
if (textValue != null) {
if (PLACEHOLDERS.matcher(textValue.getImage()).matches()) {
hasPlaceholders = true;
}
}
break;
default:
break;
}
}
if (hasPlaceholders && isUnescaped) {
for (ASTElExpression expr : hasELInInnerElements(node)) {
addViolation(data, expr);
}
}
if (isEL && isUnescaped) {
for (ASTElExpression expr : toReport) {
addViolation(data, expr);
}
}
}
private boolean doesTagSupportEscaping(final ASTElement node) {
if (node.getName() == null) {
return false;
}
switch (node.getName().toLowerCase(Locale.ROOT)) { // vf is case insensitive
case APEX_OUTPUT_TEXT:
case APEX_PAGE_MESSAGE:
case APEX_PAGE_MESSAGES:
case APEX_SELECT_OPTION:
return true;
default:
return false;
}
}
private Set<ASTElExpression> hasELInInnerElements(final ASTElement node) {
final Set<ASTElExpression> toReturn = new HashSet<>();
final ASTContent content = node.getFirstChildOfType(ASTContent.class);
if (content != null) {
final List<ASTElement> innerElements = content.findChildrenOfType(ASTElement.class);
for (final ASTElement element : innerElements) {
if (APEX_PARAM.equalsIgnoreCase(element.getName())) {
final List<ASTAttribute> innerAttributes = element.findChildrenOfType(ASTAttribute.class);
for (ASTAttribute attrib : innerAttributes) {
final List<ASTElExpression> elsInVal = attrib.findDescendantsOfType(ASTElExpression.class);
for (final ASTElExpression el : elsInVal) {
if (ElEscapeDetector.startsWithSafeResource(el)) {
continue;
}
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(el,
ElEscapeDetector.Escaping.HTMLENCODE)) {
toReturn.add(el);
}
}
}
}
}
}
return toReturn;
}
}
| 12,089 | 36.78125 | 171 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/rule/security/VfHtmlStyleTagXssRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security;
import java.util.EnumSet;
import java.util.Set;
import java.util.regex.Pattern;
import net.sourceforge.pmd.lang.vf.ast.ASTContent;
import net.sourceforge.pmd.lang.vf.ast.ASTElExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTElement;
import net.sourceforge.pmd.lang.vf.ast.ASTText;
import net.sourceforge.pmd.lang.vf.ast.VfNode;
import net.sourceforge.pmd.lang.vf.rule.AbstractVfRule;
import net.sourceforge.pmd.lang.vf.rule.security.internal.ElEscapeDetector;
public class VfHtmlStyleTagXssRule extends AbstractVfRule {
private static final String STYLE_TAG = "style";
private static final String APEX_PREFIX = "apex";
private static final Set<ElEscapeDetector.Escaping> URLENCODE_JSINHTMLENCODE = EnumSet.of(ElEscapeDetector.Escaping.URLENCODE, ElEscapeDetector.Escaping.JSINHTMLENCODE);
private static final Set<ElEscapeDetector.Escaping> ANY_ENCODE = EnumSet.of(ElEscapeDetector.Escaping.ANY);
private static final Pattern URL_METHOD_PATTERN = Pattern.compile("url\\s*\\([^)]*$", Pattern.CASE_INSENSITIVE);
public VfHtmlStyleTagXssRule() {
addRuleChainVisit(ASTElExpression.class);
}
/**
* We are looking for an ASTElExpression node that is
* placed inside an ASTContent, which in turn is placed inside
* an ASTElement, where the element is not an inbuilt vf tag.
*
* <pre>{@code
* <ASTElement>
* <ASTContent>
* <ASTElExpression></ASTElExpression>
* </ASTContent>
* </ASTElement>
* }</pre>
*/
@Override
public Object visit(ASTElExpression node, Object data) {
final VfNode nodeParent = node.getParent();
if (!(nodeParent instanceof ASTContent)) {
// nothing to do here.
// We care only if parent is available and is an ASTContent
return data;
}
final ASTContent contentNode = (ASTContent) nodeParent;
final VfNode nodeGrandParent = contentNode.getParent();
if (!(nodeGrandParent instanceof ASTElement)) {
// nothing to do here.
// We care only if grandparent is available and is an ASTElement
return data;
}
final ASTElement elementNode = (ASTElement) nodeGrandParent;
// make sure elementNode does not have an "apex:" prefix
if (isApexPrefixed(elementNode)) {
// nothing to do here.
// This rule does not deal with inbuilt-visualforce tags
return data;
}
verifyEncoding(node, contentNode, elementNode, data);
return data;
}
/**
* Examining encoding of ElExpression - we apply different rules
* for plain HTML tags and <style></style> content.
*/
private void verifyEncoding(
ASTElExpression node,
ASTContent contentNode,
ASTElement elementNode,
Object data) {
final String previousText = getPreviousText(contentNode, node);
final boolean isWithinSafeResource = ElEscapeDetector.startsWithSafeResource(node);
// if El is inside a <style></style> tag
// and is not surrounded by a safe resource, check for violations
if (isStyleTag(elementNode) && !isWithinSafeResource) {
// check if we are within a URL expression
if (isWithinUrlMethod(previousText)) {
verifyEncodingWithinUrl(node, data);
} else {
verifyEncodingWithoutUrl(node, data);
}
}
}
private boolean isStyleTag(ASTElement elementNode) {
// are we dealing with HTML <style></style> tag?
return STYLE_TAG.equalsIgnoreCase(elementNode.getLocalName());
}
private void verifyEncodingWithinUrl(ASTElExpression elExpressionNode, Object data) {
// only allow URLENCODING or JSINHTMLENCODING
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(
elExpressionNode,
URLENCODE_JSINHTMLENCODE)) {
addViolationWithMessage(
data,
elExpressionNode,
"Dynamic EL content within URL in style tag should be URLENCODED or JSINHTMLENCODED as appropriate");
}
}
private void verifyEncodingWithoutUrl(ASTElExpression elExpressionNode, Object data) {
if (ElEscapeDetector.doesElContainAnyUnescapedIdentifiers(
elExpressionNode,
ANY_ENCODE)) {
addViolationWithMessage(
data,
elExpressionNode,
"Dynamic EL content in style tag should be appropriately encoded");
}
}
private boolean isApexPrefixed(ASTElement node) {
return node.isHasNamespacePrefix()
&& APEX_PREFIX.equalsIgnoreCase(node.getNamespacePrefix());
}
/**
* Get text content within style tag that leads up to the ElExpression.
* For example, in this snippet:
*
* <pre>
* <style>
* div {
* background: url('{!HTMLENCODE(XSSHere)}');
* }
* </style>
* </pre>
*
* {@code getPreviousText(...)} would return <code>"\n div {\n background: url("</code>.
*
*/
private String getPreviousText(ASTContent content, ASTElExpression elExpressionNode) {
final int indexInParent = elExpressionNode.getIndexInParent();
final VfNode previous = indexInParent > 0 ? content.getChild(indexInParent - 1) : null;
return previous instanceof ASTText ? previous.getImage() : "";
}
// visible for unit testing
static boolean isWithinUrlMethod(String previousText) {
// match for a pattern that
// 1. contains "url" (case insensitive),
// 2. followed by any number of whitespaces,
// 3. a starting bracket "("
// 4. and anything else but an ending bracket ")"
// For example:
// Matches: "div { background: url('", "div { background: Url ( blah"
// Does not match: "div { background: url('myUrl')", "div { background: myStyle('"
return URL_METHOD_PATTERN.matcher(previousText).find();
}
}
| 6,293 | 36.023529 | 173 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/lang/vf/rule/security/internal/ElEscapeDetector.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.vf.rule.security.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import net.sourceforge.pmd.lang.vf.DataType;
import net.sourceforge.pmd.lang.vf.ast.ASTArguments;
import net.sourceforge.pmd.lang.vf.ast.ASTDotExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTElExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTExpression;
import net.sourceforge.pmd.lang.vf.ast.ASTIdentifier;
import net.sourceforge.pmd.lang.vf.ast.ASTNegationExpression;
import net.sourceforge.pmd.lang.vf.ast.VfNode;
import net.sourceforge.pmd.lang.vf.ast.VfTypedNode;
/**
* Helps detect visualforce encoding in EL Expressions
* (porting over code previously living in VfUnescapeElRule for reusability)
*/
public final class ElEscapeDetector {
private static final Set<String> SAFE_PROPERTIES = new HashSet<>(Arrays.asList("id", "size", "caseNumber"));
private static final Set<String> SAFE_BUILTIN_FUNCTIONS = new HashSet<>(Arrays.asList(
// These DateTime functions accept or return dates, and therefore don't need escaping.
"addmonths", "date", "datevalue", "datetimevalue", "day", "hour", "millisecond", "minute", "month", "now",
"second", "timenow", "timevalue", "today", "weekday", "year",
// These Logical functions accept or return booleans, and therefore don't need escaping.
"and", "isblank", "isclone", "isnew", "isnull", "isnumber", "not", "or",
// These Math functions return numbers, and therefore don't require escaping.
"abs", "ceiling", "exp", "floor", "ln", "log", "max", "mceiling", "mfloor", "min", "mod", "round", "sqrt",
// These Text functions are safe, either because of what they accept or what they return.
"begins", "br", "casesafeid", "contains", "find", "getsessionid", "ispickval", "len",
// These Advanced functions are safe because of what they accept or what they return.
"currencyrate", "getrecordids", "ischanged", "junctionidlist", "linkto", "regex", "urlfor"
));
private static final Set<String> FUNCTIONS_WITH_XSSABLE_ARG0 = new HashSet<>(Arrays.asList(
// For these methods, the first argument is a string that must be escaped.
"left", "lower", "lpad", "mid", "right", "rpad", "upper"
));
private static final Set<String> FUNCTIONS_WITH_XSSABLE_ARG2 = new HashSet<>(Arrays.asList(
// For these methods, the third argument is a string that must be escaped.
"lpad", "rpad"
));
private static final Set<String> SAFE_GLOBAL_VARS = new HashSet<>(Arrays.asList("$action", "$page", "$site",
"$resource", "$label", "$objecttype", "$component", "$remoteaction", "$messagechannel"));
private ElEscapeDetector() {
// utility class
}
private static VfNode getNextSibling(VfNode node) {
VfNode parent = node.getParent();
if (parent != null && node.getIndexInParent() < (parent.getNumChildren() - 1)) {
return parent.getChild(node.getIndexInParent() + 1);
}
return null;
}
/**
* Given an ASTExpression node, determines whether that expression and any expressions under it are properly escaped.
* @param expression - Represents a VF expression
* @param escapes - The escape operations that are acceptable in this context
* @return - True if the expression is properly escaped, otherwise false.
*/
public static boolean expressionRecursivelyValid(final ASTExpression expression, final Set<Escaping> escapes) {
// We'll want to iterate over all of this expression's children.
int childCount = expression.getNumChildren();
String prevId = "";
List<ASTExpression> relevantChildren = new ArrayList<>();
for (int i = 0; i < childCount; i++) {
VfNode child = expression.getChild(i);
if (child instanceof ASTIdentifier) {
// How we deal with an Identifier depends on what the next node after it is.
VfNode nextNode = getNextSibling(child);
if (nextNode instanceof ASTArguments || nextNode instanceof ASTDotExpression) {
// If the next node is Arguments or Dot expression, that means this Identifier represents the name
// of a function, or some kind of object. In that case, we might be okay. So we'll store the name
// and keep going.
prevId = child.getImage();
continue;
}
// If there's no next node, or the next node isn't one of the desired types, then this Identifier is a raw
// variable.
if (typedNodeIsSafe((ASTIdentifier) child)) {
// If the raw variable is of an inherently safe type, we can keep going.
continue;
}
// If the raw variable isn't inherently safe, then it's dangerous, and must be escaped.
return false;
} else if (child instanceof ASTArguments) {
// An Arguments node means we're looking at some kind of function call.
// If it's one of our designated escape functions, we're in the clear and we can keep going.
// Also, some built-in functions are inherently safe, which would mean we're good to continue.
if (functionIsEscape(prevId, escapes) || functionInherentlySafe(prevId)) {
continue;
}
// Otherwise, identify the argument expressions that must be checked, and add them to the list.
relevantChildren.addAll(getXssableArguments(prevId, (ASTArguments) child));
} else if (child instanceof ASTDotExpression) {
// Dot expressions mean we're doing accessing properties of variables.
// If the variable is one of the definitely-safe global variables, then we're in the clear.
if (isSafeGlobal(prevId)) {
continue;
}
// If the node after this one is also a Dot expression, then this is a chained access, and we can't make
// any final judgements.
if (getNextSibling(child) instanceof ASTDotExpression) {
continue;
}
// If none of those things are true, then we need to determine whether the field being accessed is
// definitely safe.
ASTIdentifier propId = child.getFirstChildOfType(ASTIdentifier.class);
// If there's an identifier for a field/property, we need to check whether that property is inherently safe,
// either because it corresponds to a safe field or because its data type is known to be safe.
if (propId != null && !isSafeProperty(propId.getImage()) && !typedNodeIsSafe(propId)) {
// If the node isn't definitely safe, it ought to be escaped. Return false.
return false;
}
} else if (child instanceof ASTExpression) {
// Expressions should always be added to the list.
relevantChildren.add((ASTExpression) child);
}
}
// Just because there's nothing immediately wrong with this node doesn't mean its children are guaranteed to be
// fine. Iterate over all of the children and make a recursive call. If any of those calls return false, we need
// to relay that back up the chain.
for (ASTExpression e : relevantChildren) {
if (!expressionRecursivelyValid(e, escapes)) {
return false;
}
}
// If we didn't find a reason to return false, we're good. Return true.
return true;
}
/**
* Indicates whether the provided function name corresponds to any of the provided escape functions.
* @param functionName - The name of a VF function
* @param escapes - A set of acceptable escape functions (e.g., JSENCODE, HTMLENCODE, etc)
* @return - True if the function is a viable escape.
*/
private static boolean functionIsEscape(String functionName, Set<Escaping> escapes) {
// If one of the escapes we were passed is ANY, then we should replace the provided set with one that contains
// all possible escapes.
Set<Escaping> handledEscapes = escapes.contains(Escaping.ANY) ? EnumSet.allOf(Escaping.class) : escapes;
for (Escaping e : handledEscapes) {
if (functionName.equalsIgnoreCase(e.toString())) {
return true;
}
}
return false;
}
/**
* Certain built-in functions are inherently safe and don't require any escaping. This method determines whether the
* function name provided corresponds to one of those methods.
* @param functionName - The name of a VF function
* @return - True if the function is an inherently safe built-in function
*/
private static boolean functionInherentlySafe(String functionName) {
String lowerCaseName = functionName.toLowerCase(Locale.ROOT);
return SAFE_BUILTIN_FUNCTIONS.contains(lowerCaseName);
}
/**
* Given a function name and a node containing its arguments, returns the ASTExpression nodes corresponding to arguments
* that require escaping. Frequently, this will be all arguments, but not always.
* @param functionName - The name of a function being called
* @param arguments - Contains the ASTExpression nodes representing the function's arguments
* @return - ASTExpression list containing all arguments that are vulnerable to XSS.
*/
private static List<ASTExpression> getXssableArguments(String functionName, ASTArguments arguments) {
List<ASTExpression> exprs = new ArrayList<>();
int argCount = arguments.getNumChildren();
if (argCount != 0) {
String lowerCaseName = functionName.toLowerCase(Locale.ROOT);
List<Integer> indicesToCheck = new ArrayList<>();
// See if the function name corresponds to one of the built-in functions that don't require us to examine
// every argument.
if ("case".equals(lowerCaseName)) {
// CASE accepts (exx, val1, res1, val2, res2, ...else_res). We want resX and else_res.
for (int i = 2; i < argCount; i += 2) {
indicesToCheck.add(i);
}
indicesToCheck.add(argCount - 1);
} else if ("if".equals(lowerCaseName)) {
// IF accepts (test, if_true, if_false). We care about if_true and if_false.
indicesToCheck.add(1);
indicesToCheck.add(2);
} else {
boolean checkAllArgs = true;
// If this is a function with an XSSable first arg, add 0 to the array.
if (FUNCTIONS_WITH_XSSABLE_ARG0.contains(lowerCaseName)) {
checkAllArgs = false;
indicesToCheck.add(0);
}
// If this is a function that has at least 3 args, and the third arg is XSSable, add 2 to the array.
if (argCount > 2 && FUNCTIONS_WITH_XSSABLE_ARG2.contains(lowerCaseName)) {
checkAllArgs = false;
indicesToCheck.add(2);
}
// If the function has no known pattern for argument checking, all arguments must be checked.
if (checkAllArgs) {
for (int i = 0; i < argCount; i++) {
indicesToCheck.add(i);
}
}
}
// Add each of the targeted arguments to the return array if they represent an Expression node. (They always
// should, but better safe than sorry.)
for (int i : indicesToCheck) {
VfNode ithArg = arguments.getChild(i);
if (ithArg instanceof ASTExpression) {
exprs.add((ASTExpression) ithArg);
}
}
}
return exprs;
}
/**
* VF has global variables prefixed with a '$'. Some of those are inherently safe to access, and this method determines
* whether the provided ID corresponds to one of those globals.
* @param id - Identifier of some variable.
* @return - True if the global is inherently safe.
*/
private static boolean isSafeGlobal(String id) {
String lowerCaseId = id.toLowerCase(Locale.ROOT);
return SAFE_GLOBAL_VARS.contains(lowerCaseId);
}
/**
* Determines whether the property being referenced is inherently safe, or if it requires XSS escaping.
* @param propertyName - The name of a field or property being referenced.
* @return - True if that field/property is inherently safe
*/
private static boolean isSafeProperty(String propertyName) {
String lowerCaseName = propertyName.toLowerCase(Locale.ROOT);
return SAFE_PROPERTIES.contains(lowerCaseName);
}
private static boolean innerContainsSafeFields(final VfNode expression) {
for (VfNode child : expression.children()) {
if (child instanceof ASTIdentifier && isSafeProperty(child.getImage())) {
return true;
}
if (child instanceof ASTArguments) {
if (containsSafeFields((ASTArguments) child)) {
return true;
}
}
if (child instanceof ASTDotExpression) {
if (innerContainsSafeFields((ASTDotExpression) child)) {
return true;
}
}
}
return false;
}
public static boolean containsSafeFields(final VfNode expression) {
final ASTExpression ex = expression.getFirstChildOfType(ASTExpression.class);
return ex != null && innerContainsSafeFields(ex);
}
public static boolean startsWithSafeResource(final ASTElExpression el) {
final ASTExpression expression = el.getFirstChildOfType(ASTExpression.class);
if (expression != null) {
final ASTNegationExpression negation = expression.getFirstChildOfType(ASTNegationExpression.class);
if (negation != null) {
return true;
}
final ASTIdentifier id = expression.getFirstChildOfType(ASTIdentifier.class);
if (id != null) {
List<ASTArguments> args = expression.findChildrenOfType(ASTArguments.class);
if (!args.isEmpty()) {
return functionInherentlySafe(id.getImage());
} else {
return isSafeGlobal(id.getImage());
}
}
}
return false;
}
public static boolean doesElContainAnyUnescapedIdentifiers(final ASTElExpression elExpression, Escaping escape) {
return doesElContainAnyUnescapedIdentifiers(elExpression, EnumSet.of(escape));
}
public static boolean doesElContainAnyUnescapedIdentifiers(final ASTElExpression elExpression,
Set<Escaping> escapes) {
if (elExpression == null) {
return false;
}
final Set<ASTIdentifier> nonEscapedIds = new HashSet<>();
final List<ASTExpression> exprs = elExpression.findChildrenOfType(ASTExpression.class);
for (final ASTExpression expr : exprs) {
if (innerContainsSafeFields(expr)) {
continue;
}
if (expressionContainsSafeDataNodes(expr)) {
continue;
}
final List<ASTIdentifier> ids = expr.findChildrenOfType(ASTIdentifier.class);
for (final ASTIdentifier id : ids) {
boolean isEscaped = false;
for (Escaping e : escapes) {
if (id.getImage().equalsIgnoreCase(e.toString())) {
isEscaped = true;
break;
}
if (e.equals(Escaping.ANY)) {
for (Escaping esc : Escaping.values()) {
if (id.getImage().equalsIgnoreCase(esc.toString())) {
isEscaped = true;
break;
}
}
}
}
if (!isEscaped) {
nonEscapedIds.add(id);
}
}
}
return !nonEscapedIds.isEmpty();
}
/**
* Return true if the type of all data nodes can be determined and none of them require escaping
* @param expression
*/
private static boolean expressionContainsSafeDataNodes(ASTExpression expression) {
try {
for (VfTypedNode node : expression.getDataNodes().keySet()) {
if (!typedNodeIsSafe(node)) {
return false;
}
}
return true;
} catch (ASTExpression.DataNodeStateException e) {
return false;
}
}
private static boolean typedNodeIsSafe(VfTypedNode node) {
DataType dataType = node.getDataType();
return dataType != null && !dataType.requiresEscaping;
}
public enum Escaping {
HTMLENCODE("HTMLENCODE"),
URLENCODE("URLENCODE"),
JSINHTMLENCODE("JSINHTMLENCODE"),
JSENCODE("JSENCODE"),
ANY("ANY");
private final String text;
Escaping(final String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}
}
| 18,138 | 43.787654 | 124 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/cpd/VfTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaEscapeTranslator;
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.MalformedSourceException;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.vf.ast.VfTokenKinds;
/**
* @author sergey.gorbaty
*/
public class VfTokenizer extends JavaCCTokenizer {
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return VfTokenKinds.newTokenManager(sourceCode);
}
@Override
protected TokenDocumentBehavior tokenBehavior() {
return new JavaccTokenDocument.TokenDocumentBehavior(VfTokenKinds.TOKEN_NAMES) {
@Override
public TextDocument translate(TextDocument text) throws MalformedSourceException {
return new JavaEscapeTranslator(text).translateDocument();
}
};
}
}
| 1,381 | 34.435897 | 94 | java |
pmd | pmd-master/pmd-visualforce/src/main/java/net/sourceforge/pmd/cpd/VfLanguage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.vf.VfLanguageModule;
/**
* @author sergey.gorbaty
*
*/
public class VfLanguage extends AbstractLanguage {
public VfLanguage() {
super(VfLanguageModule.NAME, VfLanguageModule.TERSE_NAME, new VfTokenizer(), VfLanguageModule.EXTENSIONS);
}
}
| 413 | 22 | 114 | java |
pmd | pmd-master/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/symbols/internal/JClassSymbolTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.testdata.AnnotationWithNoRetention;
import net.sourceforge.pmd.lang.java.symbols.testdata.TypeAnnotation;
/**
* Tests that test both AST and ASM symbols.
*
* @author Clément Fournier
*/
class JClassSymbolTest {
@EnumSource
@ParameterizedTest
void testAnnotationAttributes(SymImplementation impl) {
JClassSymbol sym = impl.getSymbol(TypeAnnotation.class);
assertEquals(RetentionPolicy.RUNTIME, sym.getAnnotationRetention());
}
@EnumSource
@ParameterizedTest
void testAnnotWithNoRetention(SymImplementation impl) {
JClassSymbol sym = impl.getSymbol(AnnotationWithNoRetention.class);
assertEquals(RetentionPolicy.CLASS, sym.getAnnotationRetention());
}
@EnumSource
@ParameterizedTest
void testAnnotWithNoTarget(SymImplementation impl) {
JClassSymbol sym = impl.getSymbol(AnnotationWithNoRetention.class);
for (ElementType type : ElementType.values()) {
assertEquals(type != ElementType.TYPE_PARAMETER, sym.annotationAppliesTo(type),
"annot supports " + type);
}
}
}
| 1,620 | 28.472727 | 91 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/ReportTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.lang.ast.test.TestUtilsKt.assertSize;
import static net.sourceforge.pmd.lang.ast.test.TestUtilsKt.assertSuppressed;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class ReportTest {
private final JavaParsingHelper java = JavaParsingHelper.DEFAULT;
@Test
void testBasic() {
Report r = java.executeRule(new FooRule(), TEST1);
assertFalse(r.getViolations().isEmpty());
}
@Test
void testExclusionsInReportWithRuleViolationSuppressRegex() {
Rule rule = new FooRule();
rule.setProperty(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR, ".*No Foo.*");
Report rpt = java.executeRule(rule, TEST1);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
@Test
void testExclusionsInReportWithRuleViolationSuppressXPath() {
Rule rule = new FooRule();
rule.setProperty(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR, ".[@SimpleName = 'Foo']");
Report rpt = java.executeRule(rule, TEST1);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
@Test
void testExclusionsInReportWithAnnotations() {
Report rpt =
java.executeRule(new FooRule(), TEST2);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
@Test
void testExclusionsInReportWithAnnotationsFullName() {
Report rpt = java.executeRule(new FooRule(), TEST2_FULL);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
@Test
void testExclusionsInReportWithNOPMD() {
Report rpt = java.executeRule(new FooRule(), TEST3);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
private static final String TEST1 = "public class Foo {}";
private static final String TEST2 = "@SuppressWarnings(\"PMD\")\npublic class Foo {}";
private static final String TEST2_FULL = "@java.lang.SuppressWarnings(\"PMD\")\npublic class Foo {}";
private static final String TEST3 = "public class Foo {} // NOPMD";
}
| 2,232 | 29.589041 | 105 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.lang.ast.test.TestUtilsKt.assertSize;
import static net.sourceforge.pmd.lang.ast.test.TestUtilsKt.assertSuppressed;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
class ExcludeLinesTest extends BaseParserTest {
@Test
void testAcceptance() {
assertSize(java.executeRule(getRule(), TEST1), 0);
assertSize(java.executeRule(getRule(), TEST2), 1);
}
Rule getRule() {
return new AbstractJavaRule() {
{
setMessage("!");
}
@Override
public Object visit(ASTVariableDeclaratorId node, Object data) {
addViolation(data, node);
return data;
}
};
}
@Test
void testAlternateMarker() {
Report rpt = java.withSuppressMarker("FOOBAR").executeRule(getRule(), TEST3);
assertSize(rpt, 0);
assertSuppressed(rpt, 1);
}
private static final String TEST1 = "public class Foo {\n"
+ " void foo() {\n"
+ " int x; //NOPMD \n"
+ " } \n"
+ "}";
private static final String TEST2 = "public class Foo {\n"
+ " void foo() {\n"
+ " int x;\n"
+ " } \n"
+ "}";
private static final String TEST3 = "public class Foo {\n"
+ " void foo() {\n"
+ " int x; // FOOBAR\n"
+ " } \n"
+ "}";
}
| 2,069 | 31.857143 | 85 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/LanguageVersionDiscovererTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.java.JavaLanguageModule;
class LanguageVersionDiscovererTest {
/**
* Test on Java file with default options.
* Always the latest non-preview version will be the default version.
*/
@Test
void testJavaFileUsingDefaults() {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD);
File javaFile = new File("/path/to/MyClass.java");
LanguageVersion latest = determineLatestNonPreviewVersion();
LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(javaFile);
assertEquals(latest, languageVersion, "Latest language version must be default");
}
private LanguageVersion determineLatestNonPreviewVersion() {
LanguageVersion latest = null;
for (LanguageVersion lv : JavaLanguageModule.getInstance().getVersions()) {
if (!lv.getName().endsWith("preview")) {
latest = lv;
}
}
return latest;
}
/**
* Test on Java file with Java version set to 1.4.
*/
@Test
void testJavaFileUsing14() {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD);
Language java = JavaLanguageModule.getInstance();
discoverer.setDefaultLanguageVersion(java.getVersion("1.4"));
File javaFile = new File("/path/to/MyClass.java");
LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(javaFile);
assertEquals(java.getVersion("1.4"), languageVersion);
}
@Test
void testLanguageVersionDiscoverer() {
PMDConfiguration configuration = new PMDConfiguration();
LanguageVersionDiscoverer languageVersionDiscoverer = configuration.getLanguageVersionDiscoverer();
Language java = JavaLanguageModule.getInstance();
assertEquals(determineLatestNonPreviewVersion(),
languageVersionDiscoverer.getDefaultLanguageVersion(java),
"Default Java version");
configuration
.setDefaultLanguageVersion(java.getVersion("1.5"));
assertEquals(java.getVersion("1.5"),
languageVersionDiscoverer.getDefaultLanguageVersion(java),
"Modified Java version");
}
}
| 2,777 | 35.552632 | 107 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/FooRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
public class FooRule extends AbstractJavaRule {
public FooRule() {
this("No Foo allowed");
}
public FooRule(String message) {
setMessage(message);
}
@Override
public Object visit(ASTClassOrInterfaceDeclaration c, Object ctx) {
if (c.getSimpleName().equalsIgnoreCase("Foo")) {
addViolation(ctx, c);
}
return super.visit(c, ctx);
}
@Override
public Object visit(ASTVariableDeclaratorId c, Object ctx) {
if (c.getName().equalsIgnoreCase("Foo")) {
addViolation(ctx, c);
}
return super.visit(c, ctx);
}
@Override
public String getName() {
return "NoFoo";
}
}
| 1,026 | 23.452381 | 79 | java |
pmd | pmd-master/pmd-java/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.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.util.IOUtil;
class PMDTaskTest extends AbstractAntTestHelper {
PMDTaskTest() {
antTestScriptFilename = "pmdtasktest.xml";
}
@Test
void testNoFormattersValidation() {
executeTarget("testNoFormattersValidation");
assertOutputContaining("Violation from test-rset-1.xml");
}
@Test
void testNestedRuleset() {
executeTarget("testNestedRuleset");
assertOutputContaining("Violation from test-rset-1.xml");
assertOutputContaining("Violation from test-rset-2.xml");
}
@Test
void testFormatterWithProperties() {
executeTarget("testFormatterWithProperties");
assertOutputContaining("Violation from test-rset-1.xml");
assertOutputContaining("link_prefix");
assertOutputContaining("line_prefix");
}
@Test
void testAbstractNames() {
executeTarget("testAbstractNames");
assertOutputContaining("Violation from test-rset-1.xml");
assertOutputContaining("Violation from test-rset-2.xml");
}
@Test
void testAbstractNamesInNestedRuleset() {
executeTarget("testAbstractNamesInNestedRuleset");
assertOutputContaining("Violation from test-rset-1.xml");
assertOutputContaining("Violation from test-rset-2.xml");
}
@Test
void testCommaInRulesetfiles() {
executeTarget("testCommaInRulesetfiles");
assertOutputContaining("Violation from test-rset-1.xml");
assertOutputContaining("Violation from test-rset-2.xml");
}
@Test
void testRelativeRulesets() {
executeTarget("testRelativeRulesets");
assertOutputContaining("Violation from test-rset-1.xml");
}
@Test
void testRelativeRulesetsInRulesetfiles() {
executeTarget("testRelativeRulesetsInRulesetfiles");
assertOutputContaining("Violation from test-rset-1.xml");
}
@Test
void testExplicitRuleInRuleSet() {
executeTarget("testExplicitRuleInRuleSet");
assertOutputContaining("Violation from test-rset-1.xml");
}
@Test
void testClasspath() {
executeTarget("testClasspath");
}
private static void setDefaultCharset(String charsetName) {
System.setProperty("file.encoding", charsetName);
}
@Test
void testFormatterEncodingWithXML() throws Exception {
Locale.setDefault(Locale.FRENCH);
setDefaultCharset("cp1252");
executeTarget("testFormatterEncodingWithXML");
String report = IOUtil.readFileToString(currentTempFile(), StandardCharsets.UTF_8);
assertTrue(report.contains("someVariableWithÜmlaut"));
}
@Test
void testFormatterEncodingWithXMLConsole() throws UnsupportedEncodingException {
setDefaultCharset("cp1252");
String report = executeTarget("testFormatterEncodingWithXMLConsole");
assertTrue(report.startsWith("<?xml version=\"1.0\" encoding=\"windows-1252\"?>"));
assertTrue(report.contains("someVariableWithÜmlaut"));
}
@Test
void testMissingCacheLocation() {
executeTarget("testMissingCacheLocation");
assertOutputContaining("Violation from test-rset-1.xml");
assertContains(getLog(), "This analysis could be faster");
}
@Test
void testAnalysisCache() {
executeTarget("testAnalysisCache");
assertOutputContaining("Violation from test-rset-1.xml");
assertDoesntContain(getLog(), "This analysis could be faster");
assertTrue(currentTempFile().exists());
}
@Test
void testDisableIncrementalAnalysis() {
executeTarget("testDisableIncrementalAnalysis");
assertOutputContaining("Violation from test-rset-1.xml");
assertDoesntContain(getLog(), "This analysis could be faster");
assertFalse(currentTempFile().exists());
}
}
| 4,265 | 29.913043 | 91 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/SuppressWarningsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static net.sourceforge.pmd.lang.ast.test.TestUtilsKt.assertSize;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
class SuppressWarningsTest {
private final JavaParsingHelper java = JavaParsingHelper.DEFAULT;
private static class BarRule extends AbstractJavaRule {
@Override
public String getMessage() {
return "a message";
}
@Override
public Object visit(ASTCompilationUnit cu, Object ctx) {
// Convoluted rule to make sure the violation is reported for the
// ASTCompilationUnit node
for (ASTClassOrInterfaceDeclaration c : cu.descendants(ASTClassOrInterfaceDeclaration.class)) {
if ("bar".equalsIgnoreCase(c.getSimpleName())) {
addViolation(ctx, cu);
}
}
return super.visit(cu, ctx);
}
@Override
public String getName() {
return "NoBar";
}
}
@Test
void testClassLevelSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST1);
assertSize(rpt, 0);
rpt = java.executeRule(new FooRule(), TEST2);
assertSize(rpt, 0);
}
@Test
void testInheritedSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST3);
assertSize(rpt, 0);
}
@Test
void testMethodLevelSuppression() {
Report rpt;
rpt = java.executeRule(new FooRule(), TEST4);
assertSize(rpt, 1);
}
@Test
void testConstructorLevelSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST5);
assertSize(rpt, 0);
}
@Test
void testFieldLevelSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST6);
assertSize(rpt, 1);
}
@Test
void testParameterLevelSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST7);
assertSize(rpt, 1);
}
@Test
void testLocalVariableLevelSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST8);
assertSize(rpt, 1);
}
@Test
void testSpecificSuppression() {
Report rpt = java.executeRule(new FooRule(), TEST9);
assertSize(rpt, 1);
}
@Test
void testSpecificSuppressionValue1() {
Report rpt = java.executeRule(new FooRule(), TEST9_VALUE1);
assertSize(rpt, 1);
}
@Test
void testSpecificSuppressionValue2() {
Report rpt = java.executeRule(new FooRule(), TEST9_VALUE2);
assertSize(rpt, 1);
}
@Test
void testSpecificSuppressionValue3() {
Report rpt = java.executeRule(new FooRule(), TEST9_VALUE3);
assertSize(rpt, 1);
}
@Test
void testSpecificSuppressionMulitpleValues1() {
Report rpt = java.executeRule(new FooRule(), TEST9_MULTIPLE_VALUES_1);
assertSize(rpt, 0);
}
@Test
void testSpecificSuppressionMulitpleValues2() {
Report rpt = java.executeRule(new FooRule(), TEST9_MULTIPLE_VALUES_2);
assertSize(rpt, 0);
}
@Test
void testNoSuppressionBlank() {
Report rpt = java.executeRule(new FooRule(), TEST10);
assertSize(rpt, 2);
}
@Test
void testNoSuppressionSomethingElseS() {
Report rpt = java.executeRule(new FooRule(), TEST11);
assertSize(rpt, 2);
}
@Test
void testSuppressAll() {
Report rpt = java.executeRule(new FooRule(), TEST12);
assertSize(rpt, 0);
}
@Test
void testSpecificSuppressionAtTopLevel() {
Report rpt = java.executeRule(new BarRule(), TEST13);
assertSize(rpt, 0);
}
@Test
void testConstExpr() {
testAboutConstExpr(true, 0); // with the annotation, we should get no violation
testAboutConstExpr(false, 1); // without the annotation, we should get a violation
}
private void testAboutConstExpr(boolean hasAnnotation, int numExpectedViolations) {
Report rpt = java.executeRule(new FooRule(), constExprTest(hasAnnotation));
assertSize(rpt, numExpectedViolations);
}
private static final String TEST1 = "@SuppressWarnings(\"PMD\")\npublic class Foo {}";
private static final String TEST2 = "@SuppressWarnings(\"PMD\")\npublic class Foo {\n void bar() {\n int foo;\n }\n}";
private static final String TEST3 = "public class Baz {\n @SuppressWarnings(\"PMD\")\n public class Bar {\n void bar() {\n int foo;\n }\n }\n}";
private static final String TEST4 = "public class Foo {\n @SuppressWarnings(\"PMD\")\n void bar() {\n int foo;\n }\n}";
private static final String TEST5 = "public class Bar {\n @SuppressWarnings(\"PMD\")\n public Bar() {\n int foo;\n }\n}";
private static final String TEST6 = "public class Bar {\n @SuppressWarnings(\"PMD\")\n int foo;\n void bar() {\n int foo;\n }\n}";
private static final String TEST7 = "public class Bar {\n int foo;\n void bar(@SuppressWarnings(\"PMD\") int foo) {}\n}";
private static final String TEST8 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(\"PMD\") int foo;\n }\n}";
private static final String TEST9 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(\"PMD.NoFoo\") int foo;\n }\n}";
private static final String TEST9_VALUE1 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(value = \"PMD.NoFoo\") int foo;\n }\n}";
private static final String TEST9_VALUE2 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings({\"PMD.NoFoo\"}) int foo;\n }\n}";
private static final String TEST9_VALUE3 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(value = {\"PMD.NoFoo\"}) int foo;\n }\n}";
private static final String TEST9_MULTIPLE_VALUES_1 = "@SuppressWarnings({\"PMD.NoFoo\", \"PMD.NoBar\"})\npublic class Bar {\n int foo;\n void bar() {\n int foo;\n }\n}";
private static final String TEST9_MULTIPLE_VALUES_2 = "@SuppressWarnings(value = {\"PMD.NoFoo\", \"PMD.NoBar\"})\npublic class Bar {\n int foo;\n void bar() {\n int foo;\n }\n}";
private static final String TEST10 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(\"\") int foo;\n }\n}";
private static final String TEST11 = "public class Bar {\n int foo;\n void bar() {\n @SuppressWarnings(\"SomethingElse\") int foo;\n }\n}";
private static final String TEST12 = "public class Bar {\n @SuppressWarnings(\"all\") int foo;\n}";
private static final String TEST13 = "@SuppressWarnings(\"PMD.NoBar\")\npublic class Bar {\n}";
private static @NonNull String constExprTest(boolean withAnnot) {
return "public class NewClass {\n"
+ " private final static String SUPPRESS_PMD = \"PMD.\";\n"
+ "\n"
+ (withAnnot ? " @SuppressWarnings(SUPPRESS_PMD + \"NoFoo\")\n" : "")
+ " public void someMethod1(Object Foo) {\n"
+ " System.out.println(\"someMethod1\");\n"
+ " }\n"
+ "}";
}
}
| 7,488 | 34.661905 | 183 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/RuleSetFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
/**
* Test java's rulesets
*/
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
@Test
void testExclusionOfUselessParantheses() {
RuleSet ruleset = new RuleSetLoader().loadFromString("",
"<?xml version=\"1.0\"?>\n" + "<ruleset name=\"Custom ruleset for tests\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Custom ruleset for tests</description>\n"
+ " <rule ref=\"category/java/codestyle.xml\">\n"
+ " <exclude name=\"UselessParentheses\"/>\n" + " </rule>\n" + "</ruleset>\n");
Rule rule = ruleset.getRuleByName("UselessParentheses");
assertNull(rule);
}
}
| 1,432 | 39.942857 | 143 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/LanguageVersionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import java.util.Arrays;
import java.util.Collection;
import net.sourceforge.pmd.AbstractLanguageVersionTest;
import net.sourceforge.pmd.lang.Language;
class LanguageVersionTest extends AbstractLanguageVersionTest {
static Collection<TestDescriptor> data() {
final String name = JavaLanguageModule.NAME;
final String terseName = JavaLanguageModule.TERSE_NAME;
final Language java = getLanguage(name);
return Arrays.asList(
new TestDescriptor(name, terseName, "1.3", java.getVersion("1.3")),
new TestDescriptor(name, terseName, "1.4", java.getVersion("1.4")),
new TestDescriptor(name, terseName, "1.5", java.getVersion("1.5")),
new TestDescriptor(name, terseName, "1.6", java.getVersion("1.6")),
new TestDescriptor(name, terseName, "1.7", java.getVersion("1.7")),
new TestDescriptor(name, terseName, "1.8", java.getVersion("1.8")),
new TestDescriptor(name, terseName, "9", java.getVersion("9")),
new TestDescriptor(name, terseName, "10", java.getVersion("10")),
new TestDescriptor(name, terseName, "11", java.getVersion("11")),
new TestDescriptor(name, terseName, "12", java.getVersion("12")),
new TestDescriptor(name, terseName, "13", java.getVersion("13")),
new TestDescriptor(name, terseName, "14", java.getVersion("14")),
new TestDescriptor(name, terseName, "15", java.getVersion("15")),
new TestDescriptor(name, terseName, "16", java.getVersion("16")),
new TestDescriptor(name, terseName, "16-preview", java.getVersion("16-preview")),
new TestDescriptor(name, terseName, "17", java.getVersion("17")),
new TestDescriptor(name, terseName, "17-preview", java.getVersion("17-preview")),
// this one won't be found: case sensitive!
new TestDescriptor("JAVA", "JAVA", "1.7", null));
}
}
| 2,163 | 49.325581 | 97 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/JavaAttributesPrinter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTModifierList;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
/**
* Special tweak to remove deprecated attributes of AccessNode
*/
public class JavaAttributesPrinter extends RelevantAttributePrinter {
@Override
protected void fillAttributes(@NonNull Node node, @NonNull List<AttributeInfo> result) {
super.fillAttributes(node, result);
if (node instanceof ASTModifierList) {
result.add(getModifierAttr("EffectiveModifiers", ((ASTModifierList) node).getEffectiveModifiers()));
result.add(getModifierAttr("ExplicitModifiers", ((ASTModifierList) node).getExplicitModifiers()));
}
}
@Override
protected boolean ignoreAttribute(@NonNull Node node, @NonNull Attribute attribute) {
return super.ignoreAttribute(node, attribute)
// Deprecated attributes are removed from the output
// This is only for java-grammar, since deprecated getters will
// be removed, it would be a pain to update all tree dump tests
// everytime. OTOH failing dump tests would warn us that we removed
// something that wasn't deprecated
|| attribute.isDeprecated()
|| "MainMethod".equals(attribute.getName()) && node instanceof ASTMethodDeclaration && !isBooleanTrue(attribute.getValue())
|| "Expression".equals(attribute.getName()) && node instanceof ASTExpression;
}
private boolean isBooleanTrue(Object o) {
// for some reason Boolean::new is called somewhere in the reflection layer
return o instanceof Boolean && (Boolean) o;
}
private AttributeInfo getModifierAttr(String name, Set<JModifier> mods) {
return new AttributeInfo(name, mods.stream().map(JModifier::getToken).collect(Collectors.joining(", ", "{", "}")));
}
}
| 2,419 | 41.45614 | 135 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/BaseParserTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
/**
* Base class for tests that usually need processing stages to run when
* parsing code.
*/
public abstract class BaseParserTest {
protected final JavaParsingHelper java = JavaParsingHelper.DEFAULT.withResourceContext(getClass());
protected final JavaParsingHelper java5 = java.withDefaultVersion("1.5");
protected final JavaParsingHelper java8 = java.withDefaultVersion("1.8");
protected final JavaParsingHelper java9 = java.withDefaultVersion("9");
protected ASTCompilationUnit parseCode(final String code) {
return java.parse(code);
}
/**
* Parse and return an expression. Some variables are predeclared.
*/
protected ASTExpression parseExpr(String expr) {
ASTCompilationUnit ast = java.parse("class Foo {{ "
+ "String s1,s2,s3; "
+ "int i,j,k; "
+ "Object o = (" + expr + "); }}");
return ast.descendants(ASTExpression.class).crossFindBoundaries().firstOrThrow();
}
}
| 1,341 | 35.27027 | 103 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/BaseJavaTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
/**
* Special tweak to remove deprecated attributes of AccessNode
*/
public abstract class BaseJavaTreeDumpTest extends BaseTreeDumpTest {
protected BaseJavaTreeDumpTest() {
super(new JavaAttributesPrinter(), ".java");
}
}
| 430 | 22.944444 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/JavaLanguageModuleTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageVersion;
class JavaLanguageModuleTest {
@Test
void java9IsSmallerThanJava10() {
LanguageVersion java9 = JavaLanguageModule.getInstance().getVersion("9");
LanguageVersion java10 = JavaLanguageModule.getInstance().getVersion("10");
assertTrue(java9.compareTo(java10) < 0, "java9 should be smaller than java10");
}
@Test
void previewVersionShouldBeGreaterThanNonPreview() {
LanguageVersion java20 = JavaLanguageModule.getInstance().getVersion("20");
LanguageVersion java20p = JavaLanguageModule.getInstance().getVersion("20-preview");
assertTrue(java20p.compareTo(java20) > 0, "java20-preview should be greater than java20");
}
@Test
void testCompareToVersion() {
LanguageVersion java9 = JavaLanguageModule.getInstance().getVersion("9");
assertTrue(java9.compareToVersion("10") < 0, "java9 should be smaller than java10");
}
@Test
void allVersions() {
List<LanguageVersion> versions = JavaLanguageModule.getInstance().getVersions();
for (int i = 1; i < versions.size(); i++) {
LanguageVersion previous = versions.get(i - 1);
LanguageVersion current = versions.get(i);
assertTrue(previous.compareTo(current) < 0,
"Version " + previous + " should be smaller than " + current);
}
}
}
| 1,665 | 32.32 | 98 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.