repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/Attribute.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Represents an XPath attribute of a specific node.
* Attributes know their name, the node they wrap,
* and have access to their value.
*
* <p>Two attributes are equal if they have the same name
* and their parent nodes are equal.
*
* @author daniels
*/
public class Attribute {
private static final Logger LOG = LoggerFactory.getLogger(Attribute.class);
private final Node parent;
private final String name;
private final MethodHandle handle;
private final Method method;
private boolean invoked;
private Object value;
private String stringValue;
/** Creates a new attribute belonging to the given node using its accessor. */
public Attribute(Node parent, String name, MethodHandle handle, Method m) {
this.parent = parent;
this.name = name;
this.handle = handle;
this.method = m;
}
/** Creates a new attribute belonging to the given node using its string value. */
public Attribute(Node parent, String name, String value) {
this.parent = parent;
this.name = name;
this.value = value;
this.handle = null;
this.method = null;
this.stringValue = value;
this.invoked = true;
}
/**
* Gets the generic type of the value of this attribute.
*/
public Type getType() {
return method == null ? String.class : method.getGenericReturnType();
}
public String getName() {
return name;
}
public Node getParent() {
return parent;
}
/**
* Returns null for "not deprecated", empty string for "deprecated without replacement",
* otherwise name of replacement attribute.
*/
@InternalApi
public String replacementIfDeprecated() {
if (method == null) {
return null;
} else {
DeprecatedAttribute annot = method.getAnnotation(DeprecatedAttribute.class);
String result = annot != null
? annot.replaceWith()
: method.isAnnotationPresent(Deprecated.class)
? DeprecatedAttribute.NO_REPLACEMENT
: null;
if (result == null && List.class.isAssignableFrom(method.getReturnType())) {
// Lists are generally deprecated, see #2451
result = DeprecatedAttribute.NO_REPLACEMENT;
}
return result;
}
}
public boolean isDeprecated() {
return replacementIfDeprecated() != null;
}
public Object getValue() {
if (this.invoked) {
return this.value;
}
Object value;
// this lazy loading reduces calls to Method.invoke() by about 90%
try {
value = handle.invokeExact(parent);
} catch (Throwable iae) { // NOPMD
LOG.debug("Exception while fetching attribute value", iae);
value = null;
}
this.value = value;
this.invoked = true;
return value;
}
public String getStringValue() {
if (stringValue != null) {
return stringValue;
}
Object v = getValue();
stringValue = v == null ? "" : String.valueOf(v);
return stringValue;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Attribute attribute = (Attribute) o;
return Objects.equals(parent, attribute.parent)
&& Objects.equals(name, attribute.name);
}
@Override
public int hashCode() {
return Objects.hash(parent, name);
}
@Override
public String toString() {
return name + ':' + getValue() + ':' + parent.getXPathNodeName();
}
}
| 4,287 | 25.968553 | 92 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/DeprecatedAttribute.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Node attribute getter methods might be annotated with {@code DeprecatedAttribute}
* to mark the attribute as deprecated for XPath. Unlike {@link Deprecated}, this
* annotation does not deprecate the method for java usage.
*
* @since 6.21.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DeprecatedAttribute {
String NO_REPLACEMENT = "";
/**
* The simple name of the attribute to use for replacement (with '@' prefix).
* If empty, then the attribute is deprecated for removal.
*/
String replaceWith() default NO_REPLACEMENT;
}
| 955 | 26.314286 | 84 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/impl/AttributeAxisIterator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.impl;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.impl.AbstractNode;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.lang.rule.xpath.NoAttribute;
import net.sourceforge.pmd.lang.rule.xpath.NoAttribute.NoAttrScope;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* Explores an AST node reflectively to iterate over its XPath
* attributes. This is the default way the attributes of a node
* are made accessible to XPath rules, and defines an important
* piece of PMD's XPath support.
*/
public class AttributeAxisIterator implements Iterator<Attribute> {
/** Caches the precomputed attribute accessors of a given class. */
private static final ConcurrentMap<Class<?>, List<MethodWrapper>> METHOD_CACHE = new ConcurrentHashMap<>();
/* Constants used to determine which methods are accessors */
private static final Set<Class<?>> CONSIDERED_RETURN_TYPES
= new HashSet<>(Arrays.<Class<?>>asList(Integer.TYPE, Boolean.TYPE, Double.TYPE, String.class,
Long.TYPE, Character.TYPE, Float.TYPE));
private static final Set<String> FILTERED_OUT_NAMES
= new HashSet<>(Arrays.asList("toString",
"getNumChildren",
"getIndexInParent",
"getParent",
"getClass",
"getSourceCodeFile",
"isFindBoundary",
"getRuleIndex",
"getXPathNodeName",
"altNumber",
"toStringTree",
"getTypeNameNode",
"hashCode",
"getImportedNameNode",
"getScope"));
/* Iteration variables */
private final Iterator<MethodWrapper> iterator;
private final Node node;
/**
* Creates a new iterator that enumerates the attributes of the given node.
* Note: if you want to access the attributes of a node, don't use this directly,
* use instead the overridable {@link Node#getXPathAttributesIterator()}.
*/
public AttributeAxisIterator(Node contextNode) {
this.node = contextNode;
this.iterator = METHOD_CACHE.computeIfAbsent(contextNode.getClass(), this::getWrappersForClass).iterator();
}
private List<MethodWrapper> getWrappersForClass(Class<?> nodeClass) {
return Arrays.stream(nodeClass.getMethods())
.filter(m -> isAttributeAccessor(nodeClass, m))
.map(m -> {
try {
return new MethodWrapper(m);
} catch (IllegalAccessException e) {
throw AssertionUtil.shouldNotReachHere("Method should be accessible " + e);
}
})
.collect(Collectors.toList());
}
/**
* Returns whether the given method is an attribute accessor,
* in which case a corresponding Attribute will be added to
* the iterator.
*
* @param method The method to test
*/
protected boolean isAttributeAccessor(Class<?> nodeClass, Method method) {
String methodName = method.getName();
return !methodName.startsWith("jjt")
&& !FILTERED_OUT_NAMES.contains(methodName)
&& method.getParameterTypes().length == 0
&& isConsideredReturnType(method)
// filter out methods declared in supertypes like the
// Antlr ones, unless they're opted-in
&& Node.class.isAssignableFrom(method.getDeclaringClass())
&& !isIgnored(nodeClass, method);
}
private boolean isConsideredReturnType(Method method) {
Class<?> klass = method.getReturnType();
return CONSIDERED_RETURN_TYPES.contains(klass) || klass.isEnum();
}
private boolean isIgnored(Class<?> nodeClass, Method method) {
Class<?> declaration = method.getDeclaringClass();
if (method.isAnnotationPresent(NoAttribute.class)) {
return true;
} else if (declaration == Node.class || declaration == AbstractNode.class) {
// attributes from Node and AbstractNode are never suppressed
// we don't know what might go wrong if we do suppress them
return false;
}
NoAttribute declAnnot = declaration.getAnnotation(NoAttribute.class);
if (declAnnot != null && declAnnot.scope() == NoAttrScope.ALL) {
// then the parent didn't want children to inherit the attr
return true;
}
// we don't care about the parent annotation in the following
NoAttribute localAnnot = nodeClass.getAnnotation(NoAttribute.class);
if (localAnnot == null) {
return false;
} else if (!declaration.equals(nodeClass) || method.isBridge()) {
// Bridge methods appear declared in the subclass but represent
// an inherited method.
// Then the node suppressed the attributes of its parent
return localAnnot.scope() == NoAttrScope.INHERITED;
} else {
// then declaration == nodeClass so we need the scope to be ALL
return localAnnot.scope() == NoAttrScope.ALL;
}
}
@Override
public Attribute next() {
MethodWrapper m = iterator.next();
return new Attribute(node, m.name, m.methodHandle, m.method);
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
/**
* Associates an attribute accessor with the XPath-accessible
* name of the attribute. This is used to avoid recomputing
* the name of the attribute for each attribute (it's only done
* once and put inside the {@link #METHOD_CACHE}).
*/
private static class MethodWrapper {
static final Lookup LOOKUP = MethodHandles.publicLookup();
private static final MethodType GETTER_TYPE = MethodType.methodType(Object.class, Node.class);
public MethodHandle methodHandle;
public Method method;
public String name;
MethodWrapper(Method m) throws IllegalAccessException {
this.method = m;
this.methodHandle = LOOKUP.unreflect(m).asType(GETTER_TYPE);
this.name = truncateMethodName(m.getName());
}
/**
* This method produces the actual XPath name of an attribute
* from the name of its accessor.
*/
private String truncateMethodName(String n) {
// about 70% of the methods start with 'get', so this case goes
// first
if (n.startsWith("get")) {
return n.substring("get".length());
}
if (n.startsWith("is")) {
return n.substring("is".length());
}
if (n.startsWith("has")) {
return n.substring("has".length());
}
if (n.startsWith("uses")) {
return n.substring("uses".length());
}
if ("size".equals(n)) {
return "Size";
} else if ("length".equals(n)) {
return "Length";
}
return n;
}
}
}
| 8,128 | 36.809302 | 115 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/impl/XPathHandler.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.impl;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import net.sourceforge.pmd.lang.rule.xpath.internal.DefaultXPathFunctions;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
/**
* Interface for performing Language specific XPath handling, such as
* initialization and navigation.
*/
public interface XPathHandler {
/**
* Returns the set of extension functions for this language module.
* These are the additional functions available in XPath queries.
*/
Set<ExtensionFunctionDefinition> getRegisteredExtensionFunctions();
static XPathHandler noFunctionDefinitions() {
return DefaultXPathFunctions::getDefaultFunctions;
}
/**
* Returns a default XPath handler.
*/
static XPathHandler getHandlerForFunctionDefs(ExtensionFunctionDefinition first, ExtensionFunctionDefinition... defs) {
Set<ExtensionFunctionDefinition> set = new HashSet<>(CollectionUtil.setOf(first, defs));
set.addAll(DefaultXPathFunctions.getDefaultFunctions());
return () -> Collections.unmodifiableSet(set);
}
}
| 1,296 | 28.477273 | 123 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/impl/AbstractXPathFunctionDef.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.impl;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.StructuredQName;
/**
* Base impl for an XPath function definition.
* This uses Saxon API.
*
* @since 7.0.0
*/
public abstract class AbstractXPathFunctionDef extends ExtensionFunctionDefinition {
private static final String PMD_URI_PREFIX = "http://pmd.sourceforge.net/";
private final StructuredQName qname;
private AbstractXPathFunctionDef(String localName, String namespacePrefix, String uri) {
this.qname = new StructuredQName(namespacePrefix, uri, localName);
}
protected AbstractXPathFunctionDef(String localName) {
this(localName, "pmd", PMD_URI_PREFIX + "pmd-core");
}
protected AbstractXPathFunctionDef(String localName, String languageTerseName) {
this(localName, "pmd-" + languageTerseName, PMD_URI_PREFIX + "pmd-" + languageTerseName);
}
@Override
public final StructuredQName getFunctionQName() {
return qname;
}
}
| 1,130 | 28 | 97 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/ExpressionPrinter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import net.sf.saxon.expr.AxisExpression;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.RootExpression;
import net.sf.saxon.expr.VennExpression;
import net.sf.saxon.expr.parser.Token;
import net.sf.saxon.om.AxisInfo;
/**
* Simple printer for saxon expressions. Might be useful for debugging / during development.
*
* <p>Example:
* <pre>
* ExpressionPrinter printer = new ExpressionPrinter();
* printer.visit(query.xpathExpression.getInternalExpression());
* </pre>
*/
public class ExpressionPrinter extends SaxonExprVisitor {
private int depth = 0;
private void print(String s) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.println(s);
}
@Override
public Expression visit(AxisExpression e) {
print("axis=" + AxisInfo.axisName[e.getAxis()] + "(test=" + e.getNodeTest() + ")");
return super.visit(e);
}
@Override
public Expression visit(RootExpression e) {
print("/");
return super.visit(e);
}
@Override
public Expression visit(VennExpression e) {
print("venn=" + Token.tokens[e.getOperator()]);
return super.visit(e);
}
@Override
public Expression visit(Expression expr) {
depth++;
print(expr.getClass().getSimpleName());
Expression result = super.visit(expr);
depth--;
return result;
}
}
| 1,573 | 25.233333 | 92 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/SplitUnions.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.ArrayList;
import java.util.List;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.LetExpression;
import net.sf.saxon.expr.VennExpression;
import net.sf.saxon.expr.parser.Token;
import net.sf.saxon.expr.sort.DocumentSorter;
/**
* Splits a venn expression with the union operator into single expressions.
*
* <p>E.g. "//A | //B | //C" will result in 3 expressions "//A", "//B", and "//C".
*/
class SplitUnions extends SaxonExprVisitor {
private final List<Expression> expressions = new ArrayList<>();
@Override
public Expression visit(VennExpression e) {
if (e.getOperator() == Token.UNION) {
for (Expression operand : listOf(e.getLhsExpression(), e.getRhsExpression())) {
if (operand instanceof VennExpression) {
visit(operand);
} else {
expressions.add(operand);
}
}
}
return e;
}
@Override
public Expression visit(Expression e) {
// only flatten top level unions - skip sorters and let around it
if (e instanceof VennExpression || e instanceof DocumentSorter || e instanceof LetExpression) {
return super.visit(e);
} else {
return e;
}
}
public List<Expression> getExpressions() {
return expressions;
}
}
| 1,591 | 27.428571 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/SaxonExprVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import net.sf.saxon.expr.AndExpression;
import net.sf.saxon.expr.AxisExpression;
import net.sf.saxon.expr.BinaryExpression;
import net.sf.saxon.expr.BooleanExpression;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.FilterExpression;
import net.sf.saxon.expr.LetExpression;
import net.sf.saxon.expr.OrExpression;
import net.sf.saxon.expr.QuantifiedExpression;
import net.sf.saxon.expr.RootExpression;
import net.sf.saxon.expr.SlashExpression;
import net.sf.saxon.expr.VennExpression;
import net.sf.saxon.expr.sort.DocumentSorter;
abstract class SaxonExprVisitor {
public Expression visit(DocumentSorter e) {
Expression base = visit(e.getBaseExpression());
return new DocumentSorter(base);
}
public Expression visit(SlashExpression e) {
Expression start = visit(e.getStart());
Expression step = visit(e.getStep());
return new SlashExpression(start, step);
}
public Expression visit(RootExpression e) {
return e;
}
public Expression visit(AxisExpression e) {
return e;
}
public Expression visit(VennExpression e) {
Expression operand0 = visit(e.getLhsExpression());
Expression operand1 = visit(e.getRhsExpression());
return new VennExpression(operand0, e.getOperator(), operand1);
}
public Expression visit(FilterExpression e) {
Expression base = visit(e.getLhsExpression());
Expression filter = visit(e.getFilter());
return new FilterExpression(base, filter);
}
public Expression visit(BinaryExpression e) {
Expression base = visit(e.getLhsExpression());
Expression filter = visit(e.getRhsExpression());
return new FilterExpression(base, filter);
}
public Expression visit(QuantifiedExpression e) {
return e;
}
public Expression visit(LetExpression e) {
Expression action = visit(e.getAction());
Expression sequence = visit(e.getSequence());
LetExpression result = new LetExpression();
result.setAction(action);
result.setSequence(sequence);
result.setVariableQName(e.getVariableQName());
result.setRequiredType(e.getRequiredType());
result.setSlotNumber(e.getLocalSlotNumber());
return result;
}
public Expression visit(BooleanExpression e) {
Expression operand0 = visit(e.getLhsExpression());
Expression operand1 = visit(e.getRhsExpression());
return e instanceof AndExpression ? new AndExpression(operand0, operand1)
: new OrExpression(operand0, operand1);
}
public Expression visit(Expression expr) {
Expression result;
if (expr instanceof DocumentSorter) {
result = visit((DocumentSorter) expr);
} else if (expr instanceof SlashExpression) {
result = visit((SlashExpression) expr);
} else if (expr instanceof RootExpression) {
result = visit((RootExpression) expr);
} else if (expr instanceof AxisExpression) {
result = visit((AxisExpression) expr);
} else if (expr instanceof VennExpression) {
result = visit((VennExpression) expr);
} else if (expr instanceof FilterExpression) {
result = visit((FilterExpression) expr);
} else if (expr instanceof QuantifiedExpression) {
result = visit((QuantifiedExpression) expr);
} else if (expr instanceof LetExpression) {
result = visit((LetExpression) expr);
} else if (expr instanceof BooleanExpression) {
result = visit((BooleanExpression) expr);
} else {
result = expr;
}
return result;
}
}
| 3,895 | 34.418182 | 81 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/XPathElementToNodeHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import net.sourceforge.pmd.lang.ast.Node;
import net.sf.saxon.tree.wrapper.AbstractNodeWrapper;
/**
* A function that returns the current file name.
*
* @author Clément Fournier
*/
public final class XPathElementToNodeHelper {
public static final String PMD_NODE_USER_DATA = "pmd.node";
private XPathElementToNodeHelper() {
}
static Node itemToNode(Object item) {
if (item instanceof Node) {
return (Node) item;
} else if (item instanceof AstElementNode) {
return itemToNode(((AstElementNode) item).getUnderlyingNode());
} else if (item instanceof AbstractNodeWrapper) {
return itemToNode(((AbstractNodeWrapper) item).getUnderlyingNode());
} else if (item instanceof org.w3c.dom.Node) {
return itemToNode(((org.w3c.dom.Node) item).getUserData(PMD_NODE_USER_DATA));
}
return null;
}
}
| 1,053 | 27.486486 | 89 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/DefaultXPathFunctions.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Set;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
/**
* Default XPath functions provided by pmd-core.
*/
public final class DefaultXPathFunctions {
private static final Set<ExtensionFunctionDefinition> DEFAULTS =
CollectionUtil.immutableSetOf(
FileNameXPathFunction.INSTANCE,
CoordinateXPathFunction.START_LINE,
CoordinateXPathFunction.START_COLUMN,
CoordinateXPathFunction.END_LINE,
CoordinateXPathFunction.END_COLUMN
);
private DefaultXPathFunctions() {
// utility class
}
public static Set<ExtensionFunctionDefinition> getDefaultFunctions() {
return DEFAULTS;
}
}
| 904 | 24.138889 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/DomainConversion.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sf.saxon.om.AtomicArray;
import net.sf.saxon.om.AtomicSequence;
import net.sf.saxon.om.EmptyAtomicSequence;
import net.sf.saxon.type.BuiltInAtomicType;
import net.sf.saxon.type.SchemaType;
import net.sf.saxon.value.AtomicValue;
import net.sf.saxon.value.BigIntegerValue;
import net.sf.saxon.value.BooleanValue;
import net.sf.saxon.value.DoubleValue;
import net.sf.saxon.value.FloatValue;
import net.sf.saxon.value.Int64Value;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;
import net.sf.saxon.value.UntypedAtomicValue;
/**
* Converts Java values into XPath values.
*/
public final class DomainConversion {
private DomainConversion() {
}
public static SchemaType buildType(java.lang.reflect.Type type) {
switch (type.getTypeName()) {
case "java.lang.Integer":
case "java.lang.Long":
return BuiltInAtomicType.INTEGER;
case "java.lang.Double":
case "java.lang.Float":
return BuiltInAtomicType.DOUBLE;
case "java.lang.String":
case "java.lang.Character":
case "java.lang.Class":
case "java.util.regex.Pattern":
return BuiltInAtomicType.STRING;
default:
return BuiltInAtomicType.UNTYPED_ATOMIC;
}
}
@NonNull
public static AtomicSequence convert(Object obj) {
if (obj instanceof Collection) {
return getSequenceRepresentation((Collection<?>) obj);
}
return getAtomicRepresentation(obj);
}
public static SequenceType typeOf(Object obj) {
if (obj instanceof Collection) {
if (((Collection<?>) obj).isEmpty()) {
return SequenceType.EMPTY_SEQUENCE;
}
return SequenceType.NON_EMPTY_SEQUENCE;
} else if (obj instanceof String) {
return SequenceType.SINGLE_STRING;
} else if (obj instanceof Boolean) {
return SequenceType.SINGLE_BOOLEAN;
} else if (obj instanceof Integer) {
return SequenceType.SINGLE_INTEGER;
} else if (obj instanceof Float) {
return SequenceType.SINGLE_FLOAT;
} else if (obj instanceof Long) {
return SequenceType.SINGLE_INTEGER;
} else if (obj instanceof Double) {
return SequenceType.SINGLE_DOUBLE;
} else if (obj instanceof Number) {
return SequenceType.SINGLE_NUMERIC;
} else if (obj instanceof Enum<?>) {
return SequenceType.SINGLE_STRING;
} else if (obj instanceof Character) {
return SequenceType.SINGLE_STRING;
} else if (obj instanceof Pattern) {
return SequenceType.SINGLE_STRING;
}
return SequenceType.SINGLE_ITEM;
}
public static AtomicSequence getSequenceRepresentation(Collection<?> list) {
if (list == null || list.isEmpty()) {
return EmptyAtomicSequence.getInstance();
}
List<AtomicValue> vs = new ArrayList<>(list.size());
flattenInto(list, vs);
return new AtomicArray(vs);
}
// sequences cannot be nested, this takes care of list of lists,
// just in case
private static void flattenInto(Collection<?> list, List<AtomicValue> values) {
for (Object o : list) {
if (o instanceof Collection) {
flattenInto((Collection<?>) o, values);
} else {
values.add(getAtomicRepresentation(o));
}
}
}
/**
* Gets the Saxon representation of the parameter, if its type corresponds
* to an XPath 2.0 atomic datatype.
*
* @param value The value to convert
*
* @return The converted AtomicValue
*/
@NonNull
public static AtomicValue getAtomicRepresentation(final Object value) {
/*
FUTURE When supported, we should consider refactor this implementation to use Pattern Matching
(see http://openjdk.java.net/jeps/305) so that it looks clearer.
*/
if (value == null) {
return UntypedAtomicValue.ZERO_LENGTH_UNTYPED;
} else if (value instanceof String) {
return new StringValue((String) value);
} else if (value instanceof Boolean) {
return BooleanValue.get((Boolean) value);
} else if (value instanceof Integer) {
return Int64Value.makeIntegerValue((Integer) value);
} else if (value instanceof Long) {
return new BigIntegerValue((Long) value);
} else if (value instanceof Double) {
return new DoubleValue((Double) value);
} else if (value instanceof Character) {
return new StringValue(value.toString());
} else if (value instanceof Float) {
return new FloatValue((Float) value);
} else if (value instanceof Pattern || value instanceof Enum) {
return new StringValue(String.valueOf(value));
} else {
// We could maybe use UntypedAtomicValue
throw new RuntimeException("Unable to create ValueRepresentation for value of type: " + value.getClass());
}
}
}
| 5,479 | 33.683544 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/SaxonXPathRuleQuery.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.PmdXPathException;
import net.sourceforge.pmd.lang.rule.xpath.PmdXPathException.Phase;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.util.DataMap;
import net.sourceforge.pmd.util.DataMap.SimpleDataKey;
import net.sf.saxon.Configuration;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.LocalVariableReference;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.om.AtomicSequence;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.NamePool;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.sxpath.IndependentContext;
import net.sf.saxon.sxpath.XPathDynamicContext;
import net.sf.saxon.sxpath.XPathEvaluator;
import net.sf.saxon.sxpath.XPathExpression;
import net.sf.saxon.sxpath.XPathVariable;
import net.sf.saxon.trans.XPathException;
/**
* This is a Saxon based XPathRule query.
*/
public class SaxonXPathRuleQuery {
/**
* Special nodeName that references the root expression.
*/
static final String AST_ROOT = "_AST_ROOT_";
private static final Logger LOG = LoggerFactory.getLogger(SaxonXPathRuleQuery.class);
private static final NamePool NAME_POOL = new NamePool();
/** Cache key for the wrapped tree for saxon. */
private static final SimpleDataKey<AstTreeInfo> SAXON_TREE_CACHE_KEY = DataMap.simpleDataKey("saxon.tree");
private final String xpathExpr;
@SuppressWarnings("PMD") // may be useful later, idk
private final XPathVersion version;
private final Map<PropertyDescriptor<?>, Object> properties;
private final XPathHandler xPathHandler;
private final List<String> rulechainQueries = new ArrayList<>();
private Configuration configuration;
/**
* Contains for each nodeName a sub expression, used for implementing rule chain.
*/
Map<String, List<Expression>> nodeNameToXPaths = new HashMap<>();
/**
* Representation of an XPath query, created at {@link #initialize()} using {@link #xpathExpr}.
*/
XPathExpression xpathExpression;
private final DeprecatedAttrLogger attrCtx;
public SaxonXPathRuleQuery(String xpathExpr,
XPathVersion version,
Map<PropertyDescriptor<?>, Object> properties,
XPathHandler xPathHandler,
DeprecatedAttrLogger logger) throws PmdXPathException {
this.xpathExpr = xpathExpr;
this.version = version;
this.properties = properties;
this.xPathHandler = xPathHandler;
this.attrCtx = logger;
try {
initialize();
} catch (XPathException e) {
throw wrapException(e, Phase.INITIALIZATION);
}
}
public String getXpathExpression() {
return xpathExpr;
}
public List<String> getRuleChainVisits() {
return rulechainQueries;
}
public List<Node> evaluate(final Node node) {
final AstTreeInfo documentNode = getDocumentNodeForRootNode(node);
documentNode.setAttrCtx(attrCtx);
try {
// Map AST Node -> Saxon Node
final XPathDynamicContext xpathDynamicContext = xpathExpression.createDynamicContext(documentNode.findWrapperFor(node));
// XPath 2.0 sequences may contain duplicates
final Set<Node> results = new LinkedHashSet<>();
List<Expression> expressions = getExpressionsForLocalNameOrDefault(node.getXPathNodeName());
for (Expression expression : expressions) {
@SuppressWarnings("PMD.CloseResource")
SequenceIterator iterator = expression.iterate(xpathDynamicContext.getXPathContextObject());
Item current = iterator.next();
while (current != null) {
if (current instanceof AstNodeOwner) {
results.add(((AstNodeOwner) current).getUnderlyingNode());
} else {
throw new XPathException("XPath rule expression returned a non-node (" + current.getClass() + "): " + current);
}
current = iterator.next();
}
}
final List<Node> sortedRes = new ArrayList<>(results);
sortedRes.sort(RuleChainAnalyzer.documentOrderComparator());
return sortedRes;
} catch (final XPathException e) {
throw wrapException(e, Phase.EVALUATION);
} finally {
documentNode.setAttrCtx(DeprecatedAttrLogger.noop());
}
}
private ContextedRuntimeException wrapException(XPathException e, Phase phase) {
return new PmdXPathException(e, phase, xpathExpr, version);
}
// test only
List<Expression> getExpressionsForLocalNameOrDefault(String nodeName) {
List<Expression> expressions = nodeNameToXPaths.get(nodeName);
if (expressions != null) {
return expressions;
}
return nodeNameToXPaths.get(AST_ROOT);
}
// test only
Expression getFallbackExpr() {
return nodeNameToXPaths.get(SaxonXPathRuleQuery.AST_ROOT).get(0);
}
/**
* Gets the DocumentNode representation for the whole AST in which the node is, that is, if the node is not the root
* of the AST, then the AST is traversed all the way up until the root node is found. If the DocumentNode was
* cached because this method was previously called, then a new DocumentNode will not be instanced.
*
* @param node the node from which the root node will be looked for.
*
* @return the DocumentNode representing the whole AST
*/
private AstTreeInfo getDocumentNodeForRootNode(final Node node) {
final RootNode root = node.getRoot();
return root.getUserMap().computeIfAbsent(SAXON_TREE_CACHE_KEY, () -> new AstTreeInfo(root, configuration));
}
private void addExpressionForNode(String nodeName, Expression expression) {
nodeNameToXPaths.computeIfAbsent(nodeName, n -> new ArrayList<>(2)).add(expression);
}
private void initialize() throws XPathException {
this.configuration = Configuration.newConfiguration();
this.configuration.setNamePool(getNamePool());
StaticContextWithProperties staticCtx = new StaticContextWithProperties(this.configuration);
staticCtx.setXPathLanguageLevel(version == XPathVersion.XPATH_3_1 ? 31 : 20);
staticCtx.declareNamespace("fn", NamespaceConstant.FN);
for (final PropertyDescriptor<?> propertyDescriptor : properties.keySet()) {
final String name = propertyDescriptor.name();
if (!"xpath".equals(name) && !XPathRule.VERSION_DESCRIPTOR.name().equals(name)) {
staticCtx.declareProperty(propertyDescriptor);
}
}
for (ExtensionFunctionDefinition fun : xPathHandler.getRegisteredExtensionFunctions()) {
StructuredQName qname = fun.getFunctionQName();
staticCtx.declareNamespace(qname.getPrefix(), qname.getURI());
this.configuration.registerExtensionFunction(fun);
}
final XPathEvaluator xpathEvaluator = new XPathEvaluator(configuration);
xpathEvaluator.setStaticContext(staticCtx);
xpathExpression = xpathEvaluator.createExpression(xpathExpr);
analyzeXPathForRuleChain(xpathEvaluator);
}
private void analyzeXPathForRuleChain(final XPathEvaluator xpathEvaluator) {
final Expression expr = xpathExpression.getInternalExpression();
boolean useRuleChain = true;
// First step: Split the union venn expressions into single expressions
Iterable<Expression> subexpressions = SaxonExprTransformations.splitUnions(expr);
// Second step: Analyze each expression separately
for (final Expression subexpression : subexpressions) { // final because of checkstyle
Expression modified = subexpression;
modified = SaxonExprTransformations.hoistFilters(modified);
modified = SaxonExprTransformations.reduceRoot(modified);
modified = SaxonExprTransformations.copyTopLevelLets(modified, expr);
RuleChainAnalyzer rca = new RuleChainAnalyzer(xpathEvaluator.getConfiguration());
final Expression finalExpr = rca.visit(modified); // final because of lambda
if (!rca.getRootElements().isEmpty()) {
rca.getRootElements().forEach(it -> addExpressionForNode(it, finalExpr));
} else {
// couldn't find a root element for the expression, that means, we can't use rule chain at all
// even though, it would be possible for part of the expression.
useRuleChain = false;
break;
}
}
if (useRuleChain) {
rulechainQueries.addAll(nodeNameToXPaths.keySet());
} else {
nodeNameToXPaths.clear();
LOG.debug("Unable to use RuleChain for XPath: {}", xpathExpr);
}
// always add fallback expression
addExpressionForNode(AST_ROOT, xpathExpression.getInternalExpression());
}
public static NamePool getNamePool() {
return NAME_POOL;
}
final class StaticContextWithProperties extends IndependentContext {
private final Map<StructuredQName, PropertyDescriptor<?>> propertiesByName = new HashMap<>();
StaticContextWithProperties(Configuration config) {
super(config);
}
public void declareProperty(PropertyDescriptor<?> prop) {
XPathVariable var = declareVariable(null, prop.name());
propertiesByName.put(var.getVariableQName(), prop);
}
@Override
public Expression bindVariable(StructuredQName qName) throws XPathException {
LocalVariableReference local = (LocalVariableReference) super.bindVariable(qName);
PropertyDescriptor<?> prop = propertiesByName.get(qName);
if (prop == null || prop.defaultValue() == null) {
return local;
}
// TODO Saxon optimizer bug (js/codestyle.xml/AssignmentInOperand)
Object actualValue = properties.getOrDefault(prop, prop.defaultValue());
AtomicSequence converted = DomainConversion.convert(actualValue);
local.setStaticType(null, converted, 0);
return local;
}
}
}
| 11,272 | 38.142361 | 135 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/BaseNodeInfo.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.List;
import java.util.function.Predicate;
import net.sf.saxon.om.NamePool;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.pattern.AnyNodeTest;
import net.sf.saxon.tree.iter.AxisIterator;
import net.sf.saxon.tree.iter.ListIterator;
import net.sf.saxon.tree.iter.ReverseListIterator;
import net.sf.saxon.tree.util.Navigator.AxisFilter;
import net.sf.saxon.tree.wrapper.AbstractNodeWrapper;
import net.sf.saxon.tree.wrapper.SiblingCountingNode;
abstract class BaseNodeInfo extends AbstractNodeWrapper implements SiblingCountingNode {
// It's important that all our NodeInfo implementations share the
// same getNodeKind implementation, otherwise NameTest spends a lot
// of time in virtual dispatch
private final int nodeKind;
private final NamePool namePool;
private final int fingerprint;
protected final BaseNodeInfo parent;
BaseNodeInfo(int nodeKind, NamePool namePool, String localName, BaseNodeInfo parent) {
this.nodeKind = nodeKind;
this.namePool = namePool;
this.fingerprint = namePool.allocateFingerprint("", localName) & NamePool.FP_MASK;
this.parent = parent;
}
abstract List<AstElementNode> getChildren();
@Override
public AstTreeInfo getTreeInfo() {
return (AstTreeInfo) treeInfo;
}
@Override
public final String getURI() {
return "";
}
@Override
public final String getBaseURI() {
return "";
}
@Override
public String getPrefix() {
return "";
}
@Override
public final BaseNodeInfo getParent() {
return parent;
}
@Override
public final int getFingerprint() {
return fingerprint;
}
@Override
public final boolean hasFingerprint() {
return true;
}
@Override
public final NamePool getNamePool() {
return namePool;
}
@Override
public final int getNodeKind() {
return nodeKind;
}
protected static AxisIterator filter(Predicate<? super NodeInfo> nodeTest, AxisIterator iter) {
return nodeTest == null || (nodeTest instanceof AnyNodeTest) ? iter : new AxisFilter(iter, nodeTest);
}
static AxisIterator iterateList(List<? extends NodeInfo> nodes) {
return iterateList(nodes, true);
}
@SuppressWarnings({"unchecked", "rawtypes"})
static AxisIterator iterateList(List<? extends NodeInfo> nodes, boolean forwards) {
return forwards ? new ListIterator.OfNodes((List) nodes)
: new RevListAxisIterator((List) nodes);
}
private static class RevListAxisIterator extends ReverseListIterator<NodeInfo> implements AxisIterator {
RevListAxisIterator(List<NodeInfo> list) {
super(list);
}
}
}
| 2,935 | 26.439252 | 109 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/AstAttributeNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sf.saxon.om.AtomicSequence;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.tree.iter.AxisIterator;
import net.sf.saxon.tree.iter.EmptyIterator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.tree.util.Navigator;
import net.sf.saxon.tree.wrapper.SiblingCountingNode;
import net.sf.saxon.type.SchemaType;
import net.sf.saxon.type.Type;
/**
* @since 7.0.0
*/
class AstAttributeNode extends BaseNodeInfo implements SiblingCountingNode {
private final Attribute attribute;
private AtomicSequence value;
private final SchemaType schemaType;
private final int siblingPosition;
AstAttributeNode(AstElementNode parent, Attribute attribute, int siblingPosition) {
super(Type.ATTRIBUTE, parent.getNamePool(), attribute.getName(), parent);
this.attribute = attribute;
this.schemaType = DomainConversion.buildType(attribute.getType());
this.siblingPosition = siblingPosition;
this.treeInfo = parent.getTreeInfo();
}
@Override
List<AstElementNode> getChildren() {
return Collections.emptyList();
}
@Override
public int getSiblingPosition() {
return siblingPosition;
}
@Override
protected AxisIterator iterateAttributes(Predicate<? super NodeInfo> nodeTest) {
return EmptyIterator.ofNodes();
}
@Override
protected AxisIterator iterateChildren(Predicate<? super NodeInfo> nodeTest) {
return EmptyIterator.ofNodes();
}
@Override
protected AxisIterator iterateSiblings(Predicate<? super NodeInfo> nodeTest, boolean forwards) {
return EmptyIterator.ofNodes();
}
@Override
public AtomicSequence atomize() {
if (value == null) {
value = DomainConversion.convert(attribute.getValue());
}
return value;
}
@Override
public SchemaType getSchemaType() {
return schemaType;
}
@Override
public Attribute getUnderlyingNode() {
return attribute;
}
@Override
public int compareOrder(NodeInfo other) {
if (other instanceof SiblingCountingNode) {
return Navigator.compareOrder(this, (SiblingCountingNode) other);
}
throw new UnsupportedOperationException();
}
@Override
public String getLocalPart() {
return attribute.getName();
}
@Override
public void generateId(FastStringBuffer buffer) {
buffer.append(Integer.toString(hashCode()));
}
@Override
public CharSequence getStringValueCS() {
getTreeInfo().getLogger().recordUsageOf(attribute);
return attribute.getStringValue();
}
}
| 2,967 | 24.586207 | 100 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/RuleChainAnalyzer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
import net.sourceforge.pmd.lang.ast.Node;
import net.sf.saxon.Configuration;
import net.sf.saxon.expr.AxisExpression;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.FilterExpression;
import net.sf.saxon.expr.LetExpression;
import net.sf.saxon.expr.RootExpression;
import net.sf.saxon.expr.SlashExpression;
import net.sf.saxon.expr.VennExpression;
import net.sf.saxon.expr.sort.DocumentSorter;
import net.sf.saxon.om.AxisInfo;
import net.sf.saxon.pattern.CombinedNodeTest;
import net.sf.saxon.pattern.NameTest;
import net.sf.saxon.type.Type;
/**
* Analyzes the xpath expression to find the root path selector for a element. If found,
* the element name is available via {@link RuleChainAnalyzer#getRootElements()} and the
* expression is rewritten to start at "node::self()" instead.
*
* <p>It uses a visitor to visit all the different expressions.
*
* <p>Example: The XPath expression <code>//A[condition()]/B</code> results the rootElement "A"
* and the expression is rewritten to be <code>self::node[condition()]/B</code>.
*
* <p>DocumentSorter expression is removed. The sorting of the resulting nodes needs to be done
* after all (sub)expressions have been executed.
*/
public class RuleChainAnalyzer extends SaxonExprVisitor {
private final Configuration configuration;
private List<String> rootElement;
private boolean rootElementReplaced;
private boolean insideExpensiveExpr;
private boolean foundPathInsideExpensive;
private boolean foundCombinedNodeTest;
public RuleChainAnalyzer(Configuration currentConfiguration) {
this.configuration = currentConfiguration;
}
public List<String> getRootElements() {
if (!foundPathInsideExpensive && rootElementReplaced) {
return rootElement == null ? Collections.emptyList() : rootElement;
}
return Collections.emptyList();
}
@Override
public Expression visit(DocumentSorter e) {
DocumentSorter result = (DocumentSorter) super.visit(e);
// sorting of the nodes must be done after all nodes have been found
return result.getBaseExpression();
}
public Expression visitSlashPreserveRootElement(SlashExpression e) {
Expression start = visit(e.getStart());
// save state
List<String> elt = rootElement;
boolean replaced = rootElementReplaced;
Expression step = visit(e.getStep());
if (!(e.getStart() instanceof RootExpression)) {
// restore
rootElement = elt;
rootElementReplaced = replaced;
}
return new SlashExpression(start, step);
}
@Override
public Expression visit(SlashExpression e) {
if (!insideExpensiveExpr && rootElement == null) {
Expression result = visitSlashPreserveRootElement(e);
if (rootElement != null && !rootElementReplaced) {
if (result instanceof SlashExpression) {
SlashExpression newPath = (SlashExpression) result;
Expression step = newPath.getStep();
if (step instanceof FilterExpression) {
FilterExpression filterExpression = (FilterExpression) step;
Deque<Expression> filters = new ArrayDeque<>();
Expression walker = filterExpression;
while (walker instanceof FilterExpression) {
filters.push(((FilterExpression) walker).getFilter());
walker = ((FilterExpression) walker).getBase();
}
result = new FilterExpression(new AxisExpression(AxisInfo.SELF, null), filters.pop());
while (!filters.isEmpty()) {
result = new FilterExpression(result, filters.pop());
}
rootElementReplaced = true;
} else if (step instanceof AxisExpression) {
Expression start = newPath.getStart();
if (start instanceof RootExpression) {
result = new AxisExpression(AxisInfo.SELF, null);
} else if (start instanceof VennExpression) {
// abort, set rootElementReplaced so that the
// nodes above won't try to replace themselves
rootElement = null;
result = e;
} else {
result = new SlashExpression(start, new AxisExpression(AxisInfo.SELF, null));
}
rootElementReplaced = true;
}
} else {
result = new AxisExpression(AxisInfo.DESCENDANT_OR_SELF, null);
rootElementReplaced = true;
}
}
return result;
} else {
if (insideExpensiveExpr) {
foundPathInsideExpensive = true;
}
return super.visit(e);
}
}
@Override
public Expression visit(AxisExpression e) {
if (rootElement == null && e.getNodeTest() instanceof NameTest && !foundCombinedNodeTest) {
NameTest test = (NameTest) e.getNodeTest();
if (test.getPrimitiveType() == Type.ELEMENT && e.getAxis() == AxisInfo.DESCENDANT) {
rootElement = listOf(configuration.getNamePool().getClarkName(test.getFingerprint()));
} else if (test.getPrimitiveType() == Type.ELEMENT && e.getAxis() == AxisInfo.CHILD) {
rootElement = listOf(configuration.getNamePool().getClarkName(test.getFingerprint()));
}
} else if (e.getNodeTest() instanceof CombinedNodeTest) {
foundCombinedNodeTest = true;
}
return super.visit(e);
}
@Override
public Expression visit(LetExpression e) {
// lazy expressions are not a thing in saxon HE
// instead saxon hoists expensive subexpressions into LetExpressions
// Eg //A[//B]
// is transformed to let bs := //B in //A
// so that the //B is done only once.
// The cost of an expr is an abstract measure of its expensiveness,
// Eg the cost of //A or //* is 40, the cost of //A//B is 820
// (a path expr multiplies the cost of its lhs and rhs)
if (e.getSequence().getCost() >= 20) {
boolean prevCtx = insideExpensiveExpr;
insideExpensiveExpr = true;
Expression result = super.visit(e);
insideExpensiveExpr = prevCtx;
return result;
} else {
return super.visit(e);
}
}
@Override
public Expression visit(VennExpression e) {
// stop visiting subtree. We assume all unions were at the root
// and flattened, here we find one that couldn't be flattened
return e;
}
public static Comparator<Node> documentOrderComparator() {
return PmdDocumentSorter.INSTANCE;
}
}
| 7,468 | 38.518519 | 110 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/SaxonExprTransformations.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Collections;
import net.sf.saxon.expr.AxisExpression;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.FilterExpression;
import net.sf.saxon.expr.LetExpression;
import net.sf.saxon.expr.RootExpression;
import net.sf.saxon.expr.SlashExpression;
import net.sf.saxon.om.AxisInfo;
import net.sf.saxon.pattern.AnyNodeTest;
import net.sf.saxon.pattern.NodeTest;
/**
* Utilities to transform saxon expression trees.
*/
final class SaxonExprTransformations {
private SaxonExprTransformations() {
// utility class
}
private static final SaxonExprVisitor FILTER_HOISTER = new SaxonExprVisitor() {
@Override
public Expression visit(SlashExpression e) {
Expression left = super.visit(e.getLhsExpression());
Expression right = super.visit(e.getRhsExpression());
if (right instanceof FilterExpression) {
Expression middle = ((FilterExpression) right).getBase();
Expression filter = ((FilterExpression) right).getFilter();
return new FilterExpression(new SlashExpression(left, middle), filter);
}
return super.visit(e);
}
};
private static final SaxonExprVisitor ROOT_REDUCER = new SaxonExprVisitor() {
@Override
public Expression visit(SlashExpression e) {
Expression left = super.visit(e.getLhsExpression());
Expression right = super.visit(e.getRhsExpression());
if (right instanceof AxisExpression
&& ((AxisExpression) right).getAxis() == AxisInfo.CHILD
&& left instanceof SlashExpression) {
Expression leftLeft = ((SlashExpression) left).getLhsExpression();
Expression leftRight = ((SlashExpression) left).getRhsExpression();
if (leftLeft instanceof RootExpression && leftRight instanceof AxisExpression) {
if (((AxisExpression) leftRight).getAxis() == AxisInfo.DESCENDANT_OR_SELF
&& isAnyNode(((AxisExpression) leftRight).getNodeTest())) {
// ok!
left = leftLeft; // the root expression
right = new AxisExpression(AxisInfo.DESCENDANT, ((AxisExpression) right).getNodeTest());
}
}
}
return new SlashExpression(left, right);
}
private boolean isAnyNode(NodeTest nodeTest) {
return nodeTest == null || nodeTest instanceof AnyNodeTest;
}
};
/**
* Turn {@code a/(b[c])} into {@code (a/b)[c]}. This is to somewhat
* normalize the expression as Saxon parses this inconsistently.
*/
static Expression hoistFilters(Expression expression) {
return FILTER_HOISTER.visit(expression);
}
/**
* Turn {@code ((root)/descendant-or-self::node())/child::someTest}
* into {@code ((root)/descendant::someTest)}. The latter is the pattern
* detected by the rulechain analyser.
*/
static Expression reduceRoot(Expression expression) {
return ROOT_REDUCER.visit(expression);
}
/**
* Splits a venn expression with the union operator into single expressions.
*
* <p>E.g. "//A | //B | //C" will result in 3 expressions "//A", "//B", and "//C".
*
* This split will skip into any top-level lets. So, for "let $a := e1 in (e2 | e3)"
* this will return the subexpression e2 and e3. To ensure the splits are actually equivalent
* you will have to call {@link #copyTopLevelLets(Expression, Expression)} on each subexpression
* to turn them back into "let $a := e1 in e2" and "let $a := e1 in e3" respectively.
*/
static Iterable<Expression> splitUnions(Expression expr) {
SplitUnions unions = new SplitUnions();
unions.visit(expr);
if (unions.getExpressions().isEmpty()) {
return Collections.singletonList(expr);
}
return unions.getExpressions();
}
/**
* Wraps a given subexpression in all top-level lets from the original.
* If the subexpression matches the original, then nothing is done.
*
* @param subexpr The subexpression that has been manipulated.
* @param original The original expression from which it was obtained by calling {@link #splitUnions(Expression)}.
* @return The subexpression, wrapped in a copy of all top-level let expression from the original.
*/
static Expression copyTopLevelLets(Expression subexpr, Expression original) {
if (!(original instanceof LetExpression)) {
return subexpr;
}
// Does it need them? Or is it already the same variable under the same assignment?
if (subexpr instanceof LetExpression) {
final LetExpression letSubexpr = (LetExpression) subexpr;
final LetExpression letOriginal = (LetExpression) original;
if (letOriginal.getVariableQName().equals(letSubexpr.getVariableQName())
&& letSubexpr.getSequence().toString().equals(letOriginal.getSequence().toString())) {
return subexpr;
}
}
final SaxonExprVisitor topLevelLetCopier = new SaxonExprVisitor() {
@Override
public Expression visit(LetExpression e) {
// keep copying
if (e.getAction() instanceof LetExpression) {
return super.visit(e);
}
// Manually craft the inner-most LetExpression
Expression sequence = visit(e.getSequence());
LetExpression result = new LetExpression();
result.setAction(subexpr);
result.setSequence(sequence);
result.setVariableQName(e.getVariableQName());
result.setRequiredType(e.getRequiredType());
result.setSlotNumber(e.getLocalSlotNumber());
return result;
}
};
if (original instanceof LetExpression) {
return topLevelLetCopier.visit(original);
}
return subexpr;
}
}
| 6,381 | 38.153374 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/AstDocumentNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import org.apache.commons.lang3.mutable.MutableInt;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.tree.iter.AxisIterator;
import net.sf.saxon.tree.iter.EmptyIterator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.type.Type;
/**
* See {@link AstTreeInfo#getRootNode()}.
*/
class AstDocumentNode extends BaseNodeInfo implements AstNodeOwner {
private final AstElementNode rootElement;
private final List<AstElementNode> children;
AstDocumentNode(AstTreeInfo document,
MutableInt idGenerator,
RootNode wrappedNode,
Configuration configuration) {
super(Type.DOCUMENT, configuration.getNamePool(), "", null);
this.rootElement = new AstElementNode(document, idGenerator, this, wrappedNode, configuration);
this.children = Collections.singletonList(rootElement);
}
@Override
List<AstElementNode> getChildren() {
return children;
}
public AstElementNode getRootElement() {
return rootElement;
}
@Override
protected AxisIterator iterateAttributes(Predicate<? super NodeInfo> nodeTest) {
return EmptyIterator.ofNodes();
}
@Override
protected AxisIterator iterateChildren(Predicate<? super NodeInfo> nodeTest) {
return filter(nodeTest, iterateList(children));
}
@Override
protected AxisIterator iterateSiblings(Predicate<? super NodeInfo> nodeTest, boolean forwards) {
return EmptyIterator.ofNodes();
}
@Override
public int getSiblingPosition() {
return 0;
}
@Override
public Node getUnderlyingNode() {
// this is a concession to the model, so that the expression "/"
// may be interpreted as the root node
return rootElement.getUnderlyingNode();
}
@Override
public int compareOrder(NodeInfo other) {
return other == this ? 0 : -1; // NOPMD CompareObjectsWithEquals - only a single root per tree
}
@Override
public boolean hasChildNodes() {
return true;
}
@Override
public String getLocalPart() {
return "";
}
@Override
public void generateId(FastStringBuffer buffer) {
buffer.append("0");
}
@Override
public CharSequence getStringValueCS() {
return "";
}
}
| 2,705 | 25.792079 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/AstTreeInfo.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.mutable.MutableInt;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.GenericTreeInfo;
/**
* A wrapper around the root node of an AST, implementing {@link net.sf.saxon.om.TreeInfo}.
*/
public final class AstTreeInfo extends GenericTreeInfo {
private DeprecatedAttrLogger logger;
private final Map<Node, AstElementNode> wrapperCache = new LinkedHashMap<Node, AstElementNode>() {
@Override
protected boolean removeEldestEntry(Entry eldest) {
/*
hit ratio depending on cache size:
512: 61%
1024: 75%
2048: 82%
unbounded: 85%
*/
return size() > 1024;
}
};
/**
* Builds an AstDocument, with the given node as the root.
*
* @param node The root AST Node.
* @param configuration Configuration of the run
*
* @see AstElementNode
*/
public AstTreeInfo(RootNode node, Configuration configuration) {
super(configuration);
MutableInt idGenerator = new MutableInt(1); // 0 is taken by the document node
setRootNode(new AstDocumentNode(this, idGenerator, node, configuration));
}
public AstElementNode findWrapperFor(Node node) {
AstElementNode element = wrapperCache.get(node);
if (element == null) {
element = findWrapperImpl(node);
wrapperCache.put(node, element);
assert element.getUnderlyingNode() == node : "Incorrect wrapper " + element + " for " + node;
}
return element;
}
// for the RootNode, this returns the document node
private AstElementNode findWrapperImpl(Node node) {
// find the closest cached ancestor
AstElementNode cur = getRootNode().getRootElement();
List<Node> ancestors = new ArrayList<>();
for (Node ancestor : node.ancestorsOrSelf()) {
AstElementNode wrappedAncestor = wrapperCache.get(ancestor);
ancestors.add(ancestor);
if (wrappedAncestor != null) {
cur = wrappedAncestor;
break;
}
}
// then go down the tree from that ancestor
// note we skip the first, who is the topmost ancestor
for (int i = ancestors.size() - 2; i >= 0; i--) {
Node ancestor = ancestors.get(i);
int idx = ancestor.getIndexInParent();
if (idx >= cur.getChildren().size()) {
throw new IllegalArgumentException("Node is not part of this tree " + node);
}
cur = cur.getChildren().get(idx);
wrapperCache.put(ancestor, cur);
}
if (cur.getUnderlyingNode() != node) {
// may happen with the root
throw new IllegalArgumentException("Node is not part of this tree " + node);
}
return cur;
}
/**
* Returns the document node of the tree. Note that this has a single
* child of element type. Both the document and this element child have
* the {@link RootNode} as {@link AstElementNode#getUnderlyingNode()}.
*/
@Override
public AstDocumentNode getRootNode() {
return (AstDocumentNode) super.getRootNode();
}
public void setAttrCtx(DeprecatedAttrLogger attrCtx) {
this.logger = attrCtx;
}
public DeprecatedAttrLogger getLogger() {
return logger == null ? DeprecatedAttrLogger.noop() : logger;
}
}
| 3,859 | 31.436975 | 105 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/PmdDocumentSorter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Comparator;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Sorts nodes by document order.
*/
// renamed because it conflicts with a Saxon node
final class PmdDocumentSorter implements Comparator<Node> {
public static final PmdDocumentSorter INSTANCE = new PmdDocumentSorter();
private PmdDocumentSorter() {
}
@Override
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public int compare(Node node1, Node node2) {
if (node1 == node2) {
return 0;
} else if (node1 == null) {
return -1;
} else if (node2 == null) {
return 1;
}
return node1.compareLocation(node2);
}
}
| 841 | 21.157895 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/AstNodeOwner.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Marker interface.
*/
public interface AstNodeOwner {
Node getUnderlyingNode();
}
| 280 | 16.5625 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.Objects;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.rule.xpath.impl.AbstractXPathFunctionDef;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;
/**
* A function that returns the current file name.
*
* @author Clément Fournier
*/
public final class FileNameXPathFunction extends AbstractXPathFunctionDef {
public static final FileNameXPathFunction INSTANCE = new FileNameXPathFunction();
private FileNameXPathFunction() {
super("fileName");
}
@Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[0];
}
@Override
public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
return SequenceType.STRING_SEQUENCE;
}
@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
Node node = XPathElementToNodeHelper.itemToNode(context.getContextItem());
if (node == null) {
throw new XPathException(
"Cannot call function '" + getFunctionQName().getLocalPart()
+ "' with context item " + context.getContextItem()
);
}
RootNode root = node.getRoot();
Objects.requireNonNull(root, "No root node in tree?");
String fileName = root.getTextDocument().getFileId().getFileName();
Objects.requireNonNull(fileName, "File name was not set");
return new StringValue(fileName);
}
};
}
}
| 2,128 | 30.776119 | 100 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/AstElementNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import org.apache.commons.lang3.mutable.MutableInt;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.pattern.NameTest;
import net.sf.saxon.tree.iter.AxisIterator;
import net.sf.saxon.tree.iter.EmptyIterator;
import net.sf.saxon.tree.iter.LookaheadIterator;
import net.sf.saxon.tree.iter.SingleNodeIterator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.tree.util.Navigator;
import net.sf.saxon.tree.wrapper.SiblingCountingNode;
import net.sf.saxon.type.Type;
/**
* A wrapper for Saxon around a Node. Note: the {@link RootNode} of a tree
* corresponds to both a document node and an element node that is its child.
*/
public final class AstElementNode extends BaseNodeInfo implements SiblingCountingNode, AstNodeOwner {
private final Node wrappedNode;
/** The index of the node in the tree according to document order */
private final int id;
private final List<AstElementNode> children;
private @Nullable Map<String, AstAttributeNode> attributes;
private @Nullable Map<String, Attribute> lightAttributes;
AstElementNode(AstTreeInfo document,
MutableInt idGenerator,
BaseNodeInfo parent,
Node wrappedNode,
Configuration configuration) {
super(determineType(wrappedNode), configuration.getNamePool(), wrappedNode.getXPathNodeName(), parent);
this.treeInfo = document;
this.wrappedNode = wrappedNode;
this.id = idGenerator.getAndIncrement();
this.children = new ArrayList<>(wrappedNode.getNumChildren());
for (int i = 0; i < wrappedNode.getNumChildren(); i++) {
children.add(new AstElementNode(document, idGenerator, this, wrappedNode.getChild(i), configuration));
}
}
private static int determineType(Node node) {
// As of PMD 6.48.0, only the experimental HTML module uses this naming
// convention to identify non-element nodes.
// TODO PMD 7: maybe generalize this to other languages
String name = node.getXPathNodeName();
if ("#text".equals(name)) {
return Type.TEXT;
} else if ("#comment".equals(name)) {
return Type.COMMENT;
}
return Type.ELEMENT;
}
public Map<String, AstAttributeNode> makeAttributes(Node wrappedNode) {
Map<String, AstAttributeNode> atts = new HashMap<>();
Iterator<Attribute> it = wrappedNode.getXPathAttributesIterator();
int attrIdx = 0;
while (it.hasNext()) {
Attribute next = it.next();
atts.put(next.getName(), new AstAttributeNode(this, next, attrIdx++));
}
return atts;
}
public Map<String, AstAttributeNode> getAttributes() {
if (attributes == null) {
attributes = makeAttributes(getUnderlyingNode());
}
return attributes;
}
public Map<String, Attribute> getLightAttributes() {
if (lightAttributes == null) {
lightAttributes = new HashMap<>();
getUnderlyingNode().getXPathAttributesIterator()
.forEachRemaining(it -> lightAttributes.put(it.getName(), it));
}
return lightAttributes;
}
@Override
public boolean hasChildNodes() {
return !children.isEmpty();
}
@Override
List<AstElementNode> getChildren() {
return children;
}
@Override
public Node getUnderlyingNode() {
return wrappedNode;
}
@Override
public int getColumnNumber() {
return wrappedNode.getBeginColumn();
}
@Override
public int getSiblingPosition() {
BaseNodeInfo parent = getParent();
return !(parent instanceof AstElementNode) ? 0
: id - ((AstElementNode) parent).id;
}
@Override
public int compareOrder(NodeInfo other) {
if (other instanceof AstElementNode) {
return Integer.compare(this.id, ((AstElementNode) other).id);
} else if (other instanceof SiblingCountingNode) {
return Navigator.compareOrder(this, (SiblingCountingNode) other);
}
throw new UnsupportedOperationException();
}
@Override
protected AxisIterator iterateAttributes(Predicate<? super NodeInfo> predicate) {
if (predicate instanceof NameTest) {
String local = ((NameTest) predicate).getLocalPart();
return SingleNodeIterator.makeIterator(getAttributes().get(local));
}
return filter(predicate, new IteratorAdapter(getAttributes().values().iterator()));
}
@Override
protected AxisIterator iterateChildren(Predicate<? super NodeInfo> nodeTest) {
return filter(nodeTest, iterateList(children));
}
@Override // this excludes self
protected AxisIterator iterateSiblings(Predicate<? super NodeInfo> nodeTest, boolean forwards) {
if (parent == null) {
return EmptyIterator.ofNodes();
}
List<? extends NodeInfo> siblingsList =
forwards ? CollectionUtil.drop(parent.getChildren(), wrappedNode.getIndexInParent() + 1)
: CollectionUtil.take(parent.getChildren(), wrappedNode.getIndexInParent());
return filter(nodeTest, iterateList(siblingsList, forwards));
}
@Override
public String getAttributeValue(String uri, String local) {
Attribute attribute = getLightAttributes().get(local);
if (attribute != null) {
getTreeInfo().getLogger().recordUsageOf(attribute);
return attribute.getStringValue();
}
return null;
}
@Override
public int getLineNumber() {
return wrappedNode.getBeginLine();
}
@Override
public NodeInfo getRoot() {
return getTreeInfo().getRootNode();
}
@Override
public void generateId(FastStringBuffer buffer) {
buffer.append(Integer.toString(id));
}
@Override
public String getLocalPart() {
return wrappedNode.getXPathNodeName();
}
@Override
public CharSequence getStringValueCS() {
if (getNodeKind() == Type.TEXT || getNodeKind() == Type.COMMENT) {
return getUnderlyingNode().getImage();
}
// https://www.w3.org/TR/xpath-datamodel-31/#ElementNode
// The string-value property of an Element Node must be the
// concatenation of the string-values of all its Text Node
// descendants in document order or, if the element has no such
// descendants, the zero-length string.
// Since we represent all our Nodes as elements, there are no
// text nodes
// TODO: for some languages like html we have text nodes
return "";
}
@Override
public String toString() {
return "Wrapper[" + getLocalPart() + "]@" + hashCode();
}
private static class IteratorAdapter implements AxisIterator, LookaheadIterator {
@SuppressWarnings("PMD.LooseCoupling") // getProperties() below has to return EnumSet
private static final EnumSet<Property> PROPERTIES = EnumSet.of(Property.LOOKAHEAD);
private final Iterator<? extends NodeInfo> it;
IteratorAdapter(Iterator<? extends NodeInfo> it) {
this.it = it;
}
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public NodeInfo next() {
return it.hasNext() ? it.next() : null;
}
@Override
public void close() {
// nothing to do
}
@Override
public EnumSet<Property> getProperties() {
return PROPERTIES;
}
}
}
| 8,378 | 30.382022 | 114 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/CoordinateXPathFunction.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.function.ToIntFunction;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.impl.AbstractXPathFunctionDef;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.pattern.NodeKindTest;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.type.Type;
import net.sf.saxon.value.Int64Value;
import net.sf.saxon.value.SequenceType;
/**
* A function that returns the current file name.
*
* @author Clément Fournier
*/
public final class CoordinateXPathFunction extends AbstractXPathFunctionDef {
public static final CoordinateXPathFunction START_LINE =
new CoordinateXPathFunction("startLine", Node::getBeginLine);
public static final CoordinateXPathFunction END_LINE =
new CoordinateXPathFunction("endLine", Node::getEndLine);
public static final CoordinateXPathFunction START_COLUMN =
new CoordinateXPathFunction("startColumn", Node::getBeginColumn);
public static final CoordinateXPathFunction END_COLUMN =
new CoordinateXPathFunction("endColumn", Node::getEndColumn);
private static final SequenceType[] A_SINGLE_ELEMENT = {
NodeKindTest.makeNodeKindTest(Type.ELEMENT).one(),
};
public static final String PMD_NODE_USER_DATA = "pmd.node";
private final ToIntFunction<Node> getter;
private CoordinateXPathFunction(String localName, ToIntFunction<Node> getter) {
super(localName);
this.getter = getter;
}
@Override
public SequenceType[] getArgumentTypes() {
return A_SINGLE_ELEMENT;
}
@Override
public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
return SequenceType.SINGLE_INTEGER;
}
@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
Node node = XPathElementToNodeHelper.itemToNode(arguments[0]);
if (node == null) {
throw new XPathException(
"Cannot call function '" + getFunctionQName().getLocalPart()
+ "' on argument " + arguments[0]
);
}
return Int64Value.makeIntegerValue(getter.applyAsInt(node));
}
};
}
}
| 2,637 | 32.820513 | 100 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/DeprecatedAttrLogger.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
/**
* Records usages of deprecated attributes in XPath rules. This needs
* to be threadsafe, XPath rules have one each (and share it).
*/
public abstract class DeprecatedAttrLogger {
private static final Logger LOG = LoggerFactory.getLogger(Attribute.class);
public abstract void recordUsageOf(Attribute attribute);
/**
* Create a new context for the given rule, returns a noop implementation
* if the warnings would be ignored anyway.
*/
public static DeprecatedAttrLogger create(XPathRule rule) {
return doCreate(rule, false);
}
public static DeprecatedAttrLogger createForSuppression(Rule rule) {
return doCreate(rule, true);
}
private static DeprecatedAttrLogger doCreate(Rule rule, boolean isSuppressionQuery) {
if (LOG.isWarnEnabled()) {
return new AttrLoggerImpl(rule, isSuppressionQuery);
} else {
return noop();
}
}
public static DeprecatedAttrLogger createAdHocLogger() {
if (LOG.isWarnEnabled()) {
return new AdhocLoggerImpl();
} else {
return noop();
}
}
public static Noop noop() {
return Noop.INSTANCE;
}
private static String getLoggableAttributeName(Attribute attr) {
return attr.getParent().getXPathNodeName() + "/@" + attr.getName();
}
private static final class Noop extends DeprecatedAttrLogger {
static final Noop INSTANCE = new Noop();
@Override
public void recordUsageOf(Attribute attribute) {
// do nothing
}
}
private static final class AttrLoggerImpl extends DeprecatedAttrLogger {
private final ConcurrentMap<String, Boolean> deprecated = new ConcurrentHashMap<>();
private final Rule rule;
private final boolean isSuppressionQuery;
private AttrLoggerImpl(Rule rule, boolean isSuppressionQuery) {
this.rule = rule;
this.isSuppressionQuery = isSuppressionQuery;
}
@Override
public void recordUsageOf(Attribute attribute) {
String replacement = attribute.replacementIfDeprecated();
if (replacement != null) {
String name = getLoggableAttributeName(attribute);
Boolean b = deprecated.putIfAbsent(name, Boolean.TRUE);
if (b == null) {
// this message needs to be kept in sync with PMDCoverageTest / BinaryDistributionIT
String user = isSuppressionQuery ? "violationSuppressXPath for rule " + ruleToString()
: "XPath rule " + ruleToString();
String msg = "Use of deprecated attribute '" + name + "' by " + user;
if (!replacement.isEmpty()) {
msg += ", please use " + replacement + " instead";
}
LOG.warn(msg);
}
}
}
public String ruleToString() {
// we can't compute that beforehand because the name is set
// outside of the rule constructor
String name = "'" + rule.getName() + "'";
if (rule.getRuleSetName() != null) {
name += " (in ruleset '" + rule.getRuleSetName() + "')";
}
return name;
}
}
private static final class AdhocLoggerImpl extends DeprecatedAttrLogger {
@Override
public void recordUsageOf(Attribute attribute) {
String replacement = attribute.replacementIfDeprecated();
if (replacement != null) {
String name = getLoggableAttributeName(attribute);
// this message needs to be kept in sync with PMDCoverageTest / BinaryDistributionIT
String msg = "Use of deprecated attribute '" + name + "' in a findChildNodesWithXPath navigation";
if (!replacement.isEmpty()) {
msg += ", please use " + replacement + " instead";
}
// log with exception stack trace to help figure out where exactly the xpath is used.
LOG.warn(msg, new RuntimeException(msg));
}
}
}
}
| 4,693 | 34.293233 | 114 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/CommonPropertyDescriptors.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import net.sourceforge.pmd.properties.PropertyBuilder.GenericPropertyBuilder;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* Just to share names/ other stuff.
*
* @author Clément Fournier
*/
public final class CommonPropertyDescriptors {
private CommonPropertyDescriptors() {
}
/**
* The "minimum" property that previously was on StatisticalRule.
*/
public static GenericPropertyBuilder<Integer> reportLevelProperty() {
return PropertyFactory.intProperty("minimum");
}
}
| 669 | 22.103448 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/TopoOrder.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents a partial order on a type {@code <K>}. This is used to
* generate the internal data structure of {@link LatticeRelation}s.
*/
interface TopoOrder<K> {
/**
* Partial order on classes. The direct successors of a class are
* its direct supertypes.
*/
TopoOrder<Class<?>> TYPE_HIERARCHY_ORDERING = node -> {
if (node == Object.class || node.isPrimitive()) {
// Object
return Collections.emptyList();
}
List<Class<?>> succs = new ArrayList<>();
Class<?> superclass = node.getSuperclass();
if (superclass != null) {
succs.add(superclass);
}
Collections.addAll(succs, node.getInterfaces());
if (node.isInterface() && node.getInterfaces().length == 0) {
succs.add(Object.class);
}
return succs;
};
/**
* Returns the strict direct successors of the given value.
* Successive invocation of this method must at some point
* terminate, also each invocation must yield the same result
* for the same argument.
*/
Iterable<K> directSuccessors(K key);
}
| 1,376 | 24.5 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.lang3.exception.ExceptionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.internal.SystemProps;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.StringUtil;
/** Applies a set of rules to a set of ASTs. */
public class RuleApplicator {
private static final Logger LOG = LoggerFactory.getLogger(RuleApplicator.class);
// we reuse the type lattice from run to run, eventually it converges
// towards the final topology (all node types have been encountered)
// This has excellent performance! Indexing time is insignificant
// compared to rule application for any non-trivial ruleset. Even
// when you use a single rule, indexing time is insignificant compared
// to eg type resolution.
private final TreeIndex idx;
private LanguageVersion currentLangVer;
public RuleApplicator(TreeIndex index) {
this.idx = index;
}
public void index(RootNode root) {
idx.reset();
indexTree(root, idx);
currentLangVer = root.getLanguageVersion();
}
public void apply(Collection<? extends Rule> rules, FileAnalysisListener listener) {
applyOnIndex(idx, rules, listener);
}
private void applyOnIndex(TreeIndex idx, Collection<? extends Rule> rules, FileAnalysisListener listener) {
for (Rule rule : rules) {
if (!RuleSet.applies(rule, currentLangVer)) {
continue; // No point in even trying to apply the rule
}
RuleContext ctx = RuleContext.create(listener, rule);
rule.start(ctx);
try (TimedOperation rcto = TimeTracker.startOperation(TimedOperationCategory.RULE, rule.getName())) {
int nodeCounter = 0;
Iterator<? extends Node> targets = rule.getTargetSelector().getVisitedNodes(idx);
while (targets.hasNext()) {
Node node = targets.next();
try {
nodeCounter++;
rule.apply(node, ctx);
} catch (RuntimeException e) {
reportOrRethrow(listener, rule, node, AssertionUtil.contexted(e), true);
} catch (StackOverflowError e) {
reportOrRethrow(listener, rule, node, AssertionUtil.contexted(e), SystemProps.isErrorRecoveryMode());
} catch (AssertionError e) {
reportOrRethrow(listener, rule, node, AssertionUtil.contexted(e), SystemProps.isErrorRecoveryMode());
}
}
rcto.close(nodeCounter);
} finally {
rule.end(ctx);
}
}
}
private <E extends Throwable> void reportOrRethrow(FileAnalysisListener listener, Rule rule, Node node, E e, boolean reportAndDontThrow) throws E {
if (e instanceof ExceptionContext) {
((ExceptionContext) e).addContextValue("Rule applied on node", node);
}
if (reportAndDontThrow) {
reportException(listener, rule, node, e);
} else {
throw e;
}
}
private void reportException(FileAnalysisListener listener, Rule rule, Node node, Throwable e) {
// The listener handles logging if needed,
// it may also rethrow the error.
listener.onError(new ProcessingError(e, node.getTextDocument().getFileId()));
// fixme - maybe duplicated logging
LOG.warn("Exception applying rule {} on file {}, continuing with next rule", rule.getName(), node.getTextDocument().getFileId().getAbsolutePath(), e);
String nodeToString = StringUtil.elide(node.toString(), 600, " ... (truncated)");
LOG.warn("Exception occurred on node {}", nodeToString);
}
private void indexTree(Node top, TreeIndex idx) {
idx.indexNode(top);
for (Node child : top.children()) {
indexTree(child, idx);
}
}
public static RuleApplicator build(Iterable<? extends Rule> rules) {
TargetSelectorInternal.ApplicatorBuilder builder = new TargetSelectorInternal.ApplicatorBuilder();
for (Rule it : rules) {
it.getTargetSelector().prepare(builder);
}
return builder.build();
}
}
| 5,090 | 36.992537 | 158 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/TargetSelectorInternal.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
/**
* Internal API of {@link RuleTargetSelector}.
*/
public abstract class TargetSelectorInternal {
protected TargetSelectorInternal() {
// inheritance only
}
protected abstract void prepare(ApplicatorBuilder builder);
protected abstract Iterator<? extends Node> getVisitedNodes(TreeIndex index);
protected static final class ApplicatorBuilder {
private final Set<String> namesToIndex = new HashSet<>();
private final Set<Class<? extends Node>> classesToIndex = new HashSet<>();
ApplicatorBuilder() {
// package-private
}
public void registerXPathNames(Set<String> names) {
namesToIndex.addAll(names);
}
public void registerClasses(Set<Class<? extends Node>> names) {
classesToIndex.addAll(names);
}
RuleApplicator build() {
return new RuleApplicator(new TreeIndex(namesToIndex, classesToIndex));
}
}
}
| 1,289 | 24.294118 | 83 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/TreeIndex.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.util.IteratorUtil;
/**
* Index of an AST, for use by the {@link RuleApplicator}.
*/
public class TreeIndex {
private final LatticeRelation<Class<?>, Node, Iterable<Node>> byClass;
private final Set<String> interestingNames;
private final Map<String, List<Node>> byName;
public TreeIndex(Set<String> namesToIndex,
Set<Class<? extends Node>> classesToIndex) {
byClass = new LatticeRelation<>(
TopoOrder.TYPE_HIERARCHY_ORDERING,
classesToIndex,
Class::getSimpleName,
Collectors.toSet()
);
this.interestingNames = namesToIndex;
byName = new HashMap<>();
}
void indexNode(Node n) {
if (interestingNames.contains(n.getXPathNodeName())) {
byName.computeIfAbsent(n.getXPathNodeName(), k -> new ArrayList<>()).add(n);
}
byClass.put(n.getClass(), n);
}
void reset() {
byClass.clearValues();
byName.clear();
}
Iterator<Node> getByName(String n) {
return byName.getOrDefault(n, Collections.emptyList()).iterator();
}
Iterator<Node> getByClass(Class<? extends Node> n) {
return byClass.get(n).iterator();
}
public Iterator<Node> getByName(Collection<String> n) {
return IteratorUtil.flatMap(n.iterator(), this::getByName);
}
public Iterator<Node> getByClass(Collection<? extends Class<? extends Node>> n) {
return IteratorUtil.flatMap(n.iterator(), this::getByClass);
}
}
| 1,976 | 26.458333 | 88 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/LatticeRelation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import static java.util.stream.Collectors.toSet;
import static net.sourceforge.pmd.util.CollectionUtil.any;
import static net.sourceforge.pmd.util.CollectionUtil.finish;
import static net.sourceforge.pmd.util.CollectionUtil.map;
import static net.sourceforge.pmd.util.CollectionUtil.toMutableList;
import static net.sourceforge.pmd.util.GraphUtil.DotColor;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.util.AssertionUtil;
import net.sourceforge.pmd.util.GraphUtil;
/**
* Indexes data of type {@code <V>} with keys of type {@code <K>}, where
* a partial order exists between the keys. Values are accumulated into
* a type {@code <C>} (can be an arbitrary collection). The value associated
* to a key is the recursive union of the values of all its *predecessors*
* according to the partial order.
*
* <p>For example if your type of keys is {@link Class}, and you use
* subtyping as a partial order, then the value associated to a class C
* will be the union of the individual values added for C, and those
* added for all its subtypes.
*
* <p>The internal structure only allows <i>some</i> keys to be queried
* among all keys encountered. This optimises the structure, because we
* don't accumulate values nobody cares about. This is configured by
* a predicate given to the constructor.
*
* @param <K> Type of keys, must have a corresponding {@link TopoOrder},
* must be suitable for use as a map key (immutable, consistent
* equals/hashcode)
* @param <V> Type of elements indexed by K
* @param <C> Type of collection the values are accumulated in (configurable with an arbitrary collector)
*/
class LatticeRelation<K, @NonNull V, C> {
private final Predicate<? super K> queryKeySelector;
private final TopoOrder<K> keyOrder;
private final Function<? super K, String> keyToString;
private final Collector<? super V, ?, ? extends C> collector;
private final C emptyValue; // empty value of the collector
private final Map<K, LNode> nodes = new HashMap<>();
/**
* Creates a new relation with the given configuration.
*
* @param keyOrder Partial order generating the lattice
* @param queryKeySelector Filter determining which keys can be queried
* through {@link #get(Object)}
* @param keyToString Strategy to render keys when dumping the lattice to a graph
* @param collector Collector used to accumulate values
*
* @param <A> Internal accumulator type of the collector
*/
<A> LatticeRelation(TopoOrder<K> keyOrder,
Predicate<? super K> queryKeySelector,
Function<? super K, String> keyToString,
Collector<? super V, A, ? extends C> collector) {
this.keyOrder = keyOrder;
this.queryKeySelector = queryKeySelector;
this.keyToString = keyToString;
this.collector = collector;
this.emptyValue = finish(collector, collector.supplier().get());
}
/**
* Works like the other constructor, the filter being containment
* in the given query set. This means, only keys that are in this
* set may be queried.
*
* @throws IllegalArgumentException If the query set contains a null key
* @throws IllegalStateException If the topo order generates a cycle
*/
<A> LatticeRelation(TopoOrder<K> keyOrder,
Set<? extends K> querySet,
Function<? super K, String> keyToString,
Collector<? super V, A, ? extends C> collector) {
this.keyOrder = keyOrder;
this.queryKeySelector = querySet::contains;
this.keyToString = keyToString;
this.collector = collector;
this.emptyValue = finish(collector, collector.supplier().get());
for (K k : querySet) {
if (k == null) {
throw new IllegalArgumentException("Query set " + querySet + " contains a null key");
}
putDontCheckParams(k, null);
}
}
/**
* Adds the val to the node corresponding to the [key], and all its
* successors, creating them if needed. If the key matches the filter,
* a QueryNode is created.
*
* @param preds Predecessors to which the given key must be linked
* @param k Key to add
* @param val Proper value to add to the given key (if null, nothing
* is to be added, we just create the topology)
*/
private void addSucc(@Nullable Deque<LNode> preds, final K k, final @Nullable V val) {
if (any(preds, n -> n.key.equals(k))) {
throw cycleError(preds, k);
}
LNode n = nodes.get(k);
if (n != null) {
link(preds, n, val);
return;
}
n = queryKeySelector.test(k) ? new QueryNode<>(k) : new LNode(k);
nodes.put(k, n);
link(preds, n, val);
if (preds == null) {
preds = new ArrayDeque<>();
}
preds.addLast(n);
for (K next : keyOrder.directSuccessors(k)) {
addSucc(preds, next, val);
}
if (preds.removeLast() != n) { // NOPMD CompareObjectsWithEquals
throw new IllegalStateException("Unbalanced stack push/pop");
}
}
private void link(@Nullable Iterable<LNode> preds, LNode n, @Nullable V val) {
if (preds != null) {
n.addAsSuccessorTo(preds);
}
n.addValueTransitive(val);
}
@NonNull
private IllegalStateException cycleError(@NonNull Deque<LNode> preds, K k) {
List<String> toStrings = map(toMutableList(), preds, n -> keyToString.apply(n.key));
toStrings.add(keyToString.apply(k));
return new IllegalStateException("Cycle in graph: " + String.join(" -> ", toStrings));
}
// test only
/** Returns the keys of all transitive successors. */
Set<K> transitiveQuerySuccs(K key) {
LNode lNode = nodes.get(key);
if (lNode == null) {
return Collections.emptySet();
} else {
return map(toSet(), lNode.transitiveSuccs, n -> n.key);
}
}
/**
* Adds one value to the given key. This value will be joined to the
* values of all keys inferior to it when calling {@link #get(Object)}.
*
* @throws IllegalStateException If the order has a cycle
* @throws NullPointerException If either of the parameters is null
*/
public void put(@NonNull K key, @NonNull V value) {
AssertionUtil.requireParamNotNull("key", key);
AssertionUtil.requireParamNotNull("value", value);
putDontCheckParams(key, value);
}
private void putDontCheckParams(@NonNull K key, @Nullable V value) {
addSucc(null, key, value);
}
/**
* Returns the computed value for the given key, or the default value
* of the collector.
* <p>Only keys matching the filter given when constructing the lattice
* can be queried, if that is not the case, then this will return
* the default value even if some values were {@link #put(Object, Object)}
* for it.
*
* @throws NullPointerException If the key is null
*/
@NonNull
public C get(@NonNull K key) {
AssertionUtil.requireParamNotNull("key", key);
LNode n = nodes.get(key);
return n == null ? emptyValue : n.computeValue();
}
public void clearValues() {
for (LNode n : nodes.values()) {
n.resetValue();
}
}
@Override
public String toString() {
// generates a DOT representation of the lattice
// Visualize eg at http://webgraphviz.com/
return GraphUtil.toDot(
nodes.values(),
n -> n.transitiveSuccs,
n -> n.getClass() == QueryNode.class ? DotColor.GREEN : DotColor.BLACK,
n -> keyToString.apply(n.key)
);
}
/**
* A lattice node. The default behaviour is to ignore values, only
* the subclass {@link QueryNode} accumulates them.
*/
private class LNode {
protected final @NonNull K key;
/**
* These are all the transitive strict successors, not just the direct
* ones. Each time a value is added to this node, it is added to
* all these successors too.
*/
final Set<QueryNode<?>> transitiveSuccs = new LinkedHashSet<>();
LNode(@NonNull K key) {
this.key = key;
}
/** Add a value to this node and all its transitive successors. */
void addValueTransitive(@Nullable V v) {
if (v == null) {
return;
}
this.addValue(v);
transitiveSuccs.forEach(s -> s.addValue(v));
}
void addAsSuccessorTo(Iterable<LNode> preds) {
// just link succs to preds, eliding this jump
for (QueryNode<?> it : transitiveSuccs) {
it.addAsSuccessorTo(preds);
}
}
void addValue(@NonNull V v) {
// do nothing, leaf nodes do not store values,
// they just forward to their transitive QNode successors
}
@NonNull C computeValue() {
return emptyValue;
}
void resetValue() {
// do nothing
}
@Override
public String toString() {
return "node(" + key + ')';
}
}
/**
* A node that may be queried with {@link #get(Object)}.
*
* @param <A> Internal accumulator type of the collector, this is
* the second type argument of the collector of the lattice,
* it doesn't matter outside of this class
*/
private final class QueryNode<A> extends LNode {
private A accumulator;
private C finished;
QueryNode(@NonNull K key) {
super(key);
resetValue();
}
@Override
void addAsSuccessorTo(Iterable<LNode> preds) {
preds.forEach(n -> {
if (n.transitiveSuccs.add(this)) {
// otherwise the transitive successors are also already here
n.transitiveSuccs.addAll(this.transitiveSuccs);
}
});
}
@Override
void addValue(@NonNull V v) {
collector().accumulator().accept(accumulator, v);
}
@Override
@NonNull C computeValue() {
if (finished == null) {
this.finished = finish(collector(), accumulator);
}
return this.finished;
}
@Override
void resetValue() {
accumulator = collector().supplier().get();
finished = null;
}
@Override
public String toString() {
return "qnode(" + key + ')';
}
@SuppressWarnings("unchecked")
private Collector<? super V, A, ? extends C> collector() {
return (Collector<? super V, A, ? extends C>) collector;
}
}
}
| 11,727 | 33.392962 | 105 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/NameOccurrence.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
/**
* A {@link NameOccurrence} represents one usage of a name declaration.
*
*/
public interface NameOccurrence {
/**
* Gets the location where the usage occurred.
*
* @return the node
*/
ScopedNode getLocation();
/**
* Gets the image of the used declaration, such as the variable name.
*
* @return the image
*/
String getImage();
}
| 529 | 19.384615 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Applier.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import java.util.Iterator;
import java.util.function.Predicate;
public final class Applier {
private Applier() {
// utility class
}
public static <E> void apply(Predicate<E> f, Iterator<? extends E> i) {
while (i.hasNext() && f.test(i.next())) {
// Nothing to do
}
}
}
| 460 | 19.954545 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ScopedNode.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import net.sourceforge.pmd.lang.ast.Node;
/**
* A {@link Node} which knows about the scope within it has been declared.
*/
public interface ScopedNode extends Node {
Scope getScope();
}
| 330 | 19.6875 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/AbstractScope.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Base class for any {@link Scope}. Provides useful default implementations.
*/
public abstract class AbstractScope implements Scope {
private Scope parent;
/** Stores the name declaration already sorted by class. */
private Map<Class<? extends NameDeclaration>, Map<NameDeclaration, List<NameOccurrence>>> nameDeclarations = new LinkedHashMap<>();
@Override
public Scope getParent() {
return parent;
}
@Override
public void setParent(Scope parent) {
this.parent = parent;
}
@Override
public Map<NameDeclaration, List<NameOccurrence>> getDeclarations() {
Map<NameDeclaration, List<NameOccurrence>> result = new LinkedHashMap<>();
for (Map<NameDeclaration, List<NameOccurrence>> e : nameDeclarations.values()) {
result.putAll(e);
}
return result;
}
@Override
public <T extends NameDeclaration> Map<T, List<NameOccurrence>> getDeclarations(Class<T> clazz) {
@SuppressWarnings("unchecked")
Map<T, List<NameOccurrence>> result = (Map<T, List<NameOccurrence>>) nameDeclarations.get(clazz);
if (result == null) {
result = Collections.emptyMap();
}
return result;
}
@Override
public boolean contains(NameOccurrence occ) {
for (NameDeclaration d : getDeclarations().keySet()) {
if (d.getImage().equals(occ.getImage())) {
return true;
}
}
return false;
}
@Override
public void addDeclaration(NameDeclaration declaration) {
Map<NameDeclaration, List<NameOccurrence>> declarationsPerClass = nameDeclarations.get(declaration.getClass());
if (declarationsPerClass == null) {
declarationsPerClass = new LinkedHashMap<>();
nameDeclarations.put(declaration.getClass(), declarationsPerClass);
}
declarationsPerClass.put(declaration, new ArrayList<>());
}
@SuppressWarnings("unchecked")
@Override
public <T extends Scope> T getEnclosingScope(Class<T> clazz) {
Scope current = this;
while (current != null) {
if (clazz.isAssignableFrom(current.getClass())) {
return (T) current;
}
current = current.getParent();
}
return null;
}
@Override
public Set<NameDeclaration> addNameOccurrence(NameOccurrence occurrence) {
Set<NameDeclaration> result = new HashSet<>();
for (Map.Entry<NameDeclaration, List<NameOccurrence>> e : getDeclarations().entrySet()) {
if (e.getKey().getImage().equals(occurrence.getImage())) {
result.add(e.getKey());
e.getValue().add(occurrence);
}
}
return result;
}
}
| 3,119 | 30.836735 | 135 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/ImageFinderFunction.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
public class ImageFinderFunction implements Predicate<NameDeclaration> {
private final Set<String> images;
private NameDeclaration decl;
public ImageFinderFunction(String img) {
images = Collections.singleton(img);
}
public ImageFinderFunction(List<String> imageList) {
images = new HashSet<>(imageList);
}
@Override
public boolean test(NameDeclaration nameDeclaration) {
if (images.contains(nameDeclaration.getImage())) {
decl = nameDeclaration;
return false;
}
return true;
}
public NameDeclaration getDecl() {
return this.decl;
}
}
| 931 | 22.897436 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/AbstractNameDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
/**
* Base class for all name declarations.
*/
public abstract class AbstractNameDeclaration implements NameDeclaration {
protected ScopedNode node;
public AbstractNameDeclaration(ScopedNode node) {
this.node = node;
}
@Override
public ScopedNode getNode() {
return node;
}
@Override
public String getImage() {
return node.getImage();
}
@Override
public Scope getScope() {
return node.getScope();
}
@Override
public String getName() {
return getImage();
}
}
| 702 | 17.5 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/Scope.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A scope is a region within variables and other declarations are visible.
* Scopes can be nested and form a tree. This is expressed through "parent
* scopes". Each scope manages its own declarations.
*
* @see AbstractScope AbstractScope as a base class
* @see <a href=
* "http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3">Java
* Language Specification, 6.3: Scope of a Declaration</a>
*/
public interface Scope {
/**
* Retrieves this scope's parent
*/
Scope getParent();
/**
* Points this scope to its parent
*/
void setParent(Scope parent);
/**
* Helper method that goes up the parent scopes to find a scope of the
* specified type
*
* @param clazz
* the type of the Scope to search for
* @return the found scope of the specified type or <code>null</code> if no
* such scope was found.
*/
<T extends Scope> T getEnclosingScope(Class<T> clazz);
/**
* Gets all the declaration with the occurrences in this scope.
*
* @return map of declarations with occurrences.
*/
Map<NameDeclaration, List<NameOccurrence>> getDeclarations();
/**
* Helper method to get only a specific type of name declarations. The
* return map elemens have already been casted to the correct type. This
* method usually returns a subset of {@link #getDeclarations()}.
*
* @param clazz
* the type of name declarations to use
* @return map of declarations with occurrences.
*/
<T extends NameDeclaration> Map<T, List<NameOccurrence>> getDeclarations(Class<T> clazz);
/**
* Tests whether or not a {@link NameOccurrence} is directly contained in
* the scope. This means, whether the given {@link NameOccurrence}
* references a declaration, that has been declared within this scope. Note
* that this search is just for this scope - it doesn't go diving into any
* parent scopes.
*/
boolean contains(NameOccurrence occ);
/**
* Adds a new declaration to this scope. Only after the declaration has been
* added, {@link #contains(NameOccurrence)} and
* {@link #addNameOccurrence(NameOccurrence)} can be used correctly.
*
* @param declaration
* the declaration to add
*/
void addDeclaration(NameDeclaration declaration);
/**
* Adds a {@link NameOccurrence} to this scope - only call this after
* getting a true back from {@link #contains(NameOccurrence)}.
*
* @return the {@link NameDeclaration}s that are referenced by the given
* {@link NameOccurrence}, if the {@link NameOccurrence} could be
* added. Otherwise an empty set is returned.
*/
Set<NameDeclaration> addNameOccurrence(NameOccurrence occurrence);
}
| 3,067 | 33.088889 | 93 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/symboltable/NameDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
/**
* This is a declaration of a name, e.g. a variable or method name. See
* {@link AbstractNameDeclaration} for a base class.
*/
public interface NameDeclaration {
/**
* Gets the node which manifests the declaration.
*
* @return the node
*/
ScopedNode getNode();
/**
* Gets the image of the node. This is usually the name of the declaration
* such as the variable name.
*
* @return the image
* @see #getName()
*/
String getImage();
/**
* Gets the scope in which this name has been declared.
*
* @return the scope
*/
Scope getScope();
/**
* Gets the name of the declaration, such as the variable name.
*
* @return
*/
String getName();
}
| 902 | 20 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/SimpleLanguageModuleBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.LanguageModuleBase;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
/**
* The simplest implementation of a language, where only a {@link LanguageVersionHandler}
* needs to be implemented.
*
* @author Clément Fournier
* @since 7.0.0
*/
public class SimpleLanguageModuleBase extends LanguageModuleBase {
private final Function<LanguagePropertyBundle, LanguageVersionHandler> handler;
protected SimpleLanguageModuleBase(LanguageMetadata metadata, LanguageVersionHandler handler) {
this(metadata, p -> handler);
}
public SimpleLanguageModuleBase(LanguageMetadata metadata, Function<LanguagePropertyBundle, LanguageVersionHandler> makeHandler) {
super(metadata);
this.handler = makeHandler;
}
@Override
public LanguageProcessor createProcessor(LanguagePropertyBundle bundle) {
LanguageVersionHandler services = handler.apply(bundle);
return new BatchLanguageProcessor<LanguagePropertyBundle>(bundle) {
@Override
public @NonNull LanguageVersionHandler services() {
return services;
}
};
}
}
| 1,501 | 30.291667 | 134 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/AbstractPMDProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import net.sourceforge.pmd.lang.LanguageProcessor.AnalysisTask;
import net.sourceforge.pmd.lang.document.TextFile;
/**
* This is internal API!
*
* @author Romain Pelisse <belaran@gmail.com>
*/
abstract class AbstractPMDProcessor implements AutoCloseable {
protected final AnalysisTask task;
AbstractPMDProcessor(AnalysisTask task) {
this.task = task;
}
/**
* Analyse all files. Each text file is closed.
*/
public abstract void processFiles();
/**
* Joins tasks and await completion of the analysis. After this, all
* {@link TextFile}s must have been closed.
*/
@Override
public abstract void close();
/**
* Returns a new file processor. The strategy used for threading is
* determined by {@link AnalysisTask#getThreadCount()}.
* <p>Note: Only {@code 0} threads disables multi-thread processing. See the CLI documentation
* for parameter {@code --threads}.</p>
*/
public static AbstractPMDProcessor newFileProcessor(AnalysisTask analysisTask) {
return analysisTask.getThreadCount() > 0
? new MultiThreadProcessor(analysisTask)
: new MonoThreadProcessor(analysisTask);
}
}
| 1,357 | 27.291667 | 98 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdThreadFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
class PmdThreadFactory implements ThreadFactory {
private final AtomicInteger counter = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "PmdThread " + counter.incrementAndGet());
}
}
| 474 | 22.75 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/MonoThreadProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.lang.LanguageProcessor.AnalysisTask;
import net.sourceforge.pmd.lang.document.TextFile;
/**
* @author Romain Pelisse <belaran@gmail.com>
*/
final class MonoThreadProcessor extends AbstractPMDProcessor {
MonoThreadProcessor(AnalysisTask task) {
super(task);
}
@Override
@SuppressWarnings("PMD.CloseResource") // closed by the PMDRunnable
public void processFiles() {
for (TextFile file : task.getFiles()) {
new MonothreadRunnable(file, task).run();
}
}
@Override
public void close() {
// nothing to do
}
static final class MonothreadRunnable extends PmdRunnable {
private final RuleSets ruleSets;
MonothreadRunnable(TextFile textFile, AnalysisTask task) {
super(textFile, task);
this.ruleSets = task.getRulesets();
}
@Override
protected RuleSets getRulesets() {
return ruleSets;
}
}
}
| 1,165 | 22.795918 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/MultiThreadProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.lang.LanguageProcessor.AnalysisTask;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* @author Romain Pelisse <belaran@gmail.com>
*/
final class MultiThreadProcessor extends AbstractPMDProcessor {
private final ExecutorService executor;
MultiThreadProcessor(final AnalysisTask task) {
super(task);
executor = Executors.newFixedThreadPool(task.getThreadCount(), new PmdThreadFactory());
}
@Override
@SuppressWarnings("PMD.CloseResource") // closed by the PMDRunnable
public void processFiles() {
// The thread-local is not static, but analysis-global
// This means we don't have to reset it manually, every analysis is isolated.
// The initial value makes a copy of the rulesets
final ThreadLocal<RuleSets> ruleSetCopy = ThreadLocal.withInitial(() -> {
RuleSets copy = new RuleSets(task.getRulesets());
// use a noop reporter because the copy should only contain rules that
// initialized properly
copy.initializeRules(task.getLpRegistry(), MessageReporter.quiet());
return copy;
});
for (final TextFile textFile : task.getFiles()) {
executor.submit(new PmdRunnable(textFile, task) {
@Override
protected RuleSets getRulesets() {
return ruleSetCopy.get();
}
});
}
}
@Override
public void close() {
try {
executor.shutdown();
while (!executor.awaitTermination(10, TimeUnit.HOURS)) {
// still waiting
Thread.yield();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
executor.shutdownNow();
}
}
}
| 2,207 | 31 | 95 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/BatchLanguageProcessor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.TextFile;
/**
* A base class for language processors. It processes all files of the
* corresponding language as a single batch. It can operate in parallel
* or sequentially depending on the number of threads passed in the
* {@link AnalysisTask}.
*
* @author Clément Fournier
* @since 7.0.0
*/
public abstract class BatchLanguageProcessor<P extends LanguagePropertyBundle> implements LanguageProcessor {
private final Language language;
private final P bundle;
private final LanguageVersion version;
protected BatchLanguageProcessor(P bundle) {
this.language = bundle.getLanguage();
this.bundle = bundle;
this.version = bundle.getLanguageVersion();
}
public P getProperties() {
return bundle;
}
@Override
public @NonNull LanguageVersion getLanguageVersion() {
return version;
}
@Override
public final @NonNull Language getLanguage() {
return language;
}
@Override
public @NonNull AutoCloseable launchAnalysis(@NonNull AnalysisTask task) {
// The given analysis task has all files to analyse, not only the ones for this language.
List<TextFile> files = new ArrayList<>(task.getFiles());
files.removeIf(it -> !it.getLanguageVersion().getLanguage().equals(getLanguage()));
AnalysisTask newTask = task.withFiles(files);
task.getRulesets().initializeRules(task.getLpRegistry(), task.getMessageReporter());
// launch processing.
AbstractPMDProcessor processor = AbstractPMDProcessor.newFileProcessor(newTask);
// If this is a multi-threaded processor, this call is non-blocking,
// the call to close on the returned instance blocks instead.
processor.processFiles();
return processor;
}
@Override
public void close() throws Exception {
// no additional resources
}
}
| 2,377 | 30.706667 | 109 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.cache.AnalysisCache;
import net.sourceforge.pmd.internal.SystemProps;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageProcessor.AnalysisTask;
import net.sourceforge.pmd.lang.LanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.FileAnalysisException;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.ast.SemanticException;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
/**
* A processing task for a single file.
*/
abstract class PmdRunnable implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(PmdRunnable.class);
private final TextFile textFile;
private final AnalysisTask task;
PmdRunnable(TextFile textFile, AnalysisTask task) {
this.textFile = textFile;
this.task = task;
}
/**
* This is only called within the run method (when we are on the actual carrier thread).
* That way an implementation that uses a ThreadLocal will see the
* correct thread.
*/
protected abstract RuleSets getRulesets();
@Override
public void run() throws FileAnalysisException {
TimeTracker.initThread();
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.FILE_PROCESSING);
FileAnalysisListener listener = task.getListener().startFileAnalysis(textFile)) {
RuleSets ruleSets = getRulesets();
// Coarse check to see if any RuleSet applies to file, will need to do a finer RuleSet specific check later
if (ruleSets.applies(textFile)) {
AnalysisCache analysisCache = task.getAnalysisCache();
try (TextDocument textDocument = TextDocument.create(textFile);
FileAnalysisListener cacheListener = analysisCache.startFileAnalysis(textDocument)) {
@SuppressWarnings("PMD.CloseResource")
FileAnalysisListener completeListener = FileAnalysisListener.tee(listOf(listener, cacheListener));
if (analysisCache.isUpToDate(textDocument)) {
LOG.trace("Skipping file (lang: {}) because it was found in the cache: {}", textFile.getLanguageVersion(), textFile.getFileId().getAbsolutePath());
// note: no cache listener here
// vvvvvvvv
reportCachedRuleViolations(listener, textDocument);
} else {
LOG.trace("Processing file (lang: {}): {}", textFile.getLanguageVersion(), textFile.getFileId().getAbsolutePath());
try {
processSource(completeListener, textDocument, ruleSets);
} catch (Exception | StackOverflowError | AssertionError e) {
if (e instanceof Error && !SystemProps.isErrorRecoveryMode()) { // NOPMD:
throw e;
}
// The listener handles logging if needed,
// it may also rethrow the error, as a FileAnalysisException (which we let through below)
completeListener.onError(new Report.ProcessingError(e, textFile.getFileId()));
}
}
}
} else {
LOG.trace("Skipping file (lang: {}) because no rule applies: {}", textFile.getLanguageVersion(), textFile.getFileId());
}
} catch (FileAnalysisException e) {
throw e; // bubble managed exceptions, they were already reported
} catch (Exception e) {
throw FileAnalysisException.wrap(textFile.getFileId(), "An unknown exception occurred", e);
}
TimeTracker.finishThread();
}
private void reportCachedRuleViolations(final FileAnalysisListener ctx, TextDocument file) {
for (final RuleViolation rv : task.getAnalysisCache().getCachedViolations(file)) {
ctx.onRuleViolation(rv);
}
}
private RootNode parse(Parser parser, ParserTask task) {
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.PARSER)) {
return parser.parse(task);
}
}
private void processSource(FileAnalysisListener listener,
TextDocument textDocument,
RuleSets ruleSets) throws FileAnalysisException {
SemanticErrorReporter reporter = SemanticErrorReporter.reportToLogger(task.getMessageReporter());
@SuppressWarnings("PMD.CloseResource")
LanguageProcessor processor = task.getLpRegistry().getProcessor(textDocument.getLanguageVersion().getLanguage());
ParserTask parserTask = new ParserTask(textDocument,
reporter,
task.getLpRegistry());
LanguageVersionHandler handler = processor.services();
Parser parser = handler.getParser();
RootNode rootNode = parse(parser, parserTask);
SemanticException semanticError = reporter.getFirstError();
if (semanticError != null) {
// cause a processing error to be reported and rule analysis to be skipped
throw semanticError;
}
ruleSets.apply(rootNode, listener);
}
}
| 6,263 | 42.5 | 171 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* The violation caching system. This is an internal subsystem that will
* be largely hidden with 7.0.0.
*/
@InternalApi
@Deprecated
package net.sourceforge.pmd.cache;
import net.sourceforge.pmd.annotation.InternalApi;
| 314 | 21.5 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextFile;
/**
* An analysis cache backed by a regular file.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public class FileAnalysisCache extends AbstractAnalysisCache {
private final File cacheFile;
/**
* Creates a new cache backed by the given file.
* @param cache The file on which to store analysis cache
*/
public FileAnalysisCache(final File cache) {
super();
this.cacheFile = cache;
}
@Override
public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection<? extends TextFile> files) {
// load cached data before checking for validity
loadFromFile(cacheFile, files);
super.checkValidity(ruleSets, auxclassPathClassLoader, files);
}
/**
* Loads cache data from the given file.
*
* @param cacheFile The file which backs the file analysis cache.
*/
private void loadFromFile(final File cacheFile, Collection<? extends TextFile> files) {
Map<String, FileId> idMap =
files.stream().map(TextFile::getFileId)
.collect(Collectors.toMap(FileId::getUriString, id -> id));
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "load")) {
if (cacheExists()) {
try (
DataInputStream inputStream = new DataInputStream(
new BufferedInputStream(Files.newInputStream(cacheFile.toPath())));
) {
final String cacheVersion = inputStream.readUTF();
if (PMDVersion.VERSION.equals(cacheVersion)) {
// Cache seems valid, load the rest
// Get checksums
rulesetChecksum = inputStream.readLong();
auxClassPathChecksum = inputStream.readLong();
executionClassPathChecksum = inputStream.readLong();
// Cached results
while (inputStream.available() > 0) {
final String filePathId = inputStream.readUTF();
FileId fileId = idMap.get(filePathId);
if (fileId == null) {
LOG.debug("File {} is in the cache but is not part of the analysis",
filePathId);
fileId = FileId.fromURI(filePathId);
}
final long checksum = inputStream.readLong();
final int countViolations = inputStream.readInt();
final List<RuleViolation> violations = new ArrayList<>(countViolations);
for (int i = 0; i < countViolations; i++) {
violations.add(CachedRuleViolation.loadFromStream(inputStream, fileId, ruleMapper));
}
fileResultsCache.put(fileId, new AnalysisResult(checksum, violations));
}
LOG.debug("Analysis cache loaded from {}", cacheFile);
} else {
LOG.debug("Analysis cache invalidated, PMD version changed.");
}
} catch (final EOFException e) {
LOG.warn("Cache file {} is malformed, will not be used for current analysis", cacheFile.getPath());
} catch (final IOException e) {
LOG.error("Could not load analysis cache from file: {}", e.getMessage());
}
} else if (cacheFile.isDirectory()) {
LOG.error("The configured cache location must be the path to a file, but is a directory.");
}
}
}
@Override
public void persist() {
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "persist")) {
if (cacheFile.isDirectory()) {
LOG.error("Cannot persist the cache, the given path points to a directory.");
return;
}
boolean cacheFileShouldBeCreated = !cacheFile.exists();
// Create directories missing along the way
if (cacheFileShouldBeCreated) {
final File parentFile = cacheFile.getAbsoluteFile().getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
}
try (
DataOutputStream outputStream = new DataOutputStream(
new BufferedOutputStream(Files.newOutputStream(cacheFile.toPath())))
) {
outputStream.writeUTF(pmdVersion);
outputStream.writeLong(rulesetChecksum);
outputStream.writeLong(auxClassPathChecksum);
outputStream.writeLong(executionClassPathChecksum);
for (final Map.Entry<FileId, AnalysisResult> resultEntry : updatedResultsCache.entrySet()) {
final List<RuleViolation> violations = resultEntry.getValue().getViolations();
outputStream.writeUTF(resultEntry.getKey().getUriString()); // the path id
outputStream.writeLong(resultEntry.getValue().getFileChecksum());
outputStream.writeInt(violations.size());
for (final RuleViolation rv : violations) {
CachedRuleViolation.storeToStream(outputStream, rv);
}
}
if (cacheFileShouldBeCreated) {
LOG.debug("Analysis cache created");
} else {
LOG.debug("Analysis cache updated");
}
} catch (final IOException e) {
LOG.error("Could not persist analysis cache to file: {}", e.getMessage());
}
}
}
@Override
protected boolean cacheExists() {
return cacheFile.exists() && cacheFile.isFile() && cacheFile.length() > 0;
}
}
| 7,144 | 40.063218 | 125 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/ChecksumAware.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* Interface defining an object that has a checksum The checksum is a
* fingerprint of the object's configuration, and *MUST* change if anything
* changed on the object. It differs from a {@code hashCode()} in that a
* {@code hashCode()} may not take all fields into account, but a checksum must
* do so.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public interface ChecksumAware {
/**
* Retrieves the current instance checksum
*
* @return The current checksum
*/
long getChecksum();
}
| 750 | 25.821429 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.benchmark.TimedOperation;
import net.sourceforge.pmd.benchmark.TimedOperationCategory;
import net.sourceforge.pmd.cache.internal.ClasspathFingerprinter;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
/**
* Abstract implementation of the analysis cache. Handles all operations, except for persistence.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public abstract class AbstractAnalysisCache implements AnalysisCache {
protected static final Logger LOG = LoggerFactory.getLogger(AbstractAnalysisCache.class);
protected static final ClasspathFingerprinter FINGERPRINTER = new ClasspathFingerprinter();
protected final String pmdVersion;
protected final ConcurrentMap<FileId, AnalysisResult> fileResultsCache = new ConcurrentHashMap<>();
protected final ConcurrentMap<FileId, AnalysisResult> updatedResultsCache = new ConcurrentHashMap<>();
protected final CachedRuleMapper ruleMapper = new CachedRuleMapper();
protected long rulesetChecksum;
protected long auxClassPathChecksum;
protected long executionClassPathChecksum;
/**
* Creates a new empty cache
*/
public AbstractAnalysisCache() {
pmdVersion = PMDVersion.VERSION;
}
@Override
public boolean isUpToDate(final TextDocument document) {
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "up-to-date check")) {
final AnalysisResult cachedResult = fileResultsCache.get(document.getFileId());
final AnalysisResult updatedResult;
// is this a known file? has it changed?
final boolean upToDate = cachedResult != null
&& cachedResult.getFileChecksum() == document.getCheckSum();
if (upToDate) {
LOG.trace("Incremental Analysis cache HIT");
// copy results over
updatedResult = cachedResult;
} else {
LOG.trace("Incremental Analysis cache MISS - {}",
cachedResult != null ? "file changed" : "no previous result found");
// New file being analyzed, create new empty entry
updatedResult = new AnalysisResult(document.getCheckSum(), new ArrayList<>());
}
updatedResultsCache.put(document.getFileId(), updatedResult);
return upToDate;
}
}
@Override
public List<RuleViolation> getCachedViolations(final TextDocument sourceFile) {
final AnalysisResult analysisResult = fileResultsCache.get(sourceFile.getFileId());
if (analysisResult == null) {
// new file, avoid nulls
return Collections.emptyList();
}
return analysisResult.getViolations();
}
@Override
public void analysisFailed(final TextDocument sourceFile) {
updatedResultsCache.remove(sourceFile.getFileId());
}
/**
* Returns true if the cache exists. If so, normal cache validity checks
* will be performed. Otherwise, the cache is necessarily invalid (e.g. on a first run).
*/
protected abstract boolean cacheExists();
@Override
public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection<? extends TextFile> files) {
try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "validity check")) {
boolean cacheIsValid = cacheExists();
if (cacheIsValid && ruleSets.getChecksum() != rulesetChecksum) {
LOG.debug("Analysis cache invalidated, rulesets changed.");
cacheIsValid = false;
}
final long currentAuxClassPathChecksum;
if (auxclassPathClassLoader instanceof URLClassLoader) {
// we don't want to close our aux classpath loader - we still need it...
@SuppressWarnings("PMD.CloseResource") final URLClassLoader urlClassLoader = (URLClassLoader) auxclassPathClassLoader;
currentAuxClassPathChecksum = FINGERPRINTER.fingerprint(urlClassLoader.getURLs());
if (cacheIsValid && currentAuxClassPathChecksum != auxClassPathChecksum) {
// TODO some rules don't need that (in fact, some languages)
LOG.debug("Analysis cache invalidated, auxclasspath changed.");
cacheIsValid = false;
}
} else {
currentAuxClassPathChecksum = 0;
}
final long currentExecutionClassPathChecksum = FINGERPRINTER.fingerprint(getClassPathEntries());
if (cacheIsValid && currentExecutionClassPathChecksum != executionClassPathChecksum) {
LOG.debug("Analysis cache invalidated, execution classpath changed.");
cacheIsValid = false;
}
if (!cacheIsValid) {
// Clear the cache
fileResultsCache.clear();
}
// Update the local checksums
rulesetChecksum = ruleSets.getChecksum();
auxClassPathChecksum = currentAuxClassPathChecksum;
executionClassPathChecksum = currentExecutionClassPathChecksum;
ruleMapper.initialize(ruleSets);
}
}
private static boolean isClassPathWildcard(String entry) {
return entry.endsWith("/*") || entry.endsWith("\\*");
}
private URL[] getClassPathEntries() {
final String classpath = System.getProperty("java.class.path");
final String[] classpathEntries = classpath.split(File.pathSeparator);
final List<URL> entries = new ArrayList<>();
final SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
if (!attrs.isSymbolicLink()) { // Broken link that can't be followed
entries.add(file.toUri().toURL());
}
return FileVisitResult.CONTINUE;
}
};
final SimpleFileVisitor<Path> jarFileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
String extension = IOUtil.getFilenameExtension(file.toString());
if ("jar".equalsIgnoreCase(extension)) {
fileVisitor.visitFile(file, attrs);
}
return FileVisitResult.CONTINUE;
}
};
try {
for (final String entry : classpathEntries) {
final File f = new File(entry);
if (isClassPathWildcard(entry)) {
Files.walkFileTree(new File(entry.substring(0, entry.length() - 1)).toPath(),
EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, jarFileVisitor);
} else if (f.isFile()) {
entries.add(f.toURI().toURL());
} else if (f.exists()) { // ignore non-existing directories
Files.walkFileTree(f.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
fileVisitor);
}
}
} catch (final IOException e) {
LOG.error("Incremental analysis can't check execution classpath contents", e);
throw new RuntimeException(e);
}
return entries.toArray(new URL[0]);
}
@Override
public FileAnalysisListener startFileAnalysis(TextDocument file) {
final FileId fileName = file.getFileId();
return new FileAnalysisListener() {
@Override
public void onRuleViolation(RuleViolation violation) {
updatedResultsCache.get(fileName).addViolation(violation);
}
@Override
public void onError(ProcessingError error) {
analysisFailed(file);
}
};
}
}
| 9,530 | 39.385593 | 134 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.util.StringUtil;
/**
* A {@link RuleViolation} implementation that is immutable, and therefore cache friendly
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public final class CachedRuleViolation implements RuleViolation {
private final CachedRuleMapper mapper;
private final String description;
private final String ruleClassName;
private final String ruleName;
private final String ruleTargetLanguage;
private final Map<String, String> additionalInfo;
private final FileLocation location;
private CachedRuleViolation(final CachedRuleMapper mapper, final String description,
final FileId fileFileId, final String ruleClassName, final String ruleName,
final String ruleTargetLanguage, final int beginLine, final int beginColumn,
final int endLine, final int endColumn,
final Map<String, String> additionalInfo) {
this.mapper = mapper;
this.description = description;
this.location = FileLocation.range(fileFileId, TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn));
this.ruleClassName = ruleClassName;
this.ruleName = ruleName;
this.ruleTargetLanguage = ruleTargetLanguage;
this.additionalInfo = additionalInfo;
}
@Override
public Rule getRule() {
// The mapper may be initialized after cache is loaded, so use it lazily
return mapper.getRuleForClass(ruleClassName, ruleName, ruleTargetLanguage);
}
@Override
public String getDescription() {
return description;
}
@Override
public FileLocation getLocation() {
return location;
}
@Override
public Map<String, String> getAdditionalInfo() {
return additionalInfo;
}
/**
* Helper method to load a {@link CachedRuleViolation} from an input stream.
*
* @param stream The stream from which to load the violation.
* @param fileFileId The name of the file on which this rule was reported.
* @param mapper The mapper to be used to obtain rule instances from the active rulesets.
*
* @return The loaded rule violation.
*/
/* package */
static CachedRuleViolation loadFromStream(
DataInputStream stream,
FileId fileFileId, CachedRuleMapper mapper) throws IOException {
String description = stream.readUTF();
String ruleClassName = stream.readUTF();
String ruleName = stream.readUTF();
String ruleTargetLanguage = stream.readUTF();
int beginLine = stream.readInt();
int beginColumn = stream.readInt();
int endLine = stream.readInt();
int endColumn = stream.readInt();
Map<String, String> additionalInfo = readAdditionalInfo(stream);
return new CachedRuleViolation(mapper, description, fileFileId, ruleClassName, ruleName, ruleTargetLanguage,
beginLine, beginColumn, endLine, endColumn, additionalInfo);
}
private static @NonNull Map<String, String> readAdditionalInfo(DataInputStream stream) throws IOException {
int numAdditionalInfoKeyValuePairs = stream.readInt();
if (numAdditionalInfoKeyValuePairs == 0) {
return Collections.emptyMap();
}
Map<String, String> additionalInfo = new LinkedHashMap<>();
while (numAdditionalInfoKeyValuePairs-- > 0) {
final String key = stream.readUTF();
final String value = stream.readUTF();
additionalInfo.put(key, value);
}
return Collections.unmodifiableMap(additionalInfo);
}
/**
* Helper method to store a {@link RuleViolation} in an output stream to be later
* retrieved as a {@link CachedRuleViolation}
*
* @param stream The stream on which to store the violation.
* @param violation The rule violation to cache.
*/
/* package */ static void storeToStream(final DataOutputStream stream,
final RuleViolation violation) throws IOException {
stream.writeUTF(StringUtil.nullToEmpty(violation.getDescription()));
stream.writeUTF(StringUtil.nullToEmpty(violation.getRule().getRuleClass()));
stream.writeUTF(StringUtil.nullToEmpty(violation.getRule().getName()));
stream.writeUTF(StringUtil.nullToEmpty(violation.getRule().getLanguage().getTerseName()));
FileLocation location = violation.getLocation();
stream.writeInt(location.getStartPos().getLine());
stream.writeInt(location.getStartPos().getColumn());
stream.writeInt(location.getEndPos().getLine());
stream.writeInt(location.getEndPos().getColumn());
Map<String, String> additionalInfo = violation.getAdditionalInfo();
stream.writeInt(additionalInfo.size());
for (Entry<String, String> entry : additionalInfo.entrySet()) {
stream.writeUTF(entry.getKey());
stream.writeUTF(StringUtil.nullToEmpty(entry.getValue()));
}
}
}
| 5,839 | 38.194631 | 120 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.io.IOException;
import java.util.Collection;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
/**
* Adapter to wrap {@link AnalysisCache} behaviour in a {@link GlobalAnalysisListener}.
*/
@Deprecated
@InternalApi
public class AnalysisCacheListener implements GlobalAnalysisListener {
private final AnalysisCache cache;
public AnalysisCacheListener(AnalysisCache cache, RuleSets ruleSets, ClassLoader classLoader,
Collection<? extends TextFile> textFiles) {
this.cache = cache;
cache.checkValidity(ruleSets, classLoader, textFiles);
}
@Override
public FileAnalysisListener startFileAnalysis(TextFile file) {
// AnalysisCache instances are handled specially in PmdRunnable
return FileAnalysisListener.noop();
}
@Override
public void close() throws IOException {
cache.persist();
}
}
| 1,246 | 28 | 97 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
/**
* A NOOP analysis cache. Easier / safer than null-checking.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public class NoopAnalysisCache implements AnalysisCache {
@Override
public void persist() {
// noop
}
@Override
public boolean isUpToDate(final TextDocument document) {
return false;
}
@Override
public void analysisFailed(final TextDocument sourceFile) {
// noop
}
@Override
public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection<? extends TextFile> files) {
// noop
}
@Override
public List<RuleViolation> getCachedViolations(TextDocument sourceFile) {
return Collections.emptyList();
}
@Override
public FileAnalysisListener startFileAnalysis(TextDocument filename) {
return FileAnalysisListener.noop();
}
}
| 1,437 | 23.793103 | 125 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleMapper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* A mapper from rule class names to rule instances for cached rules.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public class CachedRuleMapper {
private final Map<String, Rule> cachedRulesInstances = new HashMap<>();
/**
* Finds a rule instance for the given rule class name, name and target language
* @param className The name of the rule class that generated the cache entry
* @param ruleName The name of the rule that generated the cache entry
* @param languageName The terse name of the language for which the rule applies
* @return The requested rule
*/
public Rule getRuleForClass(final String className, final String ruleName, final String languageName) {
return cachedRulesInstances.get(getRuleKey(className, ruleName, languageName));
}
/**
* Initialize the mapper with the given rulesets.
* @param rs The rulesets from which to retrieve rules.
*/
public void initialize(final RuleSets rs) {
for (final Rule r : rs.getAllRules()) {
cachedRulesInstances.put(getRuleKey(r.getRuleClass(), r.getName(), r.getLanguage().getTerseName()), r);
}
}
private String getRuleKey(final String className, final String ruleName, final String languageName) {
return className + "$$" + ruleName + "$$" + languageName;
}
}
| 1,694 | 32.9 | 115 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import net.sourceforge.pmd.RuleSets;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
/**
* An analysis cache for incremental analysis.
* Simultaneously manages the old version of the cache,
* and the new, most up-to-date violation cache.
*
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public interface AnalysisCache {
/**
* Persists the updated analysis results on whatever medium is used by the cache.
*/
void persist() throws IOException;
/**
* Checks if a given file is up to date in the cache and can be skipped from analysis.
* Regardless of the return value of this method, each call adds the parameter to the
* updated cache, which allows {@link FileAnalysisListener#onRuleViolation(RuleViolation)}
* to add a rule violation to the file. TODO is this really best behaviour? This side-effects seems counter-intuitive.
*
* @param document The file to check in the cache
* @return True if the cache is a hit, false otherwise
*/
boolean isUpToDate(TextDocument document);
/**
* Retrieves cached violations for the given file. Make sure to call {@link #isUpToDate(TextDocument)} first.
* @param sourceFile The file to check in the cache
* @return The list of cached violations.
*/
List<RuleViolation> getCachedViolations(TextDocument sourceFile);
/**
* Notifies the cache that analysis of the given file has failed and should not be cached.
* @param sourceFile The file whose analysis failed
*/
void analysisFailed(TextDocument sourceFile);
/**
* Checks if the cache is valid for the configured rulesets and class loader.
* If the provided rulesets and classpath don't match those of the cache, the
* cache is invalidated. This needs to be called before analysis, as it
* conditions the good behaviour of {@link #isUpToDate(TextDocument)}.
*
* @param ruleSets The rulesets configured for this analysis.
* @param auxclassPathClassLoader The class loader for auxclasspath configured for this analysis.
* @param files Set of files in the current analysis. File
* records in the cache are matched to the file
* IDs of these files.
*/
void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection<? extends TextFile> files);
/**
* Returns a listener that will be used like in {@link GlobalAnalysisListener#startFileAnalysis(TextFile)}.
* This should record violations, and call {@link #analysisFailed(TextDocument)}
* upon error.
*/
FileAnalysisListener startFileAnalysis(TextDocument file);
}
| 3,254 | 39.185185 | 122 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisResult.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* The result of a single file analysis.
* Includes a checksum of the file and the complete list of violations detected.
* @deprecated This is internal API, will be hidden with 7.0.0
*/
@Deprecated
@InternalApi
public class AnalysisResult {
private final long fileChecksum;
private final List<RuleViolation> violations;
public AnalysisResult(final long fileChecksum, final List<RuleViolation> violations) {
this.fileChecksum = fileChecksum;
this.violations = violations;
}
public AnalysisResult(final long fileChecksum) {
this(fileChecksum, new ArrayList<>());
}
public long getFileChecksum() {
return fileChecksum;
}
public List<RuleViolation> getViolations() {
return violations;
}
public void addViolations(final List<RuleViolation> violations) {
this.violations.addAll(violations);
}
public void addViolation(final RuleViolation ruleViolation) {
this.violations.add(ruleViolation);
}
}
| 1,287 | 24.76 | 90 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/NoopFingerprinter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.IOException;
import java.net.URL;
import java.util.zip.Checksum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Catch-all {@link ClasspathEntryFingerprinter} that ignores all files.
*/
public class NoopFingerprinter implements ClasspathEntryFingerprinter {
private static final Logger LOG = LoggerFactory.getLogger(NoopFingerprinter.class);
@Override
public boolean appliesTo(String fileExtension) {
return true;
}
@Override
public void fingerprint(URL entry, Checksum checksum) throws IOException {
// noop
LOG.debug("Ignoring classpath entry {}", entry);
}
}
| 784 | 24.322581 | 87 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/ClasspathFingerprinter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.Adler32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClasspathFingerprinter {
private static final Logger LOG = LoggerFactory.getLogger(ClasspathFingerprinter.class);
// TODO : With Java 9 we could use List.of()…
private static final List<ClasspathEntryFingerprinter> FINGERPRINTERS = Collections.unmodifiableList(Arrays.asList(
new ZipFileFingerprinter(),
new RawFileFingerprinter(),
new NoopFingerprinter() // catch-all fingerprinter, MUST be last
));
public long fingerprint(final URL... classpathEntry) {
final Adler32 adler32 = new Adler32();
try {
for (final URL url : classpathEntry) {
final String extension = getExtension(url);
for (ClasspathEntryFingerprinter f : FINGERPRINTERS) {
if (f.appliesTo(extension)) {
f.fingerprint(url, adler32);
break;
}
}
}
} catch (final IOException e) {
// Can this even happen?
LOG.error("Incremental analysis can't fingerprint classpath contents", e);
throw new RuntimeException(e);
}
return adler32.getValue();
}
private String getExtension(final URL url) {
final String file = url.getFile();
final int lastDot = file.lastIndexOf('.');
if (lastDot == -1) {
return "";
}
return file.substring(lastDot + 1);
}
}
| 1,833 | 29.065574 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/ClasspathEntryFingerprinter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.IOException;
import java.net.URL;
import java.util.zip.Checksum;
/**
* A strategy to fingerprint a given classpath entry.
*/
public interface ClasspathEntryFingerprinter {
/**
* Checks if the fingerprinter applies to a particular file extension
*
* @param fileExtension The extension of the classpath entry to check
* @return True if this fingerprinter applies, false otherwise
*/
boolean appliesTo(String fileExtension);
/**
* Adds the given entry fingerprint to the current checksum.
*
* @param entry The entry to be fingerprinted
* @param checksum The {@link Checksum} in which to accumulate fingerprints
* @throws IOException
*/
void fingerprint(URL entry, Checksum checksum) throws IOException;
}
| 933 | 27.30303 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/RawFileFingerprinter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.internal.util.IOUtil;
/**
* Base fingerprinter for raw files.
*/
public class RawFileFingerprinter implements ClasspathEntryFingerprinter {
private static final Logger LOG = LoggerFactory.getLogger(RawFileFingerprinter.class);
private static final Set<String> SUPPORTED_EXTENSIONS;
static {
final Set<String> extensions = new HashSet<>();
extensions.add("class"); // Java class files
SUPPORTED_EXTENSIONS = Collections.unmodifiableSet(extensions);
}
@Override
public boolean appliesTo(String fileExtension) {
return SUPPORTED_EXTENSIONS.contains(fileExtension);
}
@Override
public void fingerprint(URL entry, Checksum checksum) throws IOException {
try (CheckedInputStream inputStream = new CheckedInputStream(entry.openStream(), checksum)) {
// Just read it, the CheckedInputStream will update the checksum on it's own
while (IOUtil.skipFully(inputStream, Long.MAX_VALUE) == Long.MAX_VALUE) {
// just loop
}
} catch (final FileNotFoundException ignored) {
LOG.warn("Classpath entry {} doesn't exist, ignoring it", entry);
}
}
}
| 1,667 | 29.888889 | 101 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cache/internal/ZipFileFingerprinter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cache.internal;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.Checksum;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Specialized fingerprinter for Zip files.
*/
public class ZipFileFingerprinter implements ClasspathEntryFingerprinter {
private static final Logger LOG = LoggerFactory.getLogger(ZipFileFingerprinter.class);
private static final Set<String> SUPPORTED_EXTENSIONS;
private static final Set<String> SUPPORTED_ENTRY_EXTENSIONS;
private static final Comparator<ZipEntry> FILE_NAME_COMPARATOR = new Comparator<ZipEntry>() {
@Override
public int compare(ZipEntry o1, ZipEntry o2) {
return o1.getName().compareTo(o2.getName());
}
};
static {
final Set<String> extensions = new HashSet<>();
extensions.add("jar");
extensions.add("zip");
SUPPORTED_EXTENSIONS = Collections.unmodifiableSet(extensions);
final Set<String> entryExtensions = new HashSet<>();
entryExtensions.add("class");
SUPPORTED_ENTRY_EXTENSIONS = Collections.unmodifiableSet(entryExtensions);
}
@Override
public boolean appliesTo(String fileExtension) {
return SUPPORTED_EXTENSIONS.contains(fileExtension);
}
@Override
public void fingerprint(URL entry, Checksum checksum) throws IOException {
try (ZipFile zip = new ZipFile(new File(entry.toURI()))) {
final List<ZipEntry> meaningfulEntries = getMeaningfulEntries(zip);
/*
* Make sure the order of entries in the zip do not matter.
* Duplicates are technically possible, but shouldn't exist in classpath entries
*/
Collections.sort(meaningfulEntries, FILE_NAME_COMPARATOR);
final ByteBuffer buffer = ByteBuffer.allocate(4); // Size of an int
for (final ZipEntry zipEntry : meaningfulEntries) {
/*
* The CRC actually uses 4 bytes, but as it's unsigned Java uses a long…
* the cast changes the sign, but not the underlying byte values themselves
*/
buffer.putInt(0, (int) zipEntry.getCrc());
checksum.update(buffer.array(), 0, 4);
}
} catch (final FileNotFoundException | NoSuchFileException ignored) {
LOG.warn("Classpath entry {} doesn't exist, ignoring it", entry);
} catch (final URISyntaxException e) {
// Should never happen?
LOG.warn("Malformed classpath entry doesn't refer to zip in filesystem.", e);
}
}
/**
* Retrieve a filtered list of entries discarding those that do not matter for classpath computation
* @param zip The zip file whose entries to retrieve
* @return The filtered list of zip entries
*/
private List<ZipEntry> getMeaningfulEntries(ZipFile zip) {
final List<ZipEntry> meaningfulEntries = new ArrayList<>();
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
final ZipEntry zipEntry = entries.nextElement();
if (SUPPORTED_ENTRY_EXTENSIONS.contains(getFileExtension(zipEntry))) {
meaningfulEntries.add(zipEntry);
}
}
return meaningfulEntries;
}
private String getFileExtension(final ZipEntry entry) {
if (entry.isDirectory()) {
return null;
}
final String file = entry.getName();
final int lastDot = file.lastIndexOf('.');
if (lastDot == -1) {
return "";
}
return file.substring(lastDot + 1);
}
}
| 4,233 | 32.603175 | 104 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/ResourceLoader.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* @deprecated Is internal API
*/
@Deprecated
@InternalApi
public class ResourceLoader {
public static final int TIMEOUT;
static {
int timeoutProperty = 5000;
try {
timeoutProperty = Integer.parseInt(System.getProperty("net.sourceforge.pmd.http.timeout", "5000"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
TIMEOUT = timeoutProperty;
}
private final ClassLoader classLoader;
/**
* Constructor for ResourceLoader.
*/
public ResourceLoader() {
this(ResourceLoader.class.getClassLoader());
}
/**
* Constructor for ResourceLoader.
*/
public ResourceLoader(final ClassLoader cl) {
this.classLoader = Objects.requireNonNull(cl);
}
/**
* Attempts to load the resource from file, a URL or the claspath
* <p>
* Caller is responsible for closing the {@link InputStream}.
*
* @param name The resource to attempt and load
*
* @return InputStream
*/
public @NonNull InputStream loadResourceAsStream(final String name) throws IOException {
// Search file locations first
final File file = new File(name);
if (file.exists()) {
try {
return Files.newInputStream(file.toPath());
} catch (final IOException e) {
// if the file didn't exist, we wouldn't be here
// somehow the file vanished between checking for existence and opening
throw new IOException("File was checked to exist", e);
}
}
// Maybe it's a url?
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(name).openConnection();
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
InputStream is = connection.getInputStream();
if (is != null) {
return is;
}
} catch (final Exception e) {
return loadClassPathResourceAsStreamOrThrow(name);
}
throw new IOException("Can't find resource " + name + ". Make sure the resource is a valid file or URL or is on the classpath");
}
public @Nullable InputStream loadClassPathResourceAsStream(final String name) throws IOException {
/*
* Don't use getResourceAsStream to avoid reusing connections between threads
* See https://github.com/pmd/pmd/issues/234
*/
final URL resource = classLoader.getResource(name);
if (resource == null) {
// Don't throw RuleSetNotFoundException, keep API compatibility
return null;
} else {
final URLConnection connection = resource.openConnection();
// This avoids reusing the underlying file, if the resource is loaded from a Jar file.
// The file is closed with the input stream then thus not leaving a leaked resource behind.
// See https://github.com/pmd/pmd/issues/364 and https://github.com/pmd/pmd/issues/337
connection.setUseCaches(false);
return connection.getInputStream();
}
}
public @NonNull InputStream loadClassPathResourceAsStreamOrThrow(final String name) throws IOException {
InputStream is = null;
try {
is = loadClassPathResourceAsStream(name);
} catch (final IOException ignored) {
// ignored
}
if (is == null) {
throw new FileNotFoundException("Can't find resource " + name
+ ". Make sure the resource is on the classpath");
}
return is;
}
/**
* Load the rule from the classloader from resource loader, consistent with the ruleset
*/
public Rule loadRuleFromClassPath(final String clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return (Rule) classLoader.loadClass(clazz).newInstance();
}
}
| 4,611 | 32.42029 | 137 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/ContextedStackOverflowError.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import org.apache.commons.lang3.exception.DefaultExceptionContext;
import net.sourceforge.pmd.internal.util.ExceptionContextDefaultImpl;
/**
* A {@link StackOverflowError} with nice messages.
*/
public final class ContextedStackOverflowError extends StackOverflowError implements ExceptionContextDefaultImpl<ContextedStackOverflowError> {
/** The serialization version. */
private static final long serialVersionUID = 4111035582093848670L;
private final DefaultExceptionContext exceptionContext = new DefaultExceptionContext();
private ContextedStackOverflowError(StackOverflowError e) {
super(e.getMessage());
setStackTrace(e.getStackTrace()); // pretend we're a regular assertion error
}
public static ContextedStackOverflowError wrap(StackOverflowError e) {
return e instanceof ContextedStackOverflowError ? (ContextedStackOverflowError) e
: new ContextedStackOverflowError(e);
}
@Override
public String getMessage() {
return getFormattedExceptionMessage(super.getMessage());
}
@Override
public DefaultExceptionContext getExceptionContext() {
return exceptionContext;
}
@Override
public ContextedStackOverflowError getThrowable() {
return this;
}
}
| 1,454 | 30.630435 | 143 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/ConsList.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.Validate;
final class ConsList<T> extends AbstractList<T> {
private final List<? extends T> head;
private final List<? extends T> tail;
private final int size;
ConsList(List<? extends T> head, List<? extends T> tail) {
this.head = head;
this.tail = tail;
this.size = head.size() + tail.size();
}
@Override
public T get(int index) {
Validate.validIndex(this, index);
if (index < head.size()) {
return head.get(index);
}
return tail.get(index - head.size());
}
@Override
public Iterator<T> iterator() {
return IteratorUtil.concat(head.iterator(), tail.iterator());
}
@Override
public int size() {
return size;
}
}
| 995 | 21.636364 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/StringUtil.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.document.Chars;
/**
* String-related utility functions. See also {@link StringUtils}.
*
* @author BrianRemedios
* @author Clément Fournier
*/
public final class StringUtil {
private static final Pattern XML_10_INVALID_CHARS = Pattern.compile(
"\\x00|\\x01|\\x02|\\x03|\\x04|\\x05|\\x06|\\x07|\\x08|"
+ "\\x0b|\\x0c|\\x0e|\\x0f|"
+ "\\x10|\\x11|\\x12|\\x13|\\x14|\\x15|\\x16|\\x17|\\x18|"
+ "\\x19|\\x1a|\\x1b|\\x1c|\\x1d|\\x1e|\\x1f");
private StringUtil() {
}
public static String inSingleQuotes(String s) {
if (s == null) {
s = "";
}
return "'" + s + "'";
}
public static @NonNull String inDoubleQuotes(String expected) {
return "\"" + expected + "\"";
}
/**
* Returns the (1-based) line number of the character at the given index.
* Line terminators (\r, \n) are assumed to be on the line they *end*
* and not on the following line. The method also accepts that the given
* offset be the length of the string (in which case there's no targeted character),
* to get the line number of a character that would be inserted at
* the end of the string.
*
* <pre>
*
* lineNumberAt("a\nb", 0) = 1
* lineNumberAt("a\nb", 1) = 1
* lineNumberAt("a\nb", 2) = 2
* lineNumberAt("a\nb", 3) = 2 // charAt(3) doesn't exist though
* lineNumberAt("a\nb", 4) = -1
*
* lineNumberAt("", 0) = 1
* lineNumberAt("", _) = -1
*
* </pre>
*
* @param charSeq Char sequence
* @param offsetInclusive Offset in the sequence of the targeted character.
* May be the length of the sequence.
* @return -1 if the offset is not in {@code [0, length]}, otherwise
* the line number
*/
public static int lineNumberAt(CharSequence charSeq, int offsetInclusive) {
int len = charSeq.length();
if (offsetInclusive > len || offsetInclusive < 0) {
return -1;
}
int l = 1;
for (int curOffset = 0; curOffset < offsetInclusive; curOffset++) {
// if we end up outside the string, then the line is undefined
if (curOffset >= len) {
return -1;
}
char c = charSeq.charAt(curOffset);
if (c == '\n') {
l++;
} else if (c == '\r') {
if (curOffset + 1 < len && charSeq.charAt(curOffset + 1) == '\n') {
if (curOffset == offsetInclusive - 1) {
// the CR is assumed to be on the same line as the LF
return l;
}
curOffset++; // SUPPRESS CHECKSTYLE jump to after the \n
}
l++;
}
}
return l;
}
/**
* Returns the (1-based) column number of the character at the given index.
* Line terminators are by convention taken to be part of the line they end,
* and not the new line they start. Each character has width 1 (including {@code \t}).
* The method also accepts that the given offset be the length of the
* string (in which case there's no targeted character), to get the column
* number of a character that would be inserted at the end of the string.
*
* <pre>
*
* columnNumberAt("a\nb", 0) = 1
* columnNumberAt("a\nb", 1) = 2
* columnNumberAt("a\nb", 2) = 1
* columnNumberAt("a\nb", 3) = 2 // charAt(3) doesn't exist though
* columnNumberAt("a\nb", 4) = -1
*
* columnNumberAt("a\r\n", 2) = 3
*
* </pre>
*
* @param charSeq Char sequence
* @param offsetInclusive Offset in the sequence
* @return -1 if the offset is not in {@code [0, length]}, otherwise
* the column number
*/
public static int columnNumberAt(CharSequence charSeq, final int offsetInclusive) {
if (offsetInclusive == charSeq.length()) {
return charSeq.length() == 0 ? 1 : 1 + columnNumberAt(charSeq, offsetInclusive - 1);
} else if (offsetInclusive > charSeq.length() || offsetInclusive < 0) {
return -1;
}
int col = 0;
char next = 0;
for (int i = offsetInclusive; i >= 0; i--) {
char c = charSeq.charAt(i);
if (offsetInclusive != i) {
if (c == '\n' || c == '\r' && next != '\n') {
return col;
}
}
col++;
next = c;
}
return col;
}
/**
* Like {@link StringBuilder#append(CharSequence)}, but uses an optimized
* implementation if the charsequence happens to be a {@link Chars}. {@link StringBuilder}
* already optimises the cases where the charseq is a string, a StringBuilder,
* or a stringBuffer. This is especially useful in parsers.
*/
public static StringBuilder append(StringBuilder sb, CharSequence charSeq) {
if (charSeq instanceof Chars) {
((Chars) charSeq).appendChars(sb);
return sb;
} else {
return sb.append(charSeq);
}
}
/**
* Returns the substring following the last occurrence of the
* given character. If the character doesn't occur, returns
* the whole string. This contrasts with {@link StringUtils#substringAfterLast(String, String)},
* which returns the empty string in that case.
*
* @param str String to cut
* @param c Delimiter
*/
public static String substringAfterLast(String str, int c) {
int i = str.lastIndexOf(c);
return i < 0 ? str : str.substring(i + 1);
}
/**
* Formats a double to a percentage, keeping {@code numDecimal} decimal places.
*
* @param val a double value between 0 and 1
* @param numDecimals The number of decimal places to keep
*
* @return A formatted string
*
* @throws IllegalArgumentException if the double to format is not between 0 and 1
*/
public static String percentageString(double val, int numDecimals) {
if (val < 0 || val > 1) {
throw new IllegalArgumentException("Expected a number between 0 and 1");
}
return String.format(Locale.ROOT, "%." + numDecimals + "f%%", 100 * val);
}
/**
* Checks for the existence of any of the listed prefixes on the non-null
* text and removes them.
*
* @return String
*/
public static String withoutPrefixes(String text, String... prefixes) {
for (String prefix : prefixes) {
if (text.startsWith(prefix)) {
return text.substring(prefix.length());
}
}
return text;
}
/**
* Remove characters, that are not allowed in XML 1.0 documents.
*
* <p>Allowed characters are:
* <blockquote>
* Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
* // any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
* </blockquote>
* (see <a href="https://www.w3.org/TR/xml/#charsets">Extensible Markup Language (XML) 1.0 (Fifth Edition)</a>).
*/
public static String removedInvalidXml10Characters(String text) {
Matcher matcher = XML_10_INVALID_CHARS.matcher(text);
return matcher.replaceAll("");
}
/**
* Replace some whitespace characters so they are visually apparent.
*
* @return String
*/
public static String escapeWhitespace(Object o) {
if (o == null) {
return null;
}
String s = String.valueOf(o);
s = s.replace("\n", "\\n");
s = s.replace("\r", "\\r");
s = s.replace("\t", "\\t");
return s;
}
/**
* Determine the maximum number of common leading whitespace characters the
* strings share in the same sequence. Useful for determining how many
* leading characters can be removed to shift all the text in the strings to
* the left without misaligning them.
*
* <p>Note: the spec is described in
* <a href='https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html#stripIndent()'>String#stripIndent</a>
*
* <quote>
* The minimum indentation (min) is determined as follows:
* <ul>
* <li>For each non-blank line (as defined by isBlank()), the leading white space characters are counted.
* <li>The leading white space characters on the last line are also counted even if blank.
* </ul>
* The min value is the smallest of these counts.
* </quote>
*
* @throws NullPointerException If the parameter is null
*/
private static int maxCommonLeadingWhitespaceForAll(List<? extends CharSequence> lines) {
int maxCommonWs = Integer.MAX_VALUE;
for (int i = 0; i < lines.size(); i++) {
CharSequence line = lines.get(i);
// compute common prefix
if (!StringUtils.isBlank(line) || i == lines.size() - 1) {
maxCommonWs = Math.min(maxCommonWs, countLeadingWhitespace(line));
}
}
if (maxCommonWs == Integer.MAX_VALUE) {
// common prefix not found
maxCommonWs = 0;
}
return maxCommonWs;
}
/**
* Returns a list of
*/
public static List<Chars> linesWithTrimIndent(String source) {
List<String> lines = Arrays.asList(source.split("\n"));
List<Chars> result = lines.stream().map(Chars::wrap).collect(CollectionUtil.toMutableList());
trimIndentInPlace(result);
return result;
}
/**
* Trim the common indentation of each line in place in the input list.
* Trailing whitespace is removed on each line. Note that blank lines do
* not count towards computing the max common indentation, except
* the last one.
*
* @param lines mutable list
*/
public static void trimIndentInPlace(List<Chars> lines) {
int trimDepth = maxCommonLeadingWhitespaceForAll(lines);
lines.replaceAll(chars -> chars.length() >= trimDepth
? chars.subSequence(trimDepth).trimEnd()
: chars.trimEnd());
}
/**
* Trim common indentation in the lines of the string. Like
* {@link #trimIndentInPlace(List)} called with the list of lines
* and joined with {@code \n}.
*/
public static StringBuilder trimIndent(Chars string) {
List<Chars> lines = string.lineStream().collect(CollectionUtil.toMutableList());
trimIndentInPlace(lines);
return CollectionUtil.joinCharsIntoStringBuilder(lines, "\n");
}
private static int countLeadingWhitespace(CharSequence s) {
int count = 0;
while (count < s.length() && Character.isWhitespace(s.charAt(count))) {
count++;
}
return count;
}
/**
* Are the two String values the same. The Strings can be optionally trimmed
* before checking. The Strings can be optionally compared ignoring case.
* The Strings can be have embedded whitespace standardized before
* comparing. Two null values are treated as equal.
*
* @param s1 The first String.
* @param s2 The second String.
* @param trim Indicates if the Strings should be trimmed before comparison.
* @param ignoreCase Indicates if the case of the Strings should ignored during comparison.
* @param standardizeWhitespace Indicates if the embedded whitespace should be standardized before comparison.
*
* @return <code>true</code> if the Strings are the same, <code>false</code> otherwise.
*/
public static boolean isSame(String s1, String s2, boolean trim, boolean ignoreCase,
boolean standardizeWhitespace) {
if (s1 == null && s2 == null) {
return true;
} else if (s1 == null || s2 == null) {
return false;
} else {
if (trim) {
s1 = s1.trim();
s2 = s2.trim();
}
if (standardizeWhitespace) {
// Replace all whitespace with a standard single space
// character.
s1 = s1.replaceAll("\\s+", " ");
s2 = s2.replaceAll("\\s+", " ");
}
return ignoreCase ? s1.equalsIgnoreCase(s2) : s1.equals(s2);
}
}
/**
* Formats all items onto a string with separators if more than one exists,
* return an empty string if the items are null or empty.
*
* @param items Object[]
* @param separator String
*
* @return String
*/
public static String asString(Object[] items, String separator) {
if (items == null || items.length == 0) {
return "";
}
if (items.length == 1) {
return items[0].toString();
}
StringBuilder sb = new StringBuilder(items[0].toString());
for (int i = 1; i < items.length; i++) {
sb.append(separator).append(items[i]);
}
return sb.toString();
}
/**
* If the string starts and ends with the delimiter, returns the substring
* within the delimiters. Otherwise returns the original string. The
* start and end delimiter must be 2 separate instances.
* <pre>{@code
* removeSurrounding("", _ ) = ""
* removeSurrounding("q", 'q') = "q"
* removeSurrounding("qq", 'q') = ""
* removeSurrounding("q_q", 'q') = "_"
* }</pre>
*/
public static String removeSurrounding(String string, char delimiter) {
if (string.length() >= 2
&& string.charAt(0) == delimiter
&& string.charAt(string.length() - 1) == delimiter) {
return string.substring(1, string.length() - 1);
}
return string;
}
/**
* Like {@link #removeSurrounding(String, char) removeSurrounding} with
* a double quote as a delimiter.
*/
public static String removeDoubleQuotes(String string) {
return removeSurrounding(string, '"');
}
/**
* Truncate the given string to some maximum length. If it needs
* truncation, the ellipsis string is appended. The length of the
* returned string is always lower-or-equal to the maxOutputLength,
* even when truncation occurs.
*/
public static String elide(String string, int maxOutputLength, String ellipsis) {
AssertionUtil.requireNonNegative("maxOutputLength", maxOutputLength);
if (ellipsis.length() > maxOutputLength) {
throw new IllegalArgumentException("Ellipsis too long '" + ellipsis + "', maxOutputLength=" + maxOutputLength);
}
if (string.length() <= maxOutputLength) {
return string;
}
String truncated = string.substring(0, maxOutputLength - ellipsis.length());
return truncated + ellipsis;
}
/**
* Replaces unprintable characters by their escaped (or unicode escaped)
* equivalents in the given string
*/
public static String escapeJava(String str) {
StringBuilder retval = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
final char ch = str.charAt(i);
switch (ch) {
case 0:
break;
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u").append(s.substring(s.length() - 4));
} else {
retval.append(ch);
}
break;
}
}
return retval.toString();
}
/**
* Escape the string so that it appears literally when interpreted
* by a {@link MessageFormat}.
*/
public static String quoteMessageFormat(String str) {
return str.replaceAll("'", "''");
}
/** Return the empty string if the parameter is null. */
public static String nullToEmpty(final String value) {
return value == null ? "" : value;
}
public enum CaseConvention {
/** SCREAMING_SNAKE_CASE. */
SCREAMING_SNAKE_CASE {
@Override
List<String> toWords(String name) {
return CollectionUtil.map(name.split("_"), s -> s.toLowerCase(Locale.ROOT));
}
@Override
String joinWords(List<String> words) {
return words.stream().map(s -> s.toLowerCase(Locale.ROOT)).collect(Collectors.joining("_"));
}
},
/** camelCase. */
CAMEL_CASE {
@Override
List<String> toWords(String name) {
return PASCAL_CASE.toWords(name);
}
@Override
String joinWords(List<String> words) {
if (words.isEmpty()) {
return "";
}
return words.get(0).toLowerCase(Locale.ROOT) + PASCAL_CASE.joinWords(words.subList(1, words.size()));
}
},
/** PascalCase. */
PASCAL_CASE {
@Override
List<String> toWords(String name) {
return CollectionUtil.map(name.split("(?<![A-Z])(?=[A-Z])"), s -> s.toLowerCase(Locale.ROOT));
}
@Override
String joinWords(List<String> words) {
return words.stream().map(StringUtils::capitalize).collect(Collectors.joining());
}
},
/** space separated. */
SPACE_SEPARATED {
@Override
List<String> toWords(String name) {
return CollectionUtil.map(name.split("\\s++"), s -> s.toLowerCase(Locale.ROOT));
}
@Override
String joinWords(List<String> words) {
return String.join(" ", words);
}
};
/** Split a name written with this convention into a list of *lowercase* words. */
abstract List<String> toWords(String name);
/** Takes a list of lowercase words and joins them into a name following this convention. */
abstract String joinWords(List<String> words);
public String convertTo(CaseConvention to, String name) {
return to.joinWords(toWords(name));
}
}
}
| 19,811 | 33.575916 | 136 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/IteratorUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @author Clément Fournier
* @since 6.11.0
*/
public final class IteratorUtil {
private static final int MATCH_ANY = 0;
private static final int MATCH_ALL = 1;
private static final int MATCH_NONE = 2;
private IteratorUtil() {
}
public static <T> Iterator<T> takeWhile(Iterator<T> iter, Predicate<? super T> predicate) {
return new AbstractIterator<T>() {
@Override
protected void computeNext() {
if (iter.hasNext()) {
T next = iter.next();
if (predicate.test(next)) {
setNext(next);
return;
}
}
done();
}
};
}
public static <T> Iterator<T> reverse(Iterator<T> it) {
List<T> tmp = toList(it);
Collections.reverse(tmp);
return tmp.iterator();
}
public static <T, R> Iterator<R> flatMap(Iterator<? extends T> iter, Function<? super T, ? extends @Nullable Iterator<? extends R>> f) {
return new AbstractIterator<R>() {
private Iterator<? extends R> current = null;
@Override
protected void computeNext() {
if (current != null && current.hasNext()) {
setNext(current.next());
} else {
while (iter.hasNext()) {
Iterator<? extends R> next = f.apply(iter.next());
if (next != null && next.hasNext()) {
current = next;
setNext(current.next());
return;
}
}
done();
}
}
};
}
/**
* Like flatMap, but yields each element of the input iterator before
* yielding the results of the mapper function. Null elements of the
* input iterator are both yielded by the returned iterator and passed
* to the stepper. If the stepper returns null, that result is ignored.
*/
public static <R> Iterator<R> flatMapWithSelf(Iterator<? extends R> iter, Function<? super R, ? extends @Nullable Iterator<? extends R>> f) {
return new AbstractIterator<R>() {
private Iterator<? extends R> current = null;
@Override
protected void computeNext() {
if (current != null && current.hasNext()) {
setNext(current.next());
} else {
// current is exhausted
current = null;
if (iter.hasNext()) {
R next = iter.next();
setNext(next);
current = f.apply(next);
} else {
done();
}
}
}
};
}
public static <T> Iterator<@NonNull T> filterNotNull(Iterator<? extends T> it) {
return filter(it, Objects::nonNull);
}
public static <T, R> Iterator<@NonNull R> mapNotNull(Iterator<? extends T> it, Function<@NonNull ? super T, @Nullable ? extends R> mapper) {
return new AbstractIterator<R>() {
@Override
protected void computeNext() {
while (it.hasNext()) {
T next = it.next();
if (next != null) {
R map = mapper.apply(next);
if (map != null) {
setNext(map);
return;
}
}
}
done();
}
};
}
public static <T> Iterator<T> filter(Iterator<? extends T> it, Predicate<? super T> filter) {
return new AbstractIterator<T>() {
@Override
protected void computeNext() {
while (it.hasNext()) {
T next = it.next();
if (filter.test(next)) {
setNext(next);
return;
}
}
done();
}
};
}
public static <T> Iterator<T> peek(Iterator<? extends T> iter, Consumer<? super T> action) {
return map(iter, it -> {
action.accept(it);
return it;
});
}
public static <T, R> Iterator<R> map(Iterator<? extends T> iter, Function<? super T, ? extends R> mapper) {
return new Iterator<R>() {
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public R next() {
return mapper.apply(iter.next());
}
};
}
/**
* Apply a transform on the iterator of an iterable.
*/
public static <T, R> Iterable<R> mapIterator(Iterable<? extends T> iter, Function<? super Iterator<? extends T>, ? extends Iterator<R>> mapper) {
return () -> mapper.apply(iter.iterator());
}
@SafeVarargs
public static <T> Iterator<T> iterate(T... elements) {
return Arrays.asList(elements).iterator();
}
public static <T> Iterator<T> concat(Iterator<? extends T> as, Iterator<? extends T> bs) {
if (!as.hasNext()) {
return (Iterator<T>) bs;
} else if (!bs.hasNext()) {
return (Iterator<T>) as;
}
return new Iterator<T>() {
@Override
public boolean hasNext() {
return as.hasNext() || bs.hasNext();
}
@Override
public T next() {
return as.hasNext() ? as.next() : bs.next();
}
};
}
public static <T> Iterator<T> distinct(Iterator<? extends T> iter) {
Set<T> seen = new HashSet<>();
return filter(iter, seen::add);
}
public static <T> List<T> toList(Iterator<? extends T> it) {
List<T> list = new ArrayList<>();
while (it.hasNext()) {
list.add(it.next());
}
return list;
}
public static <T> List<@NonNull T> toNonNullList(Iterator<? extends @Nullable T> it) {
List<@NonNull T> list = new ArrayList<>();
while (it.hasNext()) {
T next = it.next();
if (next != null) {
list.add(next);
}
}
return list;
}
/**
* Remove the last n elements of the iterator. This uses n elements as a lookahead.
*/
public static <T> Iterator<@NonNull T> dropLast(Iterator<? extends @Nullable T> it, final int n) {
AssertionUtil.requireNonNegative("n", n);
if (n == 0) {
return coerceWildcard(it); // noop
} else if (n == 1) { // i guess this will be common
if (!it.hasNext()) {
return Collections.emptyIterator();
}
return new AbstractIterator<T>() {
T next = it.next();
@Override
protected void computeNext() {
if (it.hasNext()) {
setNext(next);
next = it.next();
} else {
done();
}
}
};
}
// fill a circular lookahead buffer
Object[] ringBuffer = new Object[n];
for (int i = 0; i < n && it.hasNext(); i++) {
ringBuffer[i] = it.next();
}
if (!it.hasNext()) {
// the original iterator has less than n elements
return Collections.emptyIterator();
}
return new AbstractIterator<T>() {
private int idx = 0;
@Override
protected void computeNext() {
if (it.hasNext()) {
setNext((T) ringBuffer[idx]); // yield element X from the buffer
ringBuffer[idx] = it.next(); // overwrite with the element X+n
idx = (idx + 1) % ringBuffer.length; // compute idx of element X+1
} else {
// that's it: our buffer contains the n tail elements
// that we don't want to see.
done();
}
}
};
}
/**
* Coerce an iterator with a wildcard. This is safe because the Iterator
* interface is covariant (not {@link ListIterator} though).
*/
@SuppressWarnings("unchecked")
public static <T> Iterator<T> coerceWildcard(final Iterator<? extends T> it) {
return (Iterator<T>) it;
}
public static <T> Iterable<T> toIterable(final Iterator<T> it) {
return () -> it;
}
/** Counts the items in this iterator, exhausting it. */
public static int count(Iterator<?> it) {
int count = 0;
while (it.hasNext()) {
it.next();
count++;
}
return count;
}
public static <T> @Nullable T last(Iterator<? extends T> iterator) {
T next = null;
while (iterator.hasNext()) {
next = iterator.next();
}
return next;
}
/**
* Returns the nth element of this iterator, or null if the iterator
* is shorter.
*
* @throws IllegalArgumentException If n is negative
*/
public static <T> @Nullable T getNth(Iterator<? extends T> iterator, int n) {
advance(iterator, n);
return iterator.hasNext() ? iterator.next() : null;
}
/** Advance {@code n} times. */
public static void advance(Iterator<?> iterator, int n) {
AssertionUtil.requireNonNegative("n", n);
while (n > 0 && iterator.hasNext()) {
iterator.next();
n--;
}
}
/** Limit the number of elements yielded by this iterator to the given number. */
public static <T> Iterator<T> take(Iterator<? extends T> iterator, final int n) {
AssertionUtil.requireNonNegative("n", n);
if (n == 0) {
return Collections.emptyIterator();
}
return new AbstractIterator<T>() {
private int yielded = 0;
@Override
protected void computeNext() {
if (yielded >= n || !iterator.hasNext()) {
done();
} else {
setNext(iterator.next());
}
yielded++;
}
};
}
/** Produce an iterator whose first element is the nth element of the given source. */
public static <T> Iterator<T> drop(Iterator<? extends T> source, final int n) {
AssertionUtil.requireNonNegative("n", n);
if (n == 0) {
return (Iterator<T>) source;
}
return new AbstractIterator<T>() {
private int yielded = 0;
@Override
protected void computeNext() {
while (yielded++ < n && source.hasNext()) {
source.next();
}
if (!source.hasNext()) {
done();
} else {
setNext(source.next());
}
}
};
}
/**
* Returns an iterator that applies a stepping function to the previous
* value yielded. Iteration stops on the first null value returned by
* the stepper.
*
* @param seed First value. If null then the iterator is empty
* @param stepper Step function
* @param <T> Type of values
*/
public static <T> Iterator<@NonNull T> generate(@Nullable T seed, Function<? super @NonNull T, ? extends @Nullable T> stepper) {
return new AbstractIterator<T>() {
T next = seed;
@Override
protected void computeNext() {
if (next == null) {
done();
return;
}
setNext(next);
next = stepper.apply(next);
}
};
}
/**
* Returns whether some element match the predicate. If empty then {@code false}
* is returned.
*/
public static <T> boolean anyMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) {
return matches(iterator, pred, MATCH_ANY);
}
/**
* Returns whether all elements match the predicate. If empty then {@code true}
* is returned.
*/
public static <T> boolean allMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) {
return matches(iterator, pred, MATCH_ALL);
}
/**
* Returns whether no elements match the predicate. If empty then {@code true}
* is returned.
*/
public static <T> boolean noneMatch(Iterator<? extends T> iterator, Predicate<? super T> pred) {
return matches(iterator, pred, MATCH_NONE);
}
private static <T> boolean matches(Iterator<? extends T> iterator, Predicate<? super T> pred, int matchKind) {
final boolean kindAny = matchKind == MATCH_ANY;
final boolean kindAll = matchKind == MATCH_ALL;
while (iterator.hasNext()) {
final T value = iterator.next();
final boolean match = pred.test(value);
if (match ^ kindAll) { // xor
return kindAny && match;
}
}
return !kindAny;
}
public static <T> Iterator<T> singletonIterator(T value) {
class SingletonIterator implements Iterator<T> {
private boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public T next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return value;
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
action.accept(value);
}
}
return new SingletonIterator();
}
public static <T> Iterable<T> asReversed(final List<T> lst) {
return () -> new Iterator<T>() {
ListIterator<T> li = lst.listIterator(lst.size());
@Override
public boolean hasNext() {
return li.hasPrevious();
}
@Override
public T next() {
return li.previous();
}
@Override
public void remove() {
li.remove();
}
};
}
public static <T> Stream<T> toStream(Iterator<? extends T> iter) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, 0), false);
}
public abstract static class AbstractIterator<T> implements Iterator<T> {
private State state = State.NOT_READY;
private T next = null;
@Override
public boolean hasNext() {
switch (state) {
case DONE:
return false;
case READY:
return true;
default:
state = null;
computeNext();
if (state == null) {
throw new IllegalStateException("Should have called done or setNext");
}
return state == State.READY;
}
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
state = State.NOT_READY;
return next;
}
protected final void setNext(T t) {
assert state == null : "Must call exactly one of setNext or done";
next = t;
state = State.READY;
}
protected final void done() {
assert state == null : "Must call exactly one of setNext or done";
state = State.DONE;
}
/**
* Compute the next element. Implementations must call either
* {@link #done()} or {@link #setNext(Object)} exactly once.
*/
protected abstract void computeNext();
enum State {
READY, NOT_READY, DONE
}
@Deprecated
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
public abstract static class AbstractPausingIterator<T> extends AbstractIterator<T> {
private int numYielded = 0;
private T currentValue;
@Override
public T next() {
T next = super.next();
currentValue = next;
prepareViewOn(next);
numYielded++;
return next;
}
protected void prepareViewOn(T current) {
// to be overridden
}
protected final int getIterationCount() {
return numYielded;
}
protected T getCurrentValue() {
ensureReadable();
return currentValue;
}
protected void ensureReadable() {
if (numYielded == 0) {
throw new IllegalStateException("No values were yielded, should have called next");
}
}
}
}
| 18,088 | 29.09817 | 149 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/AssertionUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.util.Collection;
import java.util.function.Function;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class AssertionUtil {
private static final Pattern PACKAGE_PATTERN = Pattern.compile("[\\w$]+(\\.[\\w$]+)*|");
private static final Pattern BINARY_NAME_PATTERN = Pattern.compile("[\\w$]+(?:\\.[\\w$]+)*(?:\\[])*");
private static final Pattern BINARY_NAME_NO_ARRAY = Pattern.compile("[\\w$]++(?:\\.[\\w$]++)*");
private AssertionUtil() {
// utility class
}
/** @throws NullPointerException if any item is null */
public static void requireContainsNoNullValue(String name, Collection<?> c) {
int i = 0;
for (Object o : c) {
if (o == null) {
throw new NullPointerException(name + " contains a null element at index " + i);
}
i++;
}
}
/** @throws IllegalArgumentException if empty */
public static void requireNotEmpty(String name, Collection<?> c) {
if (c.isEmpty()) {
throw new IllegalArgumentException(name + " is empty");
}
}
public static boolean isValidJavaPackageName(CharSequence name) {
requireParamNotNull("name", name);
return PACKAGE_PATTERN.matcher(name).matches();
}
/**
* @throws IllegalArgumentException if the name is not a binary name
*/
public static void assertValidJavaBinaryName(CharSequence name) {
if (!isJavaBinaryName(name)) {
throw new IllegalArgumentException("Not a Java binary name '" + name + "'");
}
}
/**
* @throws IllegalArgumentException if the name is not a binary name
*/
public static void assertValidJavaBinaryNameNoArray(CharSequence name) {
if (!BINARY_NAME_NO_ARRAY.matcher(name).matches()) {
throw new IllegalArgumentException("Not a Java binary name '" + name + "'");
}
}
private static boolean isJavaBinaryName(CharSequence name) {
return name.length() > 0 && BINARY_NAME_PATTERN.matcher(name).matches();
}
private static boolean isValidRange(int startInclusive, int endExclusive, int minIndex, int maxIndex) {
return startInclusive <= endExclusive && minIndex <= startInclusive && endExclusive <= maxIndex;
}
private static String invalidRangeMessage(int startInclusive, int endExclusive, int minIndex, int maxIndex) {
return "Invalid range [" + startInclusive + "," + endExclusive + "[ in [" + minIndex + "," + maxIndex + "[";
}
/** Throws {@link IllegalStateException} if the condition is false. */
public static void validateState(boolean condition, String failed) {
if (!condition) {
throw new IllegalStateException(failed);
}
}
/**
* @throws IllegalArgumentException if [startInclusive,endExclusive[ is
* not a valid substring range for the given string
*/
public static void validateStringRange(CharSequence string, int startInclusive, int endExclusive) {
if (!isValidRange(startInclusive, endExclusive, 0, string.length())) {
throw new IllegalArgumentException(invalidRangeMessage(startInclusive, endExclusive, 0, string.length()));
}
}
/**
* Like {@link #validateStringRange(CharSequence, int, int)} but eliminated
* at runtime if running without assertions.
*/
public static void assertValidStringRange(CharSequence string, int startInclusive, int endExclusive) {
assert isValidRange(startInclusive, endExclusive, 0, string.length())
: invalidRangeMessage(startInclusive, endExclusive, 0, string.length());
}
/**
* Returns true if the charsequence is a valid java identifier.
*
* @param name Name (non-null)
*
* @throws NullPointerException If the name is null
*/
public static boolean isJavaIdentifier(CharSequence name) {
int len = name.length();
if (len == 0 || !Character.isJavaIdentifierStart(name.charAt(0))) {
return false;
}
for (int i = 1; i < len; i++) {
if (!Character.isJavaIdentifierPart(name.charAt(i))) {
return false;
}
}
return true;
}
public static int requireOver1(String name, final int value) {
if (value < 1) {
throw mustBe(name, value, ">= 1");
}
return value;
}
/**
* @throws IllegalArgumentException If value < 0
*/
public static int requireNonNegative(String name, int value) {
if (value < 0) {
throw mustBe(name, value, "non-negative");
}
return value;
}
/**
* @throws IndexOutOfBoundsException If value < 0
*/
public static int requireIndexNonNegative(String name, int value) {
if (value < 0) {
throw mustBe(name, value, "non-negative", IndexOutOfBoundsException::new);
}
return value;
}
/**
* @throws IndexOutOfBoundsException If value < 0 || value >= maxValue
*/
public static int requireInNonNegativeRange(String name, int value, int maxValue) {
return requireInExclusiveRange(name, value, 0, maxValue);
}
/**
* @throws IndexOutOfBoundsException If value < 1 || value >= maxValue
*/
public static int requireInPositiveRange(String name, int value, int maxValue) {
return requireInExclusiveRange(name, value, 1, maxValue);
}
// the difference between those two is the message
/**
* @throws IndexOutOfBoundsException If {@code value < minValue || value > maxValue}
*/
public static int requireInInclusiveRange(String name, int value, int minValue, int maxValue) {
return requireInRange(name, value, minValue, maxValue, true);
}
/**
* @throws IndexOutOfBoundsException If {@code value < minValue || value > maxValue}
*/
public static int requireInExclusiveRange(String name, int value, int minValue, int maxValue) {
return requireInRange(name, value, minValue, maxValue, false);
}
public static int requireInRange(String name, int value, int minValue, int maxValue, boolean inclusive) {
if (value < 0 || inclusive && value > maxValue || !inclusive && value >= maxValue) {
String message = "in range [" + minValue + "," + maxValue;
message += inclusive ? "]" : "[";
throw mustBe(name, value, message, IndexOutOfBoundsException::new);
}
return value;
}
public static RuntimeException mustBe(String name, Object value, String condition) {
return mustBe(name, value, condition, IllegalArgumentException::new);
}
public static <E extends RuntimeException> E mustBe(String name, Object value, String condition, Function<String, E> exceptionMaker) {
return exceptionMaker.apply(String.format("%s must be %s, got %s", name, condition, value));
}
@NonNull
public static <T> T requireParamNotNull(String paramName, T obj) {
if (obj == null) {
throw new NullPointerException("Parameter " + paramName + " is null");
}
return obj;
}
public static @NonNull AssertionError shouldNotReachHere(String message) {
String prefix = "This should be unreachable";
message = StringUtils.isBlank(message) ? prefix
: prefix + ": " + message;
return new AssertionError(message);
}
public static @NonNull ContextedAssertionError contexted(AssertionError e) {
return ContextedAssertionError.wrap(e);
}
public static @NonNull ContextedStackOverflowError contexted(StackOverflowError e) {
return ContextedStackOverflowError.wrap(e);
}
public static @NonNull ContextedRuntimeException contexted(RuntimeException e) {
return e instanceof ContextedRuntimeException ? (ContextedRuntimeException) e
: new ContextedRuntimeException(e);
}
}
| 8,388 | 34.54661 | 138 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/GraphUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class GraphUtil {
private GraphUtil() {
}
/**
* Generate a DOT representation for a graph.
*
* @param vertices Set of vertices
* @param successorFun Function fetching successors
* @param colorFun Color of vertex box
* @param labelFun Vertex label
* @param <V> Type of vertex, must be usable as map key (equals/hash)
*/
public static <V> String toDot(
Collection<? extends V> vertices,
Function<? super V, ? extends Collection<? extends V>> successorFun,
Function<? super V, DotColor> colorFun,
Function<? super V, String> labelFun
) {
// generates a DOT representation of the lattice
// Visualize eg at http://webgraphviz.com/
StringBuilder sb = new StringBuilder("strict digraph {\n");
Map<V, String> ids = new HashMap<>();
int i = 0;
for (V node : vertices) {
String id = "n" + i++;
ids.put(node, id);
sb.append(id)
.append(" [ shape=box, color=")
.append(colorFun.apply(node).toDot())
.append(", label=\"")
.append(escapeDotString(labelFun.apply(node)))
.append("\" ];\n");
}
List<String> edges = new ArrayList<>();
for (V node : vertices) {
// edges
String id = ids.get(node);
for (V succ : successorFun.apply(node)) {
String succId = ids.get(succ);
edges.add(id + " -> " + succId + ";\n");
}
}
edges.sort(Comparator.naturalOrder()); // for reproducibility in tests
edges.forEach(sb::append);
return sb.append('}').toString();
}
@NonNull
private static String escapeDotString(String string) {
return string.replaceAll("\\R", "\\\n")
.replaceAll("\"", "\\\"");
}
public enum DotColor {
GREEN, BLACK;
String toDot() {
return name().toLowerCase(Locale.ROOT);
}
}
}
| 2,489 | 26.666667 | 82 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/DataMap.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An opaque, strongly typed heterogeneous data container. Data maps can
* be set to accept only a certain type of key, with the type parameter.
* The key can itself constrain the type of values, using its own type
* parameter {@code T}.
*
* @param <K> Type of keys in this map.
*/
public final class DataMap<K> {
private Map<DataKey<? extends K, ?>, Object> map;
private DataMap() {
}
/**
* Set the mapping to the given data.
*
* @param key Key
* @param data Data mapped to the key
* @param <T> Type of the data
*
* @return Previous value associated with the key (nullable)
*/
@SuppressWarnings("unchecked")
public <T> @Nullable T set(DataKey<? extends K, ? super T> key, T data) {
return (T) getMap().put(key, data);
}
/**
* Retrieves the data currently mapped to the key.
*
* @param key Key
* @param <T> Type of the data
*
* @return Value associated with the key (nullable)
*/
@SuppressWarnings("unchecked")
public <T> @Nullable T get(DataKey<? extends K, ? extends T> key) {
return map == null ? null : (T) map.get(key);
}
@SuppressWarnings("unchecked")
public <T> T getOrDefault(DataKey<? extends K, ? extends T> key, T defaultValue) {
return map == null ? defaultValue : (T) map.getOrDefault(key, defaultValue);
}
/**
* Retrieve the value, or compute it if it is missing.
*
* @param key Key
* @param supplier Supplier for a value
* @param <T> Type of the data
*
* @return Value associated with the key (as nullable as the
*/
@SuppressWarnings("unchecked")
public <T> T computeIfAbsent(DataKey<? extends K, T> key, Supplier<? extends T> supplier) {
return (T) getMap().computeIfAbsent(key, k -> supplier.get());
}
/**
* Create or replace a mapping with a value computed from the current
* value (or null if missing).
*
* @param key Key
* @param function Supplier for a value
* @param <T> Type of the data
*
* @return Value returned by the parameter function
*/
@SuppressWarnings("unchecked")
public <T> T compute(DataKey<? extends K, T> key, Function<? super @Nullable T, ? extends T> function) {
return (T) getMap().compute(key, (k, v) -> function.apply((T) v));
}
private Map<DataKey<? extends K, ?>, Object> getMap() {
// the map is lazily created, it's only needed if set() is called
// at least once, but get() might be called many more times, as
// sometimes you cache a key sparsely on some nodes, and default
// to the first parent for which the key is set. The default expected
// max size is also 21, which is *way* bigger than what data maps
// typically contain (1/2 keys)
if (map == null) {
map = new IdentityHashMap<>(1);
}
return map;
}
/**
* Returns true if the given key has a non-null value in the map.
*
* @param key Key
*
* @return True if some value is set
*/
public boolean isSet(DataKey<? extends K, ?> key) {
return map != null && map.containsKey(key);
}
public static <K> DataMap<K> newDataMap() {
return new DataMap<>();
}
public static <T> SimpleDataKey<T> simpleDataKey(final String name) {
return new SimpleDataKey<>(name);
}
/**
* A key for type-safe access into a {@link DataMap}. Data keys use
* reference identity and are only compared by reference within
* {@link DataMap}.
*
* @param <K> Type of the family of keys this is a part of
* @param <T> Type of the addressed data
*/
public interface DataKey<K extends DataKey<K, T>, T> {
}
public static class SimpleDataKey<T> implements DataKey<SimpleDataKey<T>, T> {
private final String name;
SimpleDataKey(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
| 4,436 | 28.778523 | 108 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/ContextedAssertionError.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import org.apache.commons.lang3.exception.DefaultExceptionContext;
import net.sourceforge.pmd.internal.util.ExceptionContextDefaultImpl;
/**
* An {@link AssertionError} with nice messages.
*/
public final class ContextedAssertionError extends AssertionError implements ExceptionContextDefaultImpl<ContextedAssertionError> {
/** The serialization version. */
private static final long serialVersionUID = -8919808081157463410L;
private final DefaultExceptionContext exceptionContext = new DefaultExceptionContext();
private ContextedAssertionError(AssertionError e) {
super(e.getMessage());
setStackTrace(e.getStackTrace()); // pretend we're a regular assertion error
}
public static ContextedAssertionError wrap(AssertionError e) {
return e instanceof ContextedAssertionError ? (ContextedAssertionError) e
: new ContextedAssertionError(e);
}
@Override
public String getMessage() {
return getFormattedExceptionMessage(super.getMessage());
}
@Override
public DefaultExceptionContext getExceptionContext() {
return exceptionContext;
}
@Override
public ContextedAssertionError getThrowable() {
return this;
}
}
| 1,404 | 29.543478 | 131 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/CollectionUtil.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyIterator;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collector.Characteristics;
import java.util.stream.Collectors;
import org.apache.commons.lang3.Validate;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.pcollections.ConsPStack;
import org.pcollections.HashTreePSet;
import org.pcollections.PMap;
import org.pcollections.PSequence;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.document.Chars;
/**
* Generic collection-related utility functions for java.util types.
*
* @author Brian Remedios
* @author Clément Fournier
*/
public final class CollectionUtil {
private static final int UNKNOWN_SIZE = -1;
private CollectionUtil() {
}
/**
* Creates and returns a map populated with the keyValuesSets where the
* value held by the tuples are they key and value in that order.
*
* @param keys
* K[]
* @param values
* V[]
* @return Map
*
* @deprecated Used by deprecated property types
*/
@Deprecated
public static <K, V> Map<K, V> mapFrom(K[] keys, V[] values) {
if (keys.length != values.length) {
throw new RuntimeException("mapFrom keys and values arrays have different sizes");
}
Map<K, V> map = new HashMap<>(keys.length);
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
return map;
}
/**
* Returns a map based on the source but with the key & values swapped.
*
* @param source
* Map
* @return Map
*
* @deprecated Used by deprecated property types
*/
@Deprecated
public static <K, V> Map<V, K> invertedMapFrom(Map<K, V> source) {
Map<V, K> map = new HashMap<>(source.size());
for (Map.Entry<K, V> entry : source.entrySet()) {
map.put(entry.getValue(), entry.getKey());
}
return map;
}
/**
* Returns a list view that pretends it is the concatenation of
* both lists. The returned view is unmodifiable. The implementation
* is pretty stupid and not optimized for repeated concatenation,
* but should be ok for smallish chains of random-access lists.
*
* @param head Head elements (to the left)
* @param tail Tail elements (to the right)
* @param <T> Type of elements in both lists
*
* @return A concatenated view
*/
public static <T> List<T> concatView(List<? extends T> head, List<? extends T> tail) {
if (head.isEmpty()) {
return makeUnmodifiableAndNonNull(tail);
} else if (tail.isEmpty()) {
return makeUnmodifiableAndNonNull(head);
} else {
return new ConsList<>(head, tail);
}
}
/**
* Returns the set union of the given collections.
*
* @param c1 First collection
* @param c2 Second collection
*
* @return Union of both arguments
*/
@SafeVarargs
public static <T> Set<T> union(Collection<? extends T> c1, Collection<? extends T> c2, Collection<? extends T>... rest) {
Set<T> union = new LinkedHashSet<>(c1);
union.addAll(c2);
for (Collection<? extends T> ts : rest) {
union.addAll(ts);
}
return union;
}
/**
* Returns the set intersection of the given collections.
*
* @param c1 First collection
* @param c2 Second collection
*
* @return Intersection of both arguments
*/
@SafeVarargs
public static <T> Set<T> intersect(Collection<? extends T> c1, Collection<? extends T> c2, Collection<? extends T>... rest) {
Set<T> union = new LinkedHashSet<>(c1);
union.retainAll(c2);
for (Collection<? extends T> ts : rest) {
union.retainAll(ts);
}
return union;
}
/**
* Returns the set difference of the first collection with the other
* collections.
*
* @param c1 First collection
* @param c2 Second collection
*
* @return Difference of arguments
*/
@SafeVarargs
public static <T> Set<T> diff(Collection<? extends T> c1, Collection<? extends T> c2, Collection<? extends T>... rest) {
Set<T> union = new LinkedHashSet<>(c1);
union.removeAll(c2);
for (Collection<? extends T> ts : rest) {
union.removeAll(ts);
}
return union;
}
/**
* Returns a set containing the given elements. No guarantee is
* made about mutability.
*
* @param first First element
* @param rest Following elements
*/
@SafeVarargs
public static <T> Set<T> setOf(T first, T... rest) {
return immutableSetOf(first, rest);
}
/**
* Returns an unmodifiable set containing the given elements.
*
* @param first First element
* @param rest Following elements
*/
@SafeVarargs
public static <T> Set<T> immutableSetOf(T first, T... rest) {
if (rest.length == 0) {
return Collections.singleton(first);
}
Set<T> union = new LinkedHashSet<>();
union.add(first);
Collections.addAll(union, rest);
return Collections.unmodifiableSet(union);
}
/**
* Returns an unmodifiable set containing the given elements.
*
* @param first First element
* @param rest Following elements
*/
@SafeVarargs
public static <T extends Enum<T>> Set<T> immutableEnumSet(T first, T... rest) {
return Collections.unmodifiableSet(EnumSet.of(first, rest));
}
@SafeVarargs
public static <T> List<T> listOf(T first, T... rest) {
if (rest.length == 0) {
return ConsPStack.singleton(first);
}
List<T> union = new ArrayList<>();
union.add(first);
union.addAll(asList(rest));
return Collections.unmodifiableList(union);
}
public static <K, V> Map<K, V> mapOf(K k0, V v0) {
return Collections.singletonMap(k0, v0);
}
public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2) {
Map<K, V> map = new LinkedHashMap<>();
map.put(k1, v1);
map.put(k2, v2);
return Collections.unmodifiableMap(map);
}
public static <K, V> Map<K, V> buildMap(Consumer<Map<K, V>> effect) {
Map<K, V> map = new LinkedHashMap<>();
effect.accept(map);
return Collections.unmodifiableMap(map);
}
public static <K, V> Map<K, V> buildMap(Map<K, V> initialMap, Consumer<Map<K, V>> effect) {
Map<K, V> map = new LinkedHashMap<>(initialMap);
effect.accept(map);
return Collections.unmodifiableMap(map);
}
public static <T, R> List<@NonNull R> mapNotNull(Iterable<? extends T> from, Function<? super T, ? extends @Nullable R> f) {
Iterator<? extends T> it = from.iterator();
if (!it.hasNext()) {
return Collections.emptyList();
}
List<R> res = new ArrayList<>();
while (it.hasNext()) {
R r = f.apply(it.next());
if (r != null) {
res.add(r);
}
}
return res;
}
/**
* Produce a new map with the mappings of the first, and one additional
* mapping. The returned map may be unmodifiable.
*/
public static <K, V> Map<K, V> plus(Map<K, V> m, K k, V v) {
if (m instanceof PMap) {
return ((PMap<K, V>) m).plus(k, v);
}
if (m.isEmpty()) {
return Collections.singletonMap(k, v);
}
Map<K, V> newM = new HashMap<>(m);
newM.put(k, v);
return newM;
}
/**
* Produce a new list with the elements of the first, and one additional
* item. The returned list is immutable.
*/
public static <V> List<V> plus(List<V> list, V v) {
if (list instanceof PSequence) {
return ((PSequence<V>) list).plus(v);
} else if (list.isEmpty()) {
return ConsPStack.singleton(v);
}
return ConsPStack.from(list).plus(v);
}
/** Returns the empty list. */
public static <V> List<V> emptyList() {
// We use this implementation so that it plays well with other
// operations that expect immutable data.
return ConsPStack.empty();
}
/**
* Returns an unmodifiable set containing the set union of the collection,
* and the new elements.
*/
@SafeVarargs
@SuppressWarnings("unchecked")
public static <V> Set<V> setUnion(Collection<? extends V> set, V first, V... newElements) {
if (set instanceof PSet) {
return ((PSet<V>) set).plus(first).plusAll(asList(newElements));
}
Set<V> newSet = new LinkedHashSet<>(set.size() + 1 + newElements.length);
newSet.addAll(set);
newSet.add(first);
Collections.addAll(newSet, newElements);
return Collections.unmodifiableSet(newSet);
}
/**
* Returns a map associating each key in the first list to its
* corresponding value in the second.
*
* @throws IllegalArgumentException If the list size are mismatched
* @throws NullPointerException If either of the parameter is null,
* or any of the keys or values are null
*/
public static <K, V> Map<K, V> zip(List<? extends @NonNull K> from, List<? extends @NonNull V> to) {
AssertionUtil.requireParamNotNull("keys", from);
AssertionUtil.requireParamNotNull("values", to);
Validate.isTrue(from.size() == to.size(), "Mismatched list sizes %s to %s", from, to);
if (from.isEmpty()) { //NOPMD: we really want to compare references here
return emptyMap();
}
Map<K, V> map = new HashMap<>(from.size());
for (int i = 0; i < from.size(); i++) {
K key = from.get(i);
V val = to.get(i);
Validate.notNull(key);
Validate.notNull(val);
map.put(key, val);
}
return map;
}
public static <K, V> Map<K, V> associateWith(Collection<? extends @NonNull K> keys, Function<? super K, ? extends V> mapper) {
AssertionUtil.requireParamNotNull("keys", keys);
if (keys.isEmpty()) {
return emptyMap();
}
return associateWithTo(new HashMap<>(keys.size()), keys, mapper);
}
public static <K, V> Map<K, V> associateWithTo(Map<K, V> collector, Collection<? extends @NonNull K> keys, Function<? super K, ? extends V> mapper) {
AssertionUtil.requireParamNotNull("collector", collector);
AssertionUtil.requireParamNotNull("keys", keys);
AssertionUtil.requireParamNotNull("mapper", mapper);
for (K key : keys) {
collector.put(key, mapper.apply(key));
}
return collector;
}
public static <K, V> Map<K, V> associateBy(Collection<? extends @NonNull V> values, Function<? super V, ? extends K> keyMapper) {
AssertionUtil.requireParamNotNull("values", values);
if (values.isEmpty()) {
return emptyMap();
}
return associateByTo(new HashMap<>(values.size()), values, keyMapper);
}
public static <K, V> Map<K, V> associateByTo(Map<K, V> collector, Collection<? extends @NonNull V> values, Function<? super V, ? extends K> keyMapper) {
AssertionUtil.requireParamNotNull("collector", collector);
AssertionUtil.requireParamNotNull("values", values);
AssertionUtil.requireParamNotNull("keyMapper", keyMapper);
for (V v : values) {
collector.put(keyMapper.apply(v), v);
}
return collector;
}
/**
* Map each element of the given collection with the given function,
* and accumulates it into an unmodifiable list.
*/
public static <T, R> List<R> map(Collection<? extends T> from, Function<? super T, ? extends R> f) {
if (from == null) {
return emptyList();
}
return map(from.iterator(), from.size(), f);
}
/**
* Map each element of the given iterable with the given function,
* and accumulates it into an unmodifiable list.
*/
public static <T, R> List<R> map(Iterable<? extends T> from, Function<? super T, ? extends R> f) {
if (from == null) {
return emptyList();
}
return map(from.iterator(), UNKNOWN_SIZE, f);
}
/**
* Map each element of the given array with the given function,
* and accumulates it into an unmodifiable list.
*/
public static <T, R> List<R> map(T[] from, Function<? super T, ? extends R> f) {
if (from == null) {
return emptyList();
}
return map(asList(from), f);
}
/**
* Map each element of the given iterator with the given function,
* and accumulates it into an unmodifiable list.
*/
public static <T, R> List<R> map(Iterator<? extends T> from, Function<? super T, ? extends R> f) {
if (from == null) {
return emptyList();
}
return map(from, UNKNOWN_SIZE, f);
}
private static <T, R> List<R> map(Iterator<? extends T> from, int sizeHint, Function<? super T, ? extends R> f) {
if (!from.hasNext()) {
return emptyList();
} else if (sizeHint == 1) {
return ConsPStack.singleton(f.apply(from.next()));
}
List<R> res = sizeHint == UNKNOWN_SIZE ? new ArrayList<>() : new ArrayList<>(sizeHint);
while (from.hasNext()) {
res.add(f.apply(from.next()));
}
return Collections.unmodifiableList(res);
}
/**
* Map each element of the given iterable with the given function,
* and accumulates it into the collector.
*/
public static <T, U, A, C> C map(Collector<? super U, A, ? extends C> collector,
Iterable<? extends T> from,
Function<? super T, ? extends U> f) {
if (from == null) {
return map(collector, emptyIterator(), f);
}
return map(collector, from.iterator(), f);
}
/**
* Map each element of the given iterator with the given function,
* and accumulates it into the collector.
*/
// one more type param and we can write tupac
public static <T, U, A, C> C map(Collector<? super U, A, ? extends C> collector,
Iterator<? extends T> from,
Function<? super T, ? extends U> f) {
A a = collector.supplier().get();
BiConsumer<A, ? super U> accumulator = collector.accumulator();
from.forEachRemaining(t -> accumulator.accept(a, f.apply(t)));
return finish(collector, a);
}
/**
* A collector that returns a mutable list. This contrasts with
* {@link Collectors#toList()}, which makes no guarantee about the
* mutability of the list.
*
* @param <T> Type of accumulated values
*/
public static <T> Collector<T, ?, List<T>> toMutableList() {
return Collectors.toCollection(ArrayList::new);
}
/**
* A collector that returns a mutable set. This contrasts with
* {@link Collectors#toSet()}, which makes no guarantee about the
* mutability of the set. The set preserves insertion order.
*
* @param <T> Type of accumulated values
*/
public static <T> Collector<T, ?, Set<T>> toMutableSet() {
return Collectors.toCollection(LinkedHashSet::new);
}
/**
* A collector that returns an unmodifiable list. This contrasts with
* {@link Collectors#toList()}, which makes no guarantee about the
* mutability of the list. {@code Collectors::toUnmodifiableList} was
* only added in JDK 9.
*
* @param <T> Type of accumulated values
*/
public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
return Collectors.collectingAndThen(toMutableList(), Collections::unmodifiableList);
}
/**
* A collector that returns an unmodifiable set. This contrasts with
* {@link Collectors#toSet()}, which makes no guarantee about the
* mutability of the set. {@code Collectors::toUnmodifiableSet} was
* only added in JDK 9. The set preserves insertion order.
*
* @param <T> Type of accumulated values
*/
public static <T> Collector<T, ?, Set<T>> toUnmodifiableSet() {
return Collectors.collectingAndThen(toMutableSet(), Collections::unmodifiableSet);
}
/**
* A collectors that accumulates into a persistent set.
*
* @param <T> Type of accumulated values
*/
public static <T> Collector<T, ?, PSet<T>> toPersistentSet() {
class Holder {
PSet<T> set = HashTreePSet.empty();
}
return Collector.of(
Holder::new,
(h, t) -> h.set = h.set.plus(t),
(left, right) -> {
left.set = left.set.plusAll(right.set);
return left;
},
a -> a.set
);
}
/**
* Finish the accumulated value of the collector.
*/
public static <V, A, C> C finish(Collector<? super V, A, ? extends C> collector, A acc) {
if (collector.characteristics().contains(Characteristics.IDENTITY_FINISH)) {
return (C) acc;
} else {
return collector.finisher().apply(acc);
}
}
public static <T> List<T> drop(List<T> list, int n) {
AssertionUtil.requireNonNegative("n", n);
return list.size() <= n ? emptyList()
: list.subList(n, list.size());
}
public static <T> List<T> take(List<T> list, int n) {
AssertionUtil.requireNonNegative("n", n);
return list.size() <= n ? list
: list.subList(0, n);
}
public static <T> List<T> listOfNotNull(T t) {
return t == null ? emptyList() : ConsPStack.singleton(t);
}
/**
* Returns true if any element of the iterable matches the predicate. Return
* false if the list is null or empty.
*/
public static <N> boolean any(@Nullable Iterable<? extends N> list, Predicate<? super N> predicate) {
return list != null && IteratorUtil.anyMatch(list.iterator(), predicate);
}
/**
* Returns true if all elements of the iterable match the predicate. Return
* true if the list is null or empty.
*/
public static <N> boolean all(@Nullable Iterable<? extends N> list, Predicate<? super N> predicate) {
return list == null || IteratorUtil.allMatch(list.iterator(), predicate);
}
/**
* Returns true if no element of the iterable matches the predicate. Return
* true if the list is null or empty.
*/
public static <N> boolean none(@Nullable Iterable<? extends N> list, Predicate<? super N> predicate) {
return list == null || IteratorUtil.noneMatch(list.iterator(), predicate);
}
/**
* If the set has a single element, returns it, otherwise returns null.
* Obviously the set should not contain null elements.
*/
public static <@NonNull T> @Nullable T asSingle(Set<T> set) {
if (set.size() == 1) {
return set.iterator().next();
} else {
return null;
}
}
/**
* Returns an unmodifiable copy of the list. This is to be preferred
* to {@link Collections#unmodifiableList(List)} if you don't trust
* the source of the list, because no one holds a reference to the buffer
* except the returned unmodifiable list.
*
* @param list A list
* @param <T> Type of items
*/
public static <T> List<T> defensiveUnmodifiableCopy(List<? extends T> list) {
if (list instanceof PSequence) {
return (List<T>) list; // is already immutable
}
if (list.isEmpty()) {
return ConsPStack.empty();
} else if (list.size() == 1) {
return ConsPStack.singleton(list.get(0));
}
return ConsPStack.from(list);
}
public static <T> Set<T> defensiveUnmodifiableCopyToSet(Collection<? extends T> list) {
if (list.isEmpty()) {
return emptySet();
}
return Collections.unmodifiableSet(new LinkedHashSet<>(list));
}
/**
* Like {@link String#join(CharSequence, Iterable)}, except it appends
* on a preexisting {@link StringBuilder}. The result value is that StringBuilder.
*/
public static <T> StringBuilder joinOn(StringBuilder sb,
Iterable<? extends T> iterable,
BiConsumer<? super StringBuilder, ? super T> appendItem,
String delimiter) {
boolean first = true;
for (T t : iterable) {
if (first) {
first = false;
} else {
sb.append(delimiter);
}
appendItem.accept(sb, t);
}
return sb;
}
public static @NonNull StringBuilder joinCharsIntoStringBuilder(List<Chars> lines, String delimiter) {
return joinOn(
new StringBuilder(),
lines,
(buf, line) -> line.appendChars(buf),
delimiter
);
}
/**
* Merge the second map into the first. If some keys are in common,
* merge them using the merge function, like {@link Map#merge(Object, Object, BiFunction)}.
*/
public static <K, V> void mergeMaps(Map<K, V> result, Map<K, V> other, BinaryOperator<V> mergeFun) {
for (K otherKey : other.keySet()) {
V otherInfo = other.get(otherKey); // non-null
result.merge(otherKey, otherInfo, mergeFun);
}
}
public static @NonNull <T> List<T> makeUnmodifiableAndNonNull(@Nullable List<? extends T> list) {
if (list instanceof PSequence) {
return (List<T>) list;
}
return list == null || list.isEmpty() ? emptyList()
: Collections.unmodifiableList(list);
}
}
| 23,157 | 32.562319 | 156 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/BaseResultProducingCloseable.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import java.io.Closeable;
import java.util.function.Consumer;
/**
* Base class for an autocloseable that produce a result once it has
* been closed. None of the methods of this class are synchronized.
*
* @param <T> Type of the result
*/
public abstract class BaseResultProducingCloseable<T> implements AutoCloseable {
private boolean closed;
protected final void ensureOpen() {
AssertionUtil.validateState(!closed, "Listener has been closed");
}
/**
* Returns the result.
*
* @throws IllegalStateException If this instance has not been closed yet
*/
public final T getResult() {
AssertionUtil.validateState(closed, "Cannot get result before listener is closed");
return getResultImpl();
}
/** Produce the final result. */
protected abstract T getResultImpl();
/**
* Close this object. Idempotent.
*
* @implNote Override {@link #closeImpl()} instead.
*/
@Override
public final void close() {
if (!closed) {
closed = true;
closeImpl();
}
}
/**
* Close this closeable as per the contract of {@link Closeable#close()}.
* Called exactly once. By default does nothing.
*/
protected void closeImpl() {
// override
}
public static <U, C extends BaseResultProducingCloseable<U>> U using(C closeable, Consumer<? super C> it) {
try {
it.accept(closeable);
} finally {
closeable.close();
}
return closeable.getResult();
}
}
| 1,701 | 24.029412 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/Predicate.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
import net.sourceforge.pmd.annotation.Experimental;
/**
* Simple predicate of one argument.
*
* @param <T> the type of the input to the predicate
*/
// TODO java8 - replace with java.util.function.Predicate
@Experimental
public interface Predicate<T> {
boolean test(T t);
}
| 407 | 19.4 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/OptionalBool.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util;
/** Represents a boolean that may not be present. Use as a non-null type. */
public enum OptionalBool {
NO, UNKNOWN, YES;
/**
* Returns the logical complement.
* <pre>{@code
* yes -> no
* unk -> unk
* no -> yes
* }</pre>
*/
public OptionalBool complement() {
switch (this) {
case YES:
return NO;
case NO:
return YES;
default:
return this;
}
}
public static OptionalBool max(OptionalBool a, OptionalBool b) {
return a.compareTo(b) > 0 ? a : b;
}
public static OptionalBool min(OptionalBool a, OptionalBool b) {
return a.compareTo(b) < 0 ? a : b;
}
/**
* If both values are the same, return it. Otherwise return UNKNOWN.
* <pre>{@code
* yes, yes -> yes
* no, no -> no
* everything else -> unk
* }</pre>
*/
public static OptionalBool join(OptionalBool a, OptionalBool b) {
return a != b ? UNKNOWN : a;
}
/** Returns true this is not {@link #UNKNOWN}. */
public boolean isKnown() {
return this != UNKNOWN;
}
/** Returns true if this is {@link #YES}. */
public boolean isTrue() {
return this == YES;
}
/** Returns either YES or NO depending on the given boolean. */
public static OptionalBool definitely(boolean a) {
return a ? YES : NO;
}
public static OptionalBool unless(boolean a) {
return a ? NO : YES;
}
}
| 1,628 | 22.608696 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/XmlTreeRenderer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
/**
* Renders a tree to XML. The resulting document is as close as possible
* to the representation PMD uses to run XPath queries on nodes. This
* allows the same XPath queries to match, in theory (it would depend
* on the XPath engine used I believe).
*/
@Experimental
public final class XmlTreeRenderer implements TreeRenderer {
// See https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Name
private static final String XML_START_CHAR = "[:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x{2FF}\\x{370}-\\x{37D}\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFFD}\\x{10000}-\\x{EFFFF}]";
private static final String XML_CHAR = "[" + XML_START_CHAR + ".\\-0-9\\xB7\\x{0300}-\\x{036F}\\x{203F}-\\x{2040}]";
private static final Pattern XML_NAME = Pattern.compile(XML_START_CHAR + XML_CHAR + "*");
private final XmlRenderingConfig strategy;
private final char attrDelim;
/*
TODO it's unclear to me how the strong typing of XPath 2.0 would
impact XPath queries run on the output XML. PMD maps attributes
to typed values, the XML only has untyped strings.
OTOH users should expect differences, and it's even documented
on this class.
*/
/**
* Creates a new XML renderer.
*
* @param strategy Strategy to parameterize the output of this instance
*/
public XmlTreeRenderer(XmlRenderingConfig strategy) {
this.strategy = strategy;
this.attrDelim = strategy.singleQuoteAttributes ? '\'' : '"';
}
/**
* Creates a new XML renderer with a default configuration.
*/
public XmlTreeRenderer() {
this(new XmlRenderingConfig());
}
/**
* {@inheritDoc}
*
* <p>Each node of the AST has a corresponding XML element, whose
* name and attributes are the one the node presents in XPath queries.
*
* @param node {@inheritDoc}
* @param out {@inheritDoc}
*
* @throws IllegalArgumentException If some node has attributes or
* a name that is not a valid XML name
*/
@Override
public void renderSubtree(Node node, Appendable out) throws IOException {
if (strategy.renderProlog) {
renderProlog(out);
}
renderSubtree(0, node, out);
out.append(strategy.lineSeparator);
}
private void renderProlog(Appendable out) throws IOException {
out.append("<?xml version=").append(attrDelim).append("1.0").append(attrDelim)
.append(" encoding=").append(attrDelim).append("UTF-8").append(attrDelim)
.append(" ?>").append(strategy.lineSeparator);
}
private void renderSubtree(int depth, Node node, Appendable out) throws IOException {
String eltName = node.getXPathNodeName();
checkValidName(eltName);
indent(depth, out).append('<').append(eltName);
Map<String, String> attributes = strategy.getXmlAttributes(node);
for (String attrName : attributes.keySet()) {
appendAttribute(out, attrName, attributes.get(attrName));
}
if (node.getNumChildren() == 0) {
out.append(" />");
return;
}
out.append(">");
for (int i = 0; i < node.getNumChildren(); i++) {
out.append(strategy.lineSeparator);
renderSubtree(depth + 1, node.getChild(i), out);
}
out.append(strategy.lineSeparator);
indent(depth, out).append("</").append(eltName).append('>');
}
private void appendAttribute(Appendable out, String name, String value) throws IOException {
checkValidName(name);
out.append(' ')
.append(name)
.append('=')
.append(attrDelim)
.append(escapeXmlAttribute(value, strategy.singleQuoteAttributes))
.append(attrDelim);
}
private void checkValidName(String name) {
if (!isValidXmlName(name) || isReservedXmlName(name)) {
throw new IllegalArgumentException(name + " is not a valid XML name");
}
}
private Appendable indent(int depth, Appendable out) throws IOException {
while (depth-- > 0) {
out.append(strategy.indentString);
}
return out;
}
private static String escapeXmlText(String xml) {
return xml.replaceAll("<", "<")
.replaceAll("&", "&");
}
private static String escapeXmlAttribute(String xml, boolean isSingleQuoted) {
return isSingleQuoted ? escapeXmlText(xml).replaceAll("'", "'")
: escapeXmlText(xml).replaceAll("\"", """);
}
private static boolean isValidXmlName(String xml) {
return XML_NAME.matcher(xml).matches();
}
private static boolean isReservedXmlName(String xml) {
return StringUtils.startsWithIgnoreCase(xml, "xml");
}
/**
* A strategy to parameterize an {@link XmlTreeRenderer}.
*/
@Experimental
public static class XmlRenderingConfig {
private String indentString = " ";
private String lineSeparator = System.lineSeparator();
private boolean singleQuoteAttributes = true;
private boolean renderProlog = true;
private Map<String, String> getXmlAttributes(Node node) {
Map<String, String> attrs = new TreeMap<>();
Iterator<Attribute> iter = node.getXPathAttributesIterator();
while (iter.hasNext()) {
Attribute next = iter.next();
if (takeAttribute(node, next)) {
try {
attrs.put(next.getName(), next.getStringValue());
} catch (Exception e) {
handleAttributeFetchException(next, e);
}
}
}
return attrs;
}
/**
* Handle an exception that occurred while fetching the value
* of an attribute. The default does nothing, it's meant to be
* overridden if you want to handle it.
*
* @param attr Attribute for which the fetch failed
* @param e Exception that occurred
*/
protected void handleAttributeFetchException(Attribute attr, Exception e) {
// to be overridden
}
/**
* Returns true if the attribute should be included in the element
* corresponding to the given node. Subclasses can override this
* method to filter out some attributes.
*
* @param node Node owning the attribute
* @param attribute Attribute to test
*/
protected boolean takeAttribute(Node node, Attribute attribute) {
return true;
}
/**
* Sets the string that should be used to separate lines. The
* default is the platform-specific line separator. The following
* special values are interpreted specially: {@code CR}, {@code CRLF},
* {@code LF}, {@code \r}, {@code \r\n} and {@code \n}. The latter
* three use literal backslashes and are interpreted like Java
* escapes. The former three are named aliases for the same.
*
* @throws NullPointerException If the argument is null
*/
public XmlRenderingConfig lineSeparator(String lineSeparator) {
this.lineSeparator = interpretLineSep(lineSeparator);
return this;
}
private static String interpretLineSep(String lineSeparator) {
switch (lineSeparator) {
case "CR":
case "\\r":
return "\r";
case "CRLF":
case "\\r\\n":
return "\r\n";
case "LF":
case "\\n":
return "\n";
default:
return lineSeparator;
}
}
/**
* Sets the delimiters use for attribute values. The default is
* to use single quotes.
*
* @param useSingleQuote True for single quotes, false for double quotes
*/
public XmlRenderingConfig singleQuoteAttributes(boolean useSingleQuote) {
this.singleQuoteAttributes = useSingleQuote;
return this;
}
/**
* Sets whether to render an XML prolog or not. The default is
* true.
*/
public XmlRenderingConfig renderProlog(boolean renderProlog) {
this.renderProlog = renderProlog;
return this;
}
/**
* Sets the string that should be used to indent children elements.
* The default is four spaces.
*
* @throws NullPointerException If the argument is null
*/
public XmlRenderingConfig indentWith(String indentString) {
this.indentString = Objects.requireNonNull(indentString);
return this;
}
}
}
| 9,556 | 32.299652 | 268 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeRenderer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.io.IOException;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
/**
* An object that can export a tree to an external text format.
*
* @see XmlTreeRenderer
*/
@Experimental
public interface TreeRenderer {
/**
* Appends the subtree rooted at the given node on the provided
* output writer. The implementation is free to filter out some
* nodes from the subtree.
*
* @param node Node to render
* @param out Object onto which the output is appended
*
* @throws IOException If an IO error occurs while appending to the output
*/
void renderSubtree(Node node, Appendable out) throws IOException;
}
| 849 | 23.285714 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeRendererDescriptorImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.util.Collections;
import java.util.Set;
import net.sourceforge.pmd.properties.AbstractPropertySource;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertySource;
abstract class TreeRendererDescriptorImpl implements TreeRendererDescriptor {
private final String id;
private final String description;
protected TreeRendererDescriptorImpl(String id, String description) {
this.id = id;
this.description = description;
}
@Override
public PropertySource newPropertyBundle() {
return new PropertyBundle(id, availableDescriptors());
}
protected Set<PropertyDescriptor<?>> availableDescriptors() {
return Collections.emptySet();
}
@Override
public String id() {
return id;
}
@Override
public String description() {
return description;
}
@Override
public String toString() {
return "TreeDescriptorImpl{"
+ "id='" + id + '\''
+ ", description='" + description + '\''
+ '}';
}
private static class PropertyBundle extends AbstractPropertySource {
private final String name;
PropertyBundle(String name,
Set<PropertyDescriptor<?>> available) {
this.name = name;
for (PropertyDescriptor<?> p : available) {
definePropertyDescriptor(p);
}
}
@Override
public String getName() {
return name;
}
@Override
protected String getPropertySourceType() {
return "tree renderer";
}
}
}
| 1,825 | 22.410256 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExportConfiguration.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.nio.file.Path;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.AbstractConfiguration;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
public class TreeExportConfiguration extends AbstractConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(TreeExportConfiguration.class);
private String format = "xml";
private Language language = LanguageRegistry.PMD.getLanguageById("java");
private Properties properties = new Properties();
private Properties languageProperties = new Properties();
private Path file;
private boolean readStdin;
private MessageReporter messageReporter = new SimpleMessageReporter(LOG);
public String getFormat() {
return format;
}
public Language getLanguage() {
return language;
}
public Properties getProperties() {
return properties;
}
public Path getFile() {
return file;
}
public Properties getLanguageProperties() {
return languageProperties;
}
public boolean isReadStdin() {
return readStdin;
}
public void setFormat(String format) {
this.format = format;
}
public void setLanguage(Language language) {
this.language = language;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setLanguageProperties(Properties properties) {
this.languageProperties = properties;
}
public void setFile(Path file) {
this.file = file;
}
public void setReadStdin(boolean readStdin) {
this.readStdin = readStdin;
}
public MessageReporter getMessageReporter() {
return messageReporter;
}
public void setMessageReporter(MessageReporter messageReporter) {
this.messageReporter = messageReporter;
}
}
| 2,254 | 24.91954 | 93 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeRenderers.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
import net.sourceforge.pmd.properties.PropertySource;
import net.sourceforge.pmd.util.treeexport.XmlTreeRenderer.XmlRenderingConfig;
/**
* Entry point to fetch and register tree renderers. This API is meant
* to be be integrated in tools that operate on tree descriptors generically.
* For that reason the standard descriptors provided by PMD and their
* properties are not public.
*
* @see #findById(String)
* @see #register(TreeRendererDescriptor)
*/
@Experimental
public final class TreeRenderers {
// descriptors are test only
static final PropertyDescriptor<Boolean> XML_RENDER_PROLOG =
PropertyFactory.booleanProperty("renderProlog")
.desc("True to output a prolog")
.defaultValue(true)
.build();
static final PropertyDescriptor<Boolean> XML_USE_SINGLE_QUOTES =
PropertyFactory.booleanProperty("singleQuoteAttributes")
.desc("Use single quotes to delimit attribute values")
.defaultValue(true)
.build();
static final PropertyDescriptor<String> XML_LINE_SEPARATOR =
PropertyFactory.stringProperty("lineSeparator")
.desc("Line separator to use. The default is platform-specific. "
+ "The values 'CR', 'CRLF', 'LF', '\\r', '\\r\\n' and '\\n' can be used "
+ "to represent a carriage return, line feed and their combination more easily.")
.defaultValue(System.lineSeparator())
.build();
static final PropertyDescriptor<Boolean> XML_RENDER_COMMON_ATTRIBUTES =
PropertyFactory.booleanProperty("renderCommonAttributes")
.desc("True to render attributes like BeginLine, EndLine, etc.")
.defaultValue(false)
.build();
static final TreeRendererDescriptor XML =
new TreeRendererDescriptorImpl("xml", "XML format with the same structure as the one used in XPath") {
private final Set<PropertyDescriptor<?>> myDescriptors
= Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.<PropertyDescriptor<?>>asList(
XML_USE_SINGLE_QUOTES, XML_LINE_SEPARATOR, XML_RENDER_PROLOG, XML_RENDER_COMMON_ATTRIBUTES
)));
@Override
protected Set<PropertyDescriptor<?>> availableDescriptors() {
return myDescriptors;
}
@Override
public TreeRenderer produceRenderer(final PropertySource properties) {
XmlRenderingConfig config =
new XmlRenderingConfig() {
private final List<String> excluded = Arrays.asList("BeginLine", "BeginColumn", "EndLine", "EndColumn", "SingleLine", "FindBoundary");
@Override
protected boolean takeAttribute(Node node, Attribute attribute) {
return properties.getProperty(XML_RENDER_COMMON_ATTRIBUTES)
|| !excluded.contains(attribute.getName());
}
}
.singleQuoteAttributes(properties.getProperty(XML_USE_SINGLE_QUOTES))
.renderProlog(properties.getProperty(XML_RENDER_PROLOG))
.lineSeparator(properties.getProperty(XML_LINE_SEPARATOR));
return new XmlTreeRenderer(config);
}
};
private static final Map<String, TreeRendererDescriptor> REGISTRY = new ConcurrentHashMap<>();
static {
List<TreeRendererDescriptor> builtinDescriptors = Arrays.asList(XML, TextTreeRenderer.DESCRIPTOR);
for (TreeRendererDescriptor descriptor : builtinDescriptors) {
REGISTRY.put(descriptor.id(), descriptor);
}
}
private TreeRenderers() {
}
/**
* Returns the renderer descriptor registered by the given ID.
* Returns null if not found, or the id is null.
*
* @param id ID of the renderer to find
*
* @return The descriptor, or null
*/
public static TreeRendererDescriptor findById(String id) {
synchronized (REGISTRY) {
return REGISTRY.get(id);
}
}
/**
* Returns the set of renderers currently registered. Order is
* undefined.
*/
public static Collection<TreeRendererDescriptor> registeredRenderers() {
return Collections.unmodifiableCollection(REGISTRY.values());
}
/**
* Registers the given renderer. If registration succeeds (the ID
* is not already associated to a descriptor), the descriptor
* will be available with {@link #findById(String)}.
*
* @param descriptor Descriptor to register
*
* @return True if the registration succeeded, false if there was
* already a registered renderer with the given ID.
*/
public static boolean register(TreeRendererDescriptor descriptor) {
synchronized (REGISTRY) {
if (REGISTRY.containsKey(descriptor.id())) {
return false;
}
REGISTRY.put(descriptor.id(), descriptor);
}
return true;
}
}
| 5,928 | 36.289308 | 158 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/Io.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.io.InputStream;
import java.io.PrintStream;
/**
* Abstraction over system streams. Useful to unit-test a CLI program.
*
* @author Clément Fournier
*/
final class Io {
public final PrintStream stdout;
public final PrintStream stderr;
public final InputStream stdin;
Io(PrintStream stdout, PrintStream stderr, InputStream stdin) {
this.stdout = stdout;
this.stderr = stderr;
this.stdin = stdin;
}
public static Io system() {
return new Io(System.out, System.err, System.in);
}
}
| 695 | 21.451613 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeRendererDescriptor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.properties.PropertySource;
/**
* Describes the configuration options of a specific {@link TreeRenderer}.
*
* @see TreeRenderers
*/
@Experimental
public interface TreeRendererDescriptor {
/**
* Returns a new property bundle, that can be used to configure
* the output of {@link #produceRenderer(PropertySource)}. Properties
* supported by the renderer are already registered on the returned
* bundle.
*/
PropertySource newPropertyBundle();
/**
* Returns the ID of this renderer, used to select it.
* The ID of a descriptor should never change.
*
* @see TreeRenderers#findById(String)
*/
String id();
/**
* Returns a short description of the format of this renderer's output.
*/
String description();
/**
* Builds a new renderer from the given properties.
*
* @param properties A property bundle, that should have been produced by
* {@link #newPropertyBundle()}.
*/
TreeRenderer produceRenderer(PropertySource properties);
}
| 1,285 | 23.730769 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collections;
import java.util.Map.Entry;
import java.util.Properties;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.LanguagePropertyBundle;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertySource;
@Experimental
public class TreeExporter {
private final TreeExportConfiguration configuration;
private final Io io;
public TreeExporter(final TreeExportConfiguration configuration) {
this(configuration, Io.system());
}
TreeExporter(final TreeExportConfiguration configuration, final Io io) {
this.configuration = configuration;
this.io = io;
}
public void export() throws IOException {
TreeRendererDescriptor descriptor = TreeRenderers.findById(configuration.getFormat());
if (descriptor == null) {
throw this.bail("Unknown format '" + configuration.getFormat() + "'");
}
PropertySource bundle = parseProperties(descriptor.newPropertyBundle(), configuration.getProperties());
LanguagePropertyBundle langProperties = parseProperties(configuration.getLanguage().newPropertyBundle(), configuration.getLanguageProperties());
LanguageRegistry lang = LanguageRegistry.PMD.getDependenciesOf(configuration.getLanguage());
try (LanguageProcessorRegistry lpRegistry = LanguageProcessorRegistry.create(lang,
Collections.singletonMap(configuration.getLanguage(), langProperties),
configuration.getMessageReporter())) {
run(lpRegistry, descriptor.produceRenderer(bundle));
}
}
private void run(LanguageProcessorRegistry langRegistry, final TreeRenderer renderer) throws IOException {
printWarning();
LanguageVersion langVersion = configuration.getLanguage().getDefaultVersion();
@SuppressWarnings("PMD.CloseResource")
LanguageProcessor processor = langRegistry.getProcessor(configuration.getLanguage());
Parser parser = processor.services().getParser();
@SuppressWarnings("PMD.CloseResource")
TextFile textFile;
if (configuration.isReadStdin()) {
io.stderr.println("Reading from stdin...");
textFile = TextFile.forReader(readFromSystemIn(), FileId.STDIN, langVersion);
} else {
textFile = TextFile.forPath(configuration.getFile(), configuration.getSourceEncoding(), langVersion);
}
// disable warnings for deprecated attributes
Slf4jSimpleConfiguration.disableLogging(Attribute.class);
try (TextDocument textDocument = TextDocument.create(textFile)) {
ParserTask task = new ParserTask(textDocument, SemanticErrorReporter.noop(), langRegistry);
RootNode root = parser.parse(task);
renderer.renderSubtree(root, io.stdout);
}
}
private Reader readFromSystemIn() {
return new BufferedReader(new InputStreamReader(io.stdin));
}
private void printWarning() {
io.stderr.println("-------------------------------------------------------------------------------");
io.stderr.println("This command line utility is experimental. It might change at any time without");
io.stderr.println("prior notice.");
io.stderr.println("-------------------------------------------------------------------------------");
}
private <T extends PropertySource> T parseProperties(T bundle, Properties properties) {
for (Entry<Object, Object> prop : properties.entrySet()) {
PropertyDescriptor<?> d = bundle.getPropertyDescriptor(prop.getKey().toString());
if (d == null) {
throw bail("Unknown property '" + prop.getKey() + "'");
}
setProperty(d, bundle, prop.getValue().toString());
}
return bundle;
}
private <T> void setProperty(PropertyDescriptor<T> descriptor, PropertySource bundle, String value) {
bundle.setProperty(descriptor, descriptor.valueFrom(value));
}
private AbortedException bail(String message) {
io.stderr.println(message);
io.stderr.println("Use --help for usage information");
return new AbortedException();
}
private static final class AbortedException extends RuntimeException {
private static final long serialVersionUID = -1925142332978792215L;
}
}
| 5,541 | 40.669173 | 155 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TextTreeRenderer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.treeexport;
import java.io.IOException;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.properties.AbstractPropertySource;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
import net.sourceforge.pmd.properties.PropertySource;
/**
* A simple recursive printer. Output looks like so:
*
* <pre>
*
* +- LocalVariableDeclaration
* +- Type
* | +- PrimitiveType
* +- VariableDeclarator
* +- VariableDeclaratorId
* +- VariableInitializer
* +- 1 child not shown
*
* </pre>
*
* or
*
* <pre>
*
* └─ LocalVariableDeclaration
* ├─ Type
* │ └─ PrimitiveType
* └─ VariableDeclarator
* ├─ VariableDeclaratorId
* └─ VariableInitializer
* └─ 1 child not shown
*
* </pre>
*
*
* By default just prints the structure, like shown above. You can
* configure it to render nodes differently by overriding {@link #appendNodeInfoLn(Appendable, Node)}.
*/
@Experimental
public class TextTreeRenderer implements TreeRenderer {
static final TreeRendererDescriptor DESCRIPTOR = new TreeRendererDescriptor() {
private final PropertyDescriptor<Boolean> onlyAscii =
PropertyFactory.booleanProperty("onlyAsciiChars")
.defaultValue(false)
.desc("Use only ASCII characters in the structure")
.build();
private final PropertyDescriptor<Integer> maxLevel =
PropertyFactory.intProperty("maxLevel")
.defaultValue(-1)
.desc("Max level on which to recurse. Negative means unbounded")
.build();
@Override
public PropertySource newPropertyBundle() {
PropertySource bundle = new AbstractPropertySource() {
@Override
protected String getPropertySourceType() {
return "tree renderer";
}
@Override
public String getName() {
return "text";
}
};
bundle.definePropertyDescriptor(onlyAscii);
bundle.definePropertyDescriptor(maxLevel);
return bundle;
}
@Override
public String id() {
return "text";
}
@Override
public String description() {
return "Text renderer";
}
@Override
public TreeRenderer produceRenderer(PropertySource properties) {
return new TextTreeRenderer(properties.getProperty(onlyAscii), properties.getProperty(maxLevel));
}
};
private final Strings str;
private final int maxLevel;
/**
* Creates a new text renderer.
*
* @param onlyAscii Whether to output the skeleton of the tree with
* only ascii characters. If false, uses unicode chars
* like '├'
* @param maxLevel Max level on which to recurse. Negative means
* unbounded. If the max level is reached, a placeholder
* is dumped, like "1 child is not shown". This is
* controlled by {@link #appendBoundaryForNodeLn(Node, Appendable, String)}.
*/
public TextTreeRenderer(boolean onlyAscii, int maxLevel) {
this.str = onlyAscii ? Strings.ASCII : Strings.UNICODE;
this.maxLevel = maxLevel;
}
@Override
public void renderSubtree(Node node, Appendable out) throws IOException {
printInnerNode(node, out, 0, "", true);
}
private String childPrefix(String prefix, boolean isTail) {
return prefix + (isTail ? str.gap : str.verticalEdge);
}
protected final void appendIndent(Appendable out, String prefix, boolean isTail) throws IOException {
out.append(prefix).append(isTail ? str.tailFork : str.fork);
}
/**
* Append info about the node. The indent has already been appended.
* This should end with a newline. The default just appends the name
* of the node, and no other information.
*/
protected void appendNodeInfoLn(Appendable out, Node node) throws IOException {
out.append(node.getXPathNodeName()).append("\n");
}
private void printInnerNode(Node node,
Appendable out,
int level,
String prefix,
boolean isTail) throws IOException {
appendIndent(out, prefix, isTail);
appendNodeInfoLn(out, node);
if (level == maxLevel) {
if (node.getNumChildren() > 0) {
appendBoundaryForNodeLn(node, out, childPrefix(prefix, isTail));
}
} else {
int n = node.getNumChildren() - 1;
String childPrefix = childPrefix(prefix, isTail);
for (int i = 0; i < node.getNumChildren(); i++) {
Node child = node.getChild(i);
printInnerNode(child, out, level + 1, childPrefix, i == n);
}
}
}
protected void appendBoundaryForNodeLn(Node node, Appendable out, String indentStr) throws IOException {
appendIndent(out, indentStr, true);
if (node.getNumChildren() == 1) {
out.append("1 child is not shown");
} else {
out.append(String.valueOf(node.getNumChildren())).append(" children are not shown");
}
out.append('\n');
}
private static final class Strings {
private static final Strings ASCII = new Strings(
"+- ",
"+- ",
"| ",
" "
);
private static final Strings UNICODE = new Strings(
"└─ ",
"├─ ",
"│ ",
" "
);
private final String tailFork;
private final String fork;
private final String verticalEdge;
private final String gap;
private Strings(String tailFork, String fork, String verticalEdge, String gap) {
this.tailFork = tailFork;
this.fork = fork;
this.verticalEdge = verticalEdge;
this.gap = gap;
}
}
}
| 6,493 | 29.777251 | 109 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/ResourceLoader.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import java.io.InputStream;
/**
* Helper class for retrieving resources relative to the installation.
*
* @author Stuart Turton
*/
public class ResourceLoader {
public InputStream getResourceStream(String path) throws java.io.IOException {
ClassLoader cl = this.getClass().getClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
InputStream stream = cl.getResourceAsStream(path);
if (stream == null) {
throw new java.io.IOException("Resource not found: " + path);
}
return stream;
}
}
| 736 | 24.413793 | 82 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/ResourceResolver.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
public class ResourceResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
if (null == href || href.length() == 0) {
return null; // will make Oracle XSLT processor explode,
// even though it's correct
}
try {
String resource = href;
ResourceLoader loader = new ResourceLoader();
return new StreamSource(loader.getResourceStream(resource), resource);
} catch (Exception ex) {
throw new TransformerException(ex);
}
}
}
| 916 | 31.75 | 82 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/DBMSMetadata.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import java.net.MalformedURLException;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Wrap JDBC connection for use by PMD: {@link DBURI} parameters specify the
* source code to be passed to PMD.
*
* @author sturton
*/
public class DBMSMetadata {
/**
* Local logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(DBMSMetadata.class);
/**
* Optional DBType property specifying a query to fetch the Source Objects
* from the database.
*
* <p>
* If the DBType lacks this property, then the standard
* DatabaseMetaData.getProcedures method is used.
* </p>
*/
private static final String GET_SOURCE_OBJECTS_STATEMENT = "getSourceObjectsStatement";
/**
* Essential DBType property specifying a CallableStatement to retrieve the
* Source Object's code from the database.
*
* <p>
* <b>If the DBType lacks this property, there is no DatabaseMetaData method
* to fallback to</b>.
* </p>
*/
private static final String GET_SOURCE_CODE_STATEMENT = "getSourceCodeStatement";
/**
* DBURI
*/
protected DBURI dburi = null;
/**
* Connection management
*/
protected Connection connection = null;
/**
* Procedural statement to return list of source code objects.
*/
protected String returnSourceCodeObjectsStatement = null;
/**
* Procedural statement to return source code.
*/
protected String returnSourceCodeStatement = null;
/**
* CallableStatement to return source code.
*/
protected CallableStatement callableStatement = null;
/**
* {@link java.sql.Types} value representing the type returned by
* {@link #callableStatement}
*
* <b>Currently only java.sql.Types.String and java.sql.Types.Clob are
* supported</b>
*/
protected int returnType = java.sql.Types.CLOB;
/* constructors */
/**
* Minimal constructor
*
* @param c
* JDBC Connection
* @throws SQLException
*/
public DBMSMetadata(Connection c) throws SQLException {
connection = c;
}
/**
* Define database connection and source code to retrieve with explicit
* database username and password.
*
* @param user
* Database username
* @param password
* Database password
* @param dbURI
* {@link DBURI } containing JDBC connection plus parameters to
* specify source code.
* @throws SQLException
* on failing to create JDBC connection
* @throws MalformedURLException
* on attempting to connect with malformed JDBC URL
* @throws ClassNotFoundException
* on failing to locate the JDBC driver class.
*/
public DBMSMetadata(String user, String password, DBURI dbURI)
throws SQLException, MalformedURLException, ClassNotFoundException {
String urlString = init(dbURI);
Properties mergedProperties = dbURI.getDbType().getProperties();
Map<String, String> dbURIParameters = dbURI.getParameters();
mergedProperties.putAll(dbURIParameters);
mergedProperties.put("user", user);
mergedProperties.put("password", password);
connection = DriverManager.getConnection(urlString, mergedProperties);
LOG.debug("we have a connection={}", connection);
}
/**
* Define database connection and source code to retrieve with database
* properties.
*
* @param properties
* database settings such as database username, password
* @param dbURI
* {@link DBURI } containing JDBC connection plus parameters to
* specify source code.
* @throws SQLException
* on failing to create JDBC connection
* @throws MalformedURLException
* on attempting to connect with malformed JDBC URL
* @throws ClassNotFoundException
* on failing to locate the JDBC driver class.
*/
public DBMSMetadata(Properties properties, DBURI dbURI)
throws SQLException, MalformedURLException, ClassNotFoundException {
String urlString = init(dbURI);
Properties mergedProperties = dbURI.getDbType().getProperties();
Map<String, String> dbURIParameters = dbURI.getParameters();
mergedProperties.putAll(dbURIParameters);
mergedProperties.putAll(properties);
LOG.debug("Retrieving connection for urlString={}", urlString);
connection = DriverManager.getConnection(urlString, mergedProperties);
LOG.debug("Secured Connection for DBURI={}", dbURI);
}
/**
* Define database connection and source code to retrieve.
*
* <p>
* This constructor is reliant on database username and password embedded in
* the JDBC URL or defaulted from the {@link DBURI}'s <code>DriverType</code>.
* </p>
*
* @param dbURI
* {@link DBURI } containing JDBC connection plus parameters to
* specify source code.
* @throws SQLException
* on failing to create JDBC connection
* @throws ClassNotFoundException
* on failing to locate the JDBC driver class.
*/
public DBMSMetadata(DBURI dbURI) throws SQLException, ClassNotFoundException {
String urlString = init(dbURI);
Properties dbURIProperties = dbURI.getDbType().getProperties();
Map<String, String> dbURIParameters = dbURI.getParameters();
/*
* Overwrite any DBType properties with DBURI parameters allowing JDBC
* connection properties to be inherited from DBType or passed as DBURI
* parameters
*/
dbURIProperties.putAll(dbURIParameters);
connection = DriverManager.getConnection(urlString, dbURIProperties);
}
/**
* Return JDBC Connection for direct JDBC access to the specified database.
*
* @return I=JDBC Connection
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
return connection;
}
private String init(DBURI dbURI) throws ClassNotFoundException {
this.dburi = dbURI;
this.returnSourceCodeObjectsStatement = dbURI.getDbType().getProperties()
.getProperty(GET_SOURCE_OBJECTS_STATEMENT);
this.returnSourceCodeStatement = dbURI.getDbType().getProperties().getProperty(GET_SOURCE_CODE_STATEMENT);
this.returnType = dbURI.getSourceCodeType();
LOG.debug("returnSourceCodeStatement={}, returnType={}", returnSourceCodeStatement, returnType);
String driverClass = dbURI.getDriverClass();
String urlString = dbURI.getURL().toString();
LOG.debug("driverClass={}, urlString={}", driverClass, urlString);
Class.forName(driverClass);
LOG.debug("Located class for driverClass={}", driverClass);
return urlString;
}
/**
* Return source code text from the database.
*
* @param sourceObject object
* @return source code
* @throws SQLException
*/
public java.io.Reader getSourceCode(SourceObject sourceObject) throws SQLException {
return getSourceCode(sourceObject.getType(), sourceObject.getName(), sourceObject.getSchema());
}
/**
* return source code text
*
* @param objectType
* @param name
* Source Code name
* @param schema
* Owner of the code
* @return Source code text.
* @throws SQLException
* on failing to retrieve the source Code text
*/
public java.io.Reader getSourceCode(String objectType, String name, String schema) throws SQLException {
Object result;
/*
* Only define callableStatement once and reuse it for subsequent calls
* to getSourceCode()
*/
if (null == callableStatement) {
LOG.trace("getSourceCode: returnSourceCodeStatement=\"{}\"", returnSourceCodeStatement);
LOG.trace("getSourceCode: returnType=\"{}\"", returnType);
callableStatement = getConnection().prepareCall(returnSourceCodeStatement);
callableStatement.registerOutParameter(1, returnType);
}
// set IN parameters
callableStatement.setString(2, objectType);
callableStatement.setString(3, name);
callableStatement.setString(4, schema);
//
// execute statement
callableStatement.executeUpdate();
// retrieve OUT parameters
result = callableStatement.getObject(1);
return (java.sql.Types.CLOB == returnType) ? ((Clob) result).getCharacterStream()
: new java.io.StringReader(result.toString());
}
/**
* Return all source code objects associated with any associated DBURI.
*
* @return
*/
public List<SourceObject> getSourceObjectList() {
if (null == dburi) {
LOG.warn("No dbUri defined - no further action possible");
return Collections.emptyList();
} else {
return getSourceObjectList(dburi.getLanguagesList(), dburi.getSchemasList(), dburi.getSourceCodeTypesList(),
dburi.getSourceCodeNamesList());
}
}
/**
* Return all source code objects associated with the specified languages,
* schemas, source code types and source code names.
*
* <p>
* Each parameter may be null and the appropriate field from any related
* DBURI is assigned, defaulting to the normal SQL wildcard expression
* ("%").
* </p>
*
* @param languages
* Optional list of languages to search for
* @param schemas
* Optional list of schemas to search for
* @param sourceCodeTypes
* Optional list of source code types to search for
* @param sourceCodeNames
* Optional list of source code names to search for
*/
public List<SourceObject> getSourceObjectList(List<String> languages, List<String> schemas,
List<String> sourceCodeTypes, List<String> sourceCodeNames) {
List<SourceObject> sourceObjectsList = new ArrayList<>();
List<String> searchLanguages = languages;
List<String> searchSchemas = schemas;
List<String> searchSourceCodeTypes = sourceCodeTypes;
List<String> searchSourceCodeNames = sourceCodeNames;
List<String> wildcardList = Arrays.asList("%");
/*
* Assign each search list to the first
*
* explicit parameter dburi field wildcard list
*
*/
if (null == searchLanguages) {
List<String> dbURIList = (null == dburi) ? null : dburi.getLanguagesList();
if (null == dbURIList || dbURIList.isEmpty()) {
searchLanguages = wildcardList;
} else {
searchLanguages = dbURIList;
}
}
if (null == searchSchemas) {
List<String> dbURIList = (null == dburi) ? null : dburi.getSchemasList();
if (null == dbURIList || dbURIList.isEmpty()) {
searchSchemas = wildcardList;
} else {
searchSchemas = dbURIList;
}
}
if (null == searchSourceCodeTypes) {
List<String> dbURIList = (null == dburi) ? null : dburi.getSourceCodeTypesList();
if (null == dbURIList || dbURIList.isEmpty()) {
searchSourceCodeTypes = wildcardList;
} else {
searchSourceCodeTypes = dbURIList;
}
}
if (null == searchSourceCodeNames) {
List<String> dbURIList = (null == dburi) ? null : dburi.getSourceCodeNamesList();
if (null == dbURIList || dbURIList.isEmpty()) {
searchSourceCodeNames = wildcardList;
} else {
searchSourceCodeNames = dbURIList;
}
}
try {
if (null != returnSourceCodeObjectsStatement) {
LOG.debug("Have bespoke returnSourceCodeObjectsStatement from DBURI: \"{}\"",
returnSourceCodeObjectsStatement);
try (PreparedStatement sourceCodeObjectsStatement = getConnection()
.prepareStatement(returnSourceCodeObjectsStatement)) {
for (String language : searchLanguages) {
for (String schema : searchSchemas) {
for (String sourceCodeType : searchSourceCodeTypes) {
for (String sourceCodeName : searchSourceCodeNames) {
sourceObjectsList.addAll(findSourceObjects(sourceCodeObjectsStatement, language, schema,
sourceCodeType, sourceCodeName));
}
}
}
}
}
} else {
// Use standard DatabaseMetaData interface
LOG.debug(
"Have dbUri - no returnSourceCodeObjectsStatement, reverting to DatabaseMetaData.getProcedures(...)");
DatabaseMetaData metadata = connection.getMetaData();
List<String> schemasList = dburi.getSchemasList();
for (String schema : schemasList) {
for (String sourceCodeName : dburi.getSourceCodeNamesList()) {
sourceObjectsList.addAll(findSourceObjectFromMetaData(metadata, schema, sourceCodeName));
}
}
}
LOG.trace("Identfied={} sourceObjects", sourceObjectsList.size());
return sourceObjectsList;
} catch (SQLException sqle) {
throw new RuntimeException("Problem collecting list of source code objects", sqle);
}
}
private List<SourceObject> findSourceObjectFromMetaData(DatabaseMetaData metadata,
String schema, String sourceCodeName) throws SQLException {
List<SourceObject> sourceObjectsList = new ArrayList<>();
/*
* public ResultSet getProcedures(String catalog ,
* String schemaPattern , String procedureNamePattern)
* throws SQLException
*/
try (ResultSet sourceCodeObjects = metadata.getProcedures(null, schema, sourceCodeName)) {
/*
* From Javadoc .... Each procedure description has the
* the following columns: PROCEDURE_CAT String =>
* procedure catalog (may be null) PROCEDURE_SCHEM
* String => procedure schema (may be null)
* PROCEDURE_NAME String => procedure name reserved for
* future use reserved for future use reserved for
* future use REMARKS String => explanatory comment on
* the procedure PROCEDURE_TYPE short => kind of
* procedure: procedureResultUnknown - Cannot determine
* if a return value will be returned procedureNoResult
* - Does not return a return value
* procedureReturnsResult - Returns a return value
* SPECIFIC_NAME String => The name which uniquely
* identifies this procedure within its schema.
*
* Oracle getProcedures actually returns these 8
* columns:- ResultSet "Matched Procedures" has 8
* columns and contains ...
* [PROCEDURE_CAT,PROCEDURE_SCHEM,PROCEDURE_NAME,NULL,
* NULL,NULL,REMARKS,PROCEDURE_TYPE
* ,null,PHPDEMO,ADD_JOB_HISTORY,null,null,null,
* Standalone procedure or function,1
* ,FETCHPERFPKG,PHPDEMO,BULKSELECTPRC,null,null,null,
* Packaged function,2
* ,FETCHPERFPKG,PHPDEMO,BULKSELECTPRC,null,null,null,
* Packaged procedure,1
* ,null,PHPDEMO,CITY_LIST,null,null,null,Standalone
* procedure or function,1
* ,null,PHPDEMO,EDDISCOUNT,null,null,null,Standalone
* procedure or function,2
* ,SELPKG_BA,PHPDEMO,EMPSELBULK,null,null,null,Packaged
* function,2
* ,SELPKG_BA,PHPDEMO,EMPSELBULK,null,null,null,Packaged
* procedure,1
* ,INSPKG,PHPDEMO,INSFORALL,null,null,null,Packaged
* procedure,1
* ,null,PHPDEMO,MYDOFETCH,null,null,null,Standalone
* procedure or function,2
* ,null,PHPDEMO,MYPROC1,null,null,null,Standalone
* procedure or function,1
* ,null,PHPDEMO,MYPROC2,null,null,null,Standalone
* procedure or function,1
* ,null,PHPDEMO,MYXAQUERY,null,null,null,Standalone
* procedure or function,1
* ,null,PHPDEMO,POLICY_VPDPARTS,null,null,null,
* Standalone procedure or function,2
* ,FETCHPERFPKG,PHPDEMO,REFCURPRC,null,null,null,
* Packaged procedure,1
* ,null,PHPDEMO,SECURE_DML,null,null,null,Standalone
* procedure or function,1 ... ]
*/
while (sourceCodeObjects.next()) {
LOG.trace("Located schema={},object_type={},object_name={}",
sourceCodeObjects.getString("PROCEDURE_SCHEM"),
sourceCodeObjects.getString("PROCEDURE_TYPE"),
sourceCodeObjects.getString("PROCEDURE_NAME"));
sourceObjectsList.add(new SourceObject(sourceCodeObjects.getString("PROCEDURE_SCHEM"),
sourceCodeObjects.getString("PROCEDURE_TYPE"),
sourceCodeObjects.getString("PROCEDURE_NAME"), null));
}
}
return sourceObjectsList;
}
private List<SourceObject> findSourceObjects(PreparedStatement sourceCodeObjectsStatement,
String language, String schema, String sourceCodeType, String sourceCodeName) throws SQLException {
List<SourceObject> sourceObjectsList = new ArrayList<>();
sourceCodeObjectsStatement.setString(1, language);
sourceCodeObjectsStatement.setString(2, schema);
sourceCodeObjectsStatement.setString(3, sourceCodeType);
sourceCodeObjectsStatement.setString(4, sourceCodeName);
LOG.debug(
"searching for language=\"{}\", schema=\"{}\", sourceCodeType=\"{}\", sourceCodeNames=\"{}\" ",
language, schema, sourceCodeType, sourceCodeName);
/*
* public ResultSet getProcedures(String catalog
* , String schemaPattern , String
* procedureNamePattern) throws SQLException
*/
try (ResultSet sourceCodeObjects = sourceCodeObjectsStatement.executeQuery()) {
/*
* From Javadoc .... Each procedure description
* has the the following columns: PROCEDURE_CAT
* String => procedure catalog (may be null)
* PROCEDURE_SCHEM String => procedure schema
* (may be null) PROCEDURE_NAME String =>
* procedure name reserved for future use
* reserved for future use reserved for future
* use REMARKS String => explanatory comment on
* the procedure PROCEDURE_TYPE short => kind of
* procedure: procedureResultUnknown - Cannot
* determine if a return value will be returned
* procedureNoResult - Does not return a return
* value procedureReturnsResult - Returns a
* return value SPECIFIC_NAME String => The name
* which uniquely identifies this procedure
* within its schema.
*/
while (sourceCodeObjects.next()) {
LOG.trace("Found schema={},object_type={},object_name={}",
sourceCodeObjects.getString("PROCEDURE_SCHEM"),
sourceCodeObjects.getString("PROCEDURE_TYPE"),
sourceCodeObjects.getString("PROCEDURE_NAME"));
sourceObjectsList
.add(new SourceObject(sourceCodeObjects.getString("PROCEDURE_SCHEM"),
sourceCodeObjects.getString("PROCEDURE_TYPE"),
sourceCodeObjects.getString("PROCEDURE_NAME"), null));
}
}
return sourceObjectsList;
}
}
| 21,142 | 38.667917 | 126 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/SourceObject.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.lang.Language;
/**
* Instantiate the fields required to retrieve {@link SourceCode}.
*
* @author sturton
*/
public class SourceObject {
private static final Logger LOG = LoggerFactory.getLogger(SourceObject.class);
/**
* Database Schema/Owner - SYS,SYSTEM,SCOTT
*
*/
String schema;
/**
* Source Code Name - DBMS_METADATA
*
*/
String name;
/**
* Source Code Type -
* FUNCTION,PROCEDURE,TRIGGER,PACKAGE,PACKAGE_BODY,TYPE,TYPE_BODY,JAVA_SOURCE.
*
*/
String type;
/**
* Source Code Revision - Optional revision/version
*
*/
String revision;
SourceObject(String schema, String type, String name, String revision) {
this.schema = schema;
this.type = type;
this.name = name;
this.revision = revision;
}
@Override
public String toString() {
return String.format("schema=\"%s\",type=\"%s\",name=\"%s\",revision=\"%s\"", this.getSchema(), this.getType(),
this.getName(), this.getRevision());
}
/**
* @return the schema
*/
public String getSchema() {
return schema;
}
/**
* @param schema
* the schema to set
*/
public void setSchema(String schema) {
this.schema = schema;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type
* the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the revision
*/
public String getRevision() {
return revision;
}
/**
* @param revision
* the revision to set
*/
public void setRevision(String revision) {
this.revision = revision;
}
/**
* Map the type to a file suffix associated with a {@link Language}
*
* @return inferred suffix
*/
public String getSuffixFromType() {
LOG.trace("Entering getSuffixFromType");
if (null == type || type.isEmpty()) {
return "";
} else if (type.toUpperCase(Locale.ROOT).contains("JAVA")) {
return ".java";
} else if (type.toUpperCase(Locale.ROOT).contains("TRIGGER")) {
return ".trg";
} else if (type.toUpperCase(Locale.ROOT).contains("FUNCTION")) {
return ".fnc";
} else if (type.toUpperCase(Locale.ROOT).contains("PROCEDURE")) {
return ".prc";
} else if (type.toUpperCase(Locale.ROOT).contains("PACKAGE_BODY")) {
return ".pkb";
} else if (type.toUpperCase(Locale.ROOT).contains("PACKAGE")) {
return ".pks";
} else if (type.toUpperCase(Locale.ROOT).contains("TYPE_BODY")) {
return ".tpb";
} else if (type.toUpperCase(Locale.ROOT).contains("TYPE")) {
return ".tps";
} else {
return "";
}
}
/**
* Gets the data source as a pseudo file name (faux-file). Adding a suffix
* matching the source object type ensures that the appropriate language
* parser is used.
*/
public String getPseudoFileName() {
return String.format("/Database/%s/%s/%s%s", getSchema(), getType(), getName(),
getSuffixFromType());
}
}
| 3,882 | 22.391566 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/DBURI.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide a single parameter to specify database objects to process.
*
* <p>
* Wrap JDBC settings for use by PMD: optional parameters specify the source
* code to be passed to PMD, or are inherited from the associated
* {@link DBType}.
* </p>
*
* <p>
* A DBURI is a <i>faux</i>-URI: it does not have a formal specification and
* comprises a JDBC(-ish) URL and an optional query, e.g.
* <code>jdbc : subprotocol [ : subname ] : connection details [ query ] </code>.
* </p>
*
* <p>
* The subprotocol and optional subname parts should be a valid DBType
* JDBC(-ish) URL jdbc:oracle:thin:username/password@//192.168.100.21:1521/ORCL
* JDBC(-ish) URL jdbc:thin:username/password@//192.168.100.21:1521/ORCL
* </p>
*
* <p>
* The query includes one or more of these:
* </p>
* <dl>
* <dt>characterset</dt>
* <dd>utf8</dd>
* <dt>languages</dt>
* <dd>comma-separated list of desired PMD languages</dd>
* <dt>schemas</dt>
* <dd>comma-separated list of database schemas</dd>
* <dt>sourcecodetypes</dt>
* <dd>comma-separated list of database source code types</dd>
* <dt>sourcecodenames</dt>
* <dd>comma-separated list of database source code names</dd>
* </dl>
*
* @see URI
* @author sturton
*/
public class DBURI {
private static final Logger LOG = LoggerFactory.getLogger(DBURI.class);
/**
* A JDBC URL with an associated query.
*
* Formats: jdbc:oracle:thin:[<user>/<password>]@//<host>[:<port>]/<service>
* jdbc:oracle:oci:[<user>/<password>]@//<host>[:<port>]/<service>
*
* Example: jdbc:oracle:thin:@//myserver.com/customer_db
* jdbc:oracle:oci:scott/tiger@//myserver.com:5521/customer_db
*/
private URI uri;
private DBType dbType;
private String url;
/**
* JDBC subprotocol
*/
private String subprotocol;
/**
* JDBC subname prefix
*/
private String subnamePrefix;
/**
* Parameters from URI
*/
private Map<String, String> parameters;
// Schema List - defaults to connecting user
private List<String> schemasList;
// Object Type List - potentially inferred from the JDBC URL
private List<String> sourceCodeTypesList;
// source Code Type List
private List<String> sourceCodeNamesList;
// Language List - potentially inferred from the JDBC URL
private List<String> languagesList;
// Driver Class - potentially inferred from the JDBC URL
private String driverClass;
// Database CharacterSet
private String characterSet;
// String to get objects - defaults inferred from the JDBC URL
private String sourceCodeTypes;
// String to get source code - defaults inferred from the JDBC URL
private String sourceCodeNames;
// languages to process - defaults inferred from the JDBC URL
private String languages;
// Return class for source code, mapped fron java.sql.Types
private int sourceCodeType;
/**
* Create DBURI from a string, combining a JDBC URL and query parameters.
*
* <p>
* From the JDBC URL component, infer:
* </p>
* <ul>
* <li>JDBC driver class</li>
* <li>supported languages</li>
* <li>default source code types</li>
* <li>default schemas</li>
* </ul>
*
* <p>
* From the query component, define these values, overriding any defaults:
* </p>
* <ul>
* <li>parsing language</li>
* <li>source code types</li>
* <li>schemas</li>
* <li>source code</li>
* </ul>
*
* @param string
* URL string
* @throws URISyntaxException
*/
public DBURI(String string) throws URISyntaxException, IOException {
this(new URI(string));
}
/**
* Create DBURI from a URI, combining a JDBC URL and query parameters.
*
* <p>
* From the JDBC URL component, infer:
* </p>
* <ul>
* <li>JDBC driver class</li>
* <li>supported languages</li>
* <li>default source code types</li>
* <li>default schemas</li>
* </ul>
*
* <p>
* From the query component, define these values, overriding any defaults:
* </p>
* <ul>
* <li>parsing language</li>
* <li>source code types</li>
* <li>schemas</li>
* <li>source code</li>
* </ul>
*
* @param uri A URI
*/
public DBURI(URI uri) throws URISyntaxException, IOException {
/*
* A JDBC URL is an opaque URL and does not have a query.
*
* We pretend that it does, strip off the query, use the real JDBC URL
* component to infer languages JDBC driver class supported languages
* default source code types default schemas generate a faux HTTP URI
* with the query, extract the query parameters
*/
this.uri = uri;
// Split the string between JDBC URL and the query
String[] splitURI = uri.toString().split("\\?");
if (splitURI.length > 1) {
url = splitURI[0];
} else {
url = uri.toString();
}
LOG.debug("Extracted URL={}", url);
// Explode URL into its separate components
setFields();
// If the original URI string contained a query component, split it
// into parameters
if (splitURI.length > 1) {
// Generate a fake HTTP URI to allow easy extraction of the
// query parameters
String chimeraString = "http://local?" + uri.toString().substring(url.length() + 1);
LOG.trace("chimeraString={}", chimeraString);
URI chimeraURI = new URI(chimeraString);
dump("chimeraURI", chimeraURI);
parameters = getParameterMap(chimeraURI);
LOG.trace("parameterMap=={}", parameters);
characterSet = parameters.get("characterset");
sourceCodeTypes = parameters.get("sourcecodetypes");
sourceCodeNames = parameters.get("sourcecodenames");
languages = parameters.get("languages");
// Populate the lists
if (null != sourceCodeNames) {
sourceCodeNamesList = Arrays.asList(sourceCodeNames.split(","));
}
if (null != languages) {
languagesList = Arrays.asList(languages.split(","));
}
if (null != parameters.get("schemas")) {
schemasList = Arrays.asList(parameters.get("schemas").split(","));
}
if (null != sourceCodeTypes) {
sourceCodeTypesList = Arrays.asList(sourceCodeTypes.split(","));
}
}
}
/**
* Return extracted parameters from dburi.
*
* @param dburi
* @return extracted parameters
* @throws UnsupportedEncodingException
*/
private Map<String, String> getParameterMap(URI dburi) throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<>();
String query = dburi.getRawQuery();
LOG.trace("dburi,getQuery()={}", query);
if (null != query && !"".equals(query)) {
String[] params = query.split("&");
for (String param : params) {
String[] splits = param.split("=");
String name = splits[0];
String value = null;
if (splits.length > 1) {
value = splits[1];
}
map.put(name, (null == value) ? value : URLDecoder.decode(value, "UTF-8"));
}
}
return map;
}
/**
* Dump this URI to the log.
*
* @param description
* @param dburi
*/
static void dump(String description, URI dburi) {
LOG.debug("dump ({})\n: isOpaque={}, isAbsolute={} Scheme={},\n SchemeSpecificPart={},\n Host={},\n Port={},\n Path={},\n Fragment={},\n Query={}",
description, dburi.isOpaque(), dburi.isAbsolute(), dburi.getScheme(), dburi.getSchemeSpecificPart(),
dburi.getHost(), dburi.getPort(), dburi.getPath(), dburi.getFragment(), dburi.getQuery());
String query = dburi.getQuery();
if (null != query && !"".equals(query)) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<>();
for (String param : params) {
String[] splits = param.split("=");
String name = splits[0];
String value = null;
if (splits.length > 1) {
value = splits[1];
}
map.put(name, value);
LOG.debug("name={},value={}", name, value);
}
}
// return map;
}
public URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public DBType getDbType() {
return dbType;
}
public void setDbType(DBType dbType) {
this.dbType = dbType;
}
public List<String> getSchemasList() {
return schemasList;
}
public void setSchemasList(List<String> schemasList) {
this.schemasList = schemasList;
}
public List<String> getSourceCodeTypesList() {
return sourceCodeTypesList;
}
public void setSourceCodeTypesList(List<String> sourceCodeTypesList) {
this.sourceCodeTypesList = sourceCodeTypesList;
}
public List<String> getSourceCodeNamesList() {
return sourceCodeNamesList;
}
public void setSourceCodeNamesList(List<String> sourceCodeNamesList) {
this.sourceCodeNamesList = sourceCodeNamesList;
}
public List<String> getLanguagesList() {
return languagesList;
}
public void setLanguagesList(List<String> languagesList) {
this.languagesList = languagesList;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public String getCharacterSet() {
return characterSet;
}
public void setCharacterSet(String characterSet) {
this.characterSet = characterSet;
}
public int getSourceCodeType() {
return sourceCodeType;
}
public void setSourceCodeType(int sourceCodeType) {
this.sourceCodeType = sourceCodeType;
}
public String getSubprotocol() {
return subprotocol;
}
public void setSubprotocol(String subprotocol) {
this.subprotocol = subprotocol;
}
public String getSubnamePrefix() {
return subnamePrefix;
}
public void setSubnamePrefix(String subnamePrefix) {
this.subnamePrefix = subnamePrefix;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* @return the url
*/
public String getURL() {
return url;
}
/**
* @param jdbcURL
* the url to set
*/
public void setURL(String jdbcURL) {
this.url = jdbcURL;
}
/**
* Populate the URI and query collections from the original string
*
* @throws URISyntaxException
* @throws IOException
*/
private void setFields() throws URISyntaxException, IOException {
if (url.startsWith("jdbc:")) {
// java.net.URI is intended for "normal" URLs
URI jdbcURI = new URI(getURL().substring(5));
LOG.debug("setFields - substr(jdbcURL,5):{}", getURL().substring(5));
dump("substr(jdbcURL,5)", jdbcURI);
// jdbc:subprotocol:subname
String[] uriParts = url.split(":");
for (String part : uriParts) {
LOG.trace("JDBCpart={}", part);
}
/*
* Expect jdbc : subprotocol [ : subname ] : connection details
* uriParts.length < 3 Error uriParts.length = 3 Driver information
* may be inferred from part[1] - the subprotocol uriParts.length >=
* 4 Driver information may be inferred from part[2]- the first part
* of the subname
*/
if (3 == uriParts.length) {
subprotocol = uriParts[1];
} else if (4 <= uriParts.length) {
subprotocol = uriParts[1];
subnamePrefix = uriParts[2];
} else {
throw new URISyntaxException(getURL(), "Could not understand JDBC URL", 1);
}
LOG.debug("subprotocol={}'' subnamePrefix={}", subprotocol, subnamePrefix);
// Set values from DBType defaults
this.dbType = new DBType(subprotocol, subnamePrefix);
LOG.debug("DBType properties found at {} with {} properties.",
dbType.getPropertiesSource(), dbType.getProperties().size());
LOG.trace("DBType properties are:- {}", dbType.getProperties());
if (null != dbType.getDriverClass()) {
this.driverClass = dbType.getDriverClass();
}
if (null != dbType.getCharacterSet()) {
this.characterSet = dbType.getCharacterSet();
}
if (null != dbType.getLanguages()) {
this.languages = dbType.getLanguages();
}
if (null != dbType.getSourceCodeTypes()) {
sourceCodeTypes = dbType.getSourceCodeTypes();
}
LOG.debug("DBType other properties follow ...");
if (null != dbType.getProperties().getProperty("schemas")) {
schemasList = Arrays.asList(dbType.getProperties().getProperty("schemas").split(","));
}
if (null != dbType.getProperties().getProperty("sourcecodenames")) {
sourceCodeNames = dbType.getProperties().getProperty("sourcecodenames");
}
String returnType = dbType.getProperties().getProperty("returnType");
if (null != returnType) {
sourceCodeType = Integer.parseInt(returnType);
}
LOG.debug("DBType populating lists ");
// Populate the lists
if (null != sourceCodeNames) {
sourceCodeNamesList = Arrays.asList(sourceCodeNames.split(","));
}
if (null != languages) {
languagesList = Arrays.asList(languages.split(","));
}
if (null != sourceCodeTypes) {
sourceCodeTypesList = Arrays.asList(sourceCodeTypes.split(","));
}
LOG.debug("DBType lists generated");
}
}
@Override
public String toString() {
return uri.toASCIIString();
}
}
| 15,250 | 28.499033 | 155 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/database/DBType.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.database;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encapsulate the settings needed to access database source code.
*
*
* @author sturton
*/
public class DBType {
private static final Logger LOG = LoggerFactory.getLogger(DBType.class);
private static final String INTERNAL_SETTINGS = "[Internal Settings]";
/**
* The names of the properties
*/
public enum Property {
USER("user", "Name of the connecting database user"),
PASSWORD("password", "The connecting database user's password"),
DRIVER("driver", "JDBC driver classname"),
CHARACTERSET("characterset", "Reader character set"),
LANGUAGES("languages", "Comma-separated list of PMD-supported languages"),
SCHEMAS("schemas", "SchemaSpy compatible regular expression for schemas to be processed"),
SOURCE_TYPES("sourcecodetypes", "Comma-separated list of supported source types"),
SOURCE_NAMES("sourcecodenames", "Default comma-separated list of source code names to validate"),
GET_SOURCE_CODE_STATEMENT(
"getSourceCodeStatement",
"SQL92 or Oracle embedded SQL statement to retrieve code source from the database catalogue"),
RETURN_TYPE("returnType", "int equivalent of java.sql.Types return type of getSourceCodeStatement");
private String name;
private String description;
Property(String name, String description) {
this.name = name;
this.description = description;
}
public String getPropertyName() {
return name;
}
public String getDescription() {
return description;
}
}
/**
* Where the properties were taken from
*/
private String propertiesSource;
/**
* Parameters from Properties
*/
private Properties properties;
// Driver Class
private String driverClass;
// Database CharacterSet
private String characterSet;
// String to get objects
private String sourceCodeTypes;
// Languages to process
private String languages;
// Return class for source code
private int sourceCodeReturnType;
/**
*
* @param dbType
*/
public DBType(String dbType) throws Exception {
properties = loadDBProperties(dbType);
}
/**
* Load the most specific dbType for the protocol
*
* @param subProtocol
* @param subnamePrefix
* @throws IOException
*/
public DBType(String subProtocol, String subnamePrefix) throws IOException {
LOG.debug("subProtocol={}, subnamePrefix={}", subProtocol, subnamePrefix);
if (null == subProtocol && null == subnamePrefix) {
throw new RuntimeException("subProtocol and subnamePrefix cannot both be null");
} else {
properties = null;
// Attempt subnamePrefix before subProtocol
if (subnamePrefix != null) {
properties = loadDBProperties(subnamePrefix);
}
if (properties == null && subProtocol != null) {
properties = loadDBProperties(subProtocol);
}
if (subnamePrefix != null && properties != null) {
LOG.debug("DBType found using subnamePrefix={}", subnamePrefix);
} else if (subProtocol != null && properties != null) {
LOG.debug("DBType found using subProtocol={}", subProtocol);
} else {
throw new RuntimeException(
String.format("Could not locate DBType properties using subProtocol=%s and subnamePrefix=%s",
subProtocol, subnamePrefix));
}
}
}
public Properties getProperties() {
return properties;
}
/**
* Load properties from one or more files or resources.
*
* <p>
* This method recursively finds property files or JAR resources matching
* {@matchstring}.
* </p>
* .
* <p>
* The method is intended to be able to use , so any
*
* @param matchString
* @return "current" set of properties (from one or more resources/property
* files)
*/
private Properties loadDBProperties(String matchString) throws IOException {
LOG.trace("Entering: loadDBProperties with {}", matchString);
// Locale locale = Control.g;
ResourceBundle resourceBundle = null;
LOG.trace("class_path={}", System.getProperty("java.class.path"));
/*
* Attempt to match properties files in this order:- File path with
* properties suffix File path without properties suffix Resource
* without class prefix Resource with class prefix
*/
File propertiesFile = new File(matchString);
LOG.trace("Attempting File no file suffix: {}", matchString);
try (InputStream stream = Files.newInputStream(propertiesFile.toPath())) {
resourceBundle = new PropertyResourceBundle(stream);
propertiesSource = propertiesFile.getAbsolutePath();
LOG.trace("FileSystemWithoutExtension");
} catch (NoSuchFileException notFoundOnFilesystemWithoutExtension) {
LOG.trace("notFoundOnFilesystemWithoutExtension");
LOG.trace("Attempting File with added file suffix: {}.properties", matchString);
propertiesFile = new File(matchString + ".properties");
try (InputStream stream = Files.newInputStream(propertiesFile.toPath())) {
resourceBundle = new PropertyResourceBundle(stream);
propertiesSource = propertiesFile.getAbsolutePath();
LOG.trace("FileSystemWithExtension");
} catch (NoSuchFileException notFoundOnFilesystemWithExtensionTackedOn) {
LOG.trace("Attempting JARWithoutClassPrefix: {}", matchString);
try {
resourceBundle = ResourceBundle.getBundle(matchString);
propertiesSource = "[" + INTERNAL_SETTINGS + "]" + File.separator + matchString + ".properties";
LOG.trace("InJarWithoutPath");
} catch (Exception notInJarWithoutPath) {
LOG.trace("Attempting JARWithClass prefix: {}.{}", DBType.class.getCanonicalName(), matchString);
try {
resourceBundle = ResourceBundle.getBundle(DBType.class.getPackage().getName() + "." + matchString);
propertiesSource = "[" + INTERNAL_SETTINGS + "]" + File.separator + matchString + ".properties";
LOG.trace("found InJarWithPath");
} catch (Exception notInJarWithPath) {
notInJarWithPath.printStackTrace();
notFoundOnFilesystemWithExtensionTackedOn.printStackTrace();
throw new RuntimeException(" Could not locate DBTYpe settings : " + matchString,
notInJarWithPath);
}
}
}
}
// Properties in this matched resource
Properties matchedProperties = getResourceBundleAsProperties(resourceBundle);
resourceBundle = null;
String saveLoadedFrom = getPropertiesSource();
/*
* If the matched properties contain the "extends" key, use the value as
* a matchstring, to recursively set the properties before overwriting
* any previous properties with the matched properties.
*/
String extendedPropertyFile = (String) matchedProperties.remove("extends");
if (null != extendedPropertyFile && !"".equals(extendedPropertyFile.trim())) {
Properties extendedProperties = loadDBProperties(extendedPropertyFile.trim());
// Overwrite extended properties with properties in the matched
// resource
extendedProperties.putAll(matchedProperties);
matchedProperties = extendedProperties;
}
/*
* Record the location of the original matched resource/property file,
* and the current set of properties secured.
*/
propertiesSource = saveLoadedFrom;
setProperties(matchedProperties);
return matchedProperties;
}
/**
* Options that are specific to a type of database. E.g. things like
* <code>host</code>, <code>port</code> or <code>db</code>, but <b>don't</b>
* have a setter in this class.
*
* @param dbSpecificOptions
*/
/**
* Convert <code>resourceBundle</code> to usable {@link Properties}.
*
* @param resourceBundle
* ResourceBundle
* @return Properties
*/
public static Properties getResourceBundleAsProperties(ResourceBundle resourceBundle) {
Properties properties = new Properties();
for (String key : resourceBundle.keySet()) {
properties.put(key, resourceBundle.getObject(key));
}
return properties;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((characterSet == null) ? 0 : characterSet.hashCode());
result = prime * result + ((driverClass == null) ? 0 : driverClass.hashCode());
result = prime * result + ((languages == null) ? 0 : languages.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
result = prime * result + ((propertiesSource == null) ? 0 : propertiesSource.hashCode());
result = prime * result + sourceCodeReturnType;
result = prime * result + ((sourceCodeTypes == null) ? 0 : sourceCodeTypes.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
DBType other = (DBType) obj;
if (characterSet == null) {
if (other.characterSet != null) {
return false;
}
} else if (!characterSet.equals(other.characterSet)) {
return false;
}
if (driverClass == null) {
if (other.driverClass != null) {
return false;
}
} else if (!driverClass.equals(other.driverClass)) {
return false;
}
if (languages == null) {
if (other.languages != null) {
return false;
}
} else if (!languages.equals(other.languages)) {
return false;
}
if (properties == null) {
if (other.properties != null) {
return false;
}
} else if (!properties.equals(other.properties)) {
return false;
}
if (propertiesSource == null) {
if (other.propertiesSource != null) {
return false;
}
} else if (!propertiesSource.equals(other.propertiesSource)) {
return false;
}
if (sourceCodeReturnType != other.sourceCodeReturnType) {
return false;
}
if (sourceCodeTypes == null) {
if (other.sourceCodeTypes != null) {
return false;
}
} else if (!sourceCodeTypes.equals(other.sourceCodeTypes)) {
return false;
}
return true;
}
/**
* @return the driverClass
*/
public String getDriverClass() {
return driverClass;
}
/**
* @return the characterSet
*/
public String getCharacterSet() {
return characterSet;
}
/**
* @return the sourceCodeTypes
*/
public String getSourceCodeTypes() {
return sourceCodeTypes;
}
/**
* @return the languages
*/
public String getLanguages() {
return languages;
}
/**
* @return the sourceCodeReturnType
*/
public int getSourceCodeReturnType() {
return sourceCodeReturnType;
}
/**
* @return the propertiesSource
*/
public String getPropertiesSource() {
return propertiesSource;
}
/**
* @param properties
* the properties to set
*/
public void setProperties(Properties properties) {
this.properties = properties;
// Driver Class
if (null != this.properties.getProperty("driver")) {
this.driverClass = this.properties.getProperty("driver");
}
// Database CharacterSet
if (null != this.properties.getProperty("characterset")) {
this.characterSet = this.properties.getProperty("characterset");
}
// String to get objects
if (null != this.properties.getProperty("sourcecodetypes")) {
this.sourceCodeTypes = this.properties.getProperty("sourcecodetypes");
}
// Languages to process
if (null != this.properties.getProperty("languages")) {
this.languages = this.properties.getProperty("languages");
}
// Return class for source code
if (null != this.properties.getProperty("returnType")) {
LOG.trace("returnType={}", this.properties.getProperty("returnType"));
this.sourceCodeReturnType = Integer.parseInt(this.properties.getProperty("returnType"));
}
}
@Override
public String toString() {
return DBType.class.getCanonicalName() + "@" + propertiesSource;
}
}
| 14,085 | 33.106538 | 123 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/designerbindings/RelatedNodesSelector.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.designerbindings;
import java.util.List;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Provides a way for the designer to highlight related nodes upon selection,
* eg those nodes referring to the same variable or method.
*
* <p>This API only published to bind to the designer for now, it should
* not be used by rule code. The criterion for selecting nodes to highlight
* is subject to change at the implementation's discretion. In particular it's
* not necessarily the usages of a variable.
*
* <p>The binary API is <b>unstable</b> until at least 7.0, meaning the only
* place this can be implemented safely is within PMD's own codebase.
*
* @author Clément Fournier
* @since 6.20.0
*/
@Experimental
public interface RelatedNodesSelector {
/**
* Returns a list of nodes that should be highlighted when selecting
* the given node. This is eg the nodes that correspond to usages of
* a variable declared by the given node. If the node cannot be handled
* by this resolver or is otherwise uninteresting, then returns an empty list.
*
* @param node A node, with no guarantee about type. Implementations
* should check their casts.
*
* @return A list of nodes to highlight
*/
List<Node> getHighlightedNodesWhenSelecting(Node node);
}
| 1,496 | 31.543478 | 82 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/designerbindings/DesignerBindings.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.designerbindings;
import java.util.Collection;
import java.util.Collections;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.lang.symboltable.ScopedNode;
/**
* Gathers some services to customise how language implementations bind
* to the designer.
*
* @author Clément Fournier
* @since 6.20.0
*/
@Experimental
public interface DesignerBindings {
/**
* Returns an instance of {@link RelatedNodesSelector}, or
* null if it should be defaulted to using the old symbol table ({@link ScopedNode}).
* That default behaviour is implemented in the designer directly.
*/
RelatedNodesSelector getRelatedNodesSelector();
/**
* Returns a collection of "additional information" entries pertaining to
* the given node. An entry may look like {@code ("Type = List<String>", 0)},
* or show the result of an XPath function. The information is shown
* when the node is displayed.
*
* <p>Order of the collection is unimportant, it's sorted using
* {@link AdditionalInfo#getSortKey()}.
*/
Collection<AdditionalInfo> getAdditionalInfo(Node node);
/**
* An entry for the "additional info" panel.
*/
class AdditionalInfo {
private final String sortKey;
private final String display;
public AdditionalInfo(String sortKey, String display) {
this.sortKey = sortKey;
this.display = display;
}
public AdditionalInfo(String display) {
this(display, display);
}
/**
* Returns the string used to sort the additional info.
* For example, returning {@code "A"} ensures this is displayed
* first, provided there's no other entry with an {@code "A"}.
*/
public String getSortKey() {
return sortKey;
}
/**
* Returns the string displayed to the user.
*/
public String getDisplayString() {
return display;
}
}
/**
* Returns the "main" attribute of the given node.
* The string representation of this attribute ({@link Attribute#getStringValue()})
* will be displayed next to the node type in the treeview. For
* example, for a numeric literal, this could return the attribute
* {@code (@IntValue, 1)}, for a class declaration, it could return the name
* of the class (eg {@code (@SimpleName, String)}.
*
* <p>If there's no obvious "main" attribute, or if the node is not
* supported, returns null. If the returned attribute is non-null,
* but its string value is, the return value is ignored.
*
* <p>Note: the attribute doesn't need to originate from
* {@link Node#getXPathAttributesIterator()}, it can be constructed
* ad-hoc. The name of the attribute should be a valid name for the
* XPath attribute though.
*
* <p>This method is meant to break the designer's dependency on {@link Node#getImage()}.
*/
// @Nullable
Attribute getMainAttribute(Node node);
/**
* Returns true if the children of this node should be displayed in
* the treeview by default. Returning "true" is the safe default value.
*/
boolean isExpandedByDefaultInTree(Node node);
/**
* Returns a constant describing an icon that the node should bear
* in the treeview and other relevant places. Returns null if no icon
* is applicable.
*/
// @Nullable
TreeIconId getIcon(Node node);
/**
* See {@link #getIcon(Node)}.
*/
@Experimental
enum TreeIconId {
CLASS,
METHOD,
CONSTRUCTOR,
FIELD,
VARIABLE
}
/**
* A base implementation for {@link DesignerBindings}.
*/
class DefaultDesignerBindings implements DesignerBindings {
private static final DefaultDesignerBindings INSTANCE = new DefaultDesignerBindings();
@Override
public RelatedNodesSelector getRelatedNodesSelector() {
return null;
}
@Override
public Collection<AdditionalInfo> getAdditionalInfo(Node node) {
return Collections.emptyList();
}
@Override
public Attribute getMainAttribute(Node node) {
String image = node.getImage();
if (image != null) {
return new Attribute(node, "Image", image);
}
return null;
}
@Override
public boolean isExpandedByDefaultInTree(Node node) {
return true;
}
@Override
public TreeIconId getIcon(Node node) {
return null;
}
/** Returns the default instance. */
public static DefaultDesignerBindings getInstance() {
return INSTANCE;
}
}
}
| 5,075 | 27.840909 | 94 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/ZipDataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.sourceforge.pmd.util.datasource.internal.AbstractDataSource;
/**
* DataSource implementation to read data from an entry in a zip or jar file.
*/
@Deprecated
public class ZipDataSource extends AbstractDataSource {
private final ZipFile zipFile;
private final ZipEntry zipEntry;
/**
* @param zipFile
* the ZipFile
* @param zipEntry
* the ZipEntry containing the file to read
*/
public ZipDataSource(ZipFile zipFile, ZipEntry zipEntry) {
this.zipFile = zipFile;
this.zipEntry = zipEntry;
}
@Override
public InputStream getInputStream() throws IOException {
return zipFile.getInputStream(zipEntry);
}
@Override
public String getNiceFileName(boolean shortNames, String inputFileName) {
// FIXME: this could probably be done better
return zipFile.getName() + ":" + zipEntry.getName();
}
@Override
public String toString() {
return new StringBuilder(ZipDataSource.class.getSimpleName())
.append('[')
.append(zipFile.getName())
.append('!')
.append(zipEntry.getName())
.append(']')
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((zipEntry == null) ? 0 : zipEntry.getName().hashCode());
result = prime * result + ((zipFile == null) ? 0 : zipFile.getName().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("PMD.CloseResource")
ZipDataSource other = (ZipDataSource) obj;
if (zipEntry == null) {
if (other.zipEntry != null) {
return false;
}
} else if (!zipEntry.getName().equals(other.zipEntry.getName())) {
return false;
}
if (zipFile == null) {
if (other.zipFile != null) {
return false;
}
} else if (!zipFile.getName().equals(other.zipFile.getName())) {
return false;
}
return true;
}
@Override
public void close() throws IOException {
if (zipFile != null) {
zipFile.close();
}
}
}
| 2,792 | 26.653465 | 91 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/FileDataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource;
import java.io.File;
import net.sourceforge.pmd.util.datasource.internal.PathDataSource;
/**
* DataSource implementation to read data from a file.
*/
@Deprecated
public class FileDataSource extends PathDataSource {
/**
* @param file the file to read
*/
public FileDataSource(File file) {
super(file.toPath(), null);
}
}
| 490 | 19.458333 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/ReaderDataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.util.datasource.internal.AbstractDataSource;
/**
* DataSource implementation to read data from a Reader.
*/
@Deprecated
public class ReaderDataSource extends AbstractDataSource {
/**
* Reader
*/
private final Reader reader;
/**
* Real or pseudo filename or path name.
*
* <p>
* Including a file suffix mapped to the correct language helps assign the
* correct parser.
* </p>
*/
private String dataSourceName;
/**
* Create the DataSource from the Reader.
*/
public ReaderDataSource(Reader reader, String dataSourceName) {
this.reader = reader;
this.dataSourceName = dataSourceName;
}
/**
* Convert the Reader into an InputStream.
* <p>
* <strong>Note:</strong> This uses the default encoding.
* </p>
*
* @return Derived InputStream
* @throws IOException
*/
@Override
public InputStream getInputStream() throws IOException {
return IOUtil.fromReader(reader);
}
/**
* Return the dataSourceName via the {@link DataSource} Interface method.
*
* <p>
* Both the parameters are ignored
* </p>
*
* @param shortNames
* ignored
* @param inputFileName
* ignored
* @return
*/
@Override
public String getNiceFileName(boolean shortNames, String inputFileName) {
return getDataSourceName();
}
/**
* @return the dataSourceName
*/
public String getDataSourceName() {
return dataSourceName;
}
/**
* @param dataSourceName
* the dataSourceName to set
*/
public void setDataSourceName(String dataSourceName) {
this.dataSourceName = dataSourceName;
}
@Override
public String toString() {
return new StringBuilder(ReaderDataSource.class.getSimpleName())
.append('[')
.append(dataSourceName)
.append(']')
.toString();
}
}
| 2,327 | 22.755102 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/DataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import net.sourceforge.pmd.lang.document.TextFile;
/**
* Represents a source file to be analyzed. Different implementations can get
* the source file from different places: the filesystem, a zip or jar file,
* etc.
*
* @deprecated Use {@link TextFile}
*/
@Deprecated
public interface DataSource extends Closeable {
/**
* Get an InputStream on the source file.
*
* @return the InputStream reading the source file
* @throws IOException
* if the file can't be opened
*/
InputStream getInputStream() throws IOException;
/**
* Return a nice version of the filename.
*
* @param shortNames
* true if short names are being used
* @param inputFileName
* name of a "master" file this file is relative to
* @return String
*/
String getNiceFileName(boolean shortNames, String inputFileName);
static DataSource forString(String sourceText, String fileName) {
return new ReaderDataSource(new StringReader(sourceText), fileName);
}
}
| 1,314 | 25.3 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/internal/AbstractDataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource.internal;
import java.io.IOException;
import net.sourceforge.pmd.util.datasource.DataSource;
@Deprecated
public abstract class AbstractDataSource implements DataSource {
@Override
public void close() throws IOException {
// empty default implementation
}
}
| 414 | 20.842105 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/datasource/internal/PathDataSource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.datasource.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.internal.util.ShortFilenameUtil;
/**
* DataSource implementation to read data from a {@link java.nio.file.Path}.
* This can also be a Path inside a zip file.
*/
//TODO This class (and all other DataSources) can be probably removed with PMD 7 in favor of TextFile
public class PathDataSource extends AbstractDataSource {
private final String displayName;
private final Path path;
/**
* @param path the file to read
*/
public PathDataSource(Path path) {
this(path, null);
}
/**
* @param path the file to read
*/
public PathDataSource(Path path, String displayName) {
this.path = path;
this.displayName = displayName;
}
@Override
public InputStream getInputStream() throws IOException {
return Files.newInputStream(path);
}
@Override
public String getNiceFileName(boolean shortNames, String inputPaths) {
return glomName(shortNames, inputPaths);
}
private String getAbsoluteFilePath() {
if ("jar".equals(path.toUri().getScheme())) {
return new File(URI.create(path.toUri().getSchemeSpecificPart()).getPath()).toString();
}
return path.toFile().getAbsolutePath();
}
private String getSimpleFilePath() {
if ("jar".equals(path.toUri().getScheme())) {
String[] zipAndFile = URI.create(path.toUri().getSchemeSpecificPart()).getPath().split("!");
return new File(zipAndFile[0]).getName() + "!" + new File(zipAndFile[1]).getName();
}
return path.toFile().getName();
}
private String glomName(boolean shortNames, String inputPaths) {
if (displayName != null) {
return displayName;
}
if (shortNames) {
if (inputPaths != null) {
List<String> inputPathPrefixes = Arrays.asList(inputPaths.split(","));
final String absoluteFilePath = getAbsoluteFilePath();
return ShortFilenameUtil.determineFileName(inputPathPrefixes, absoluteFilePath);
} else {
// if the 'master' file is not specified, just use the file name
return getSimpleFilePath();
}
}
try {
return path.toFile().getCanonicalFile().getAbsolutePath();
} catch (Exception e) {
// Exception might occur when symlinks can't be resolved (permission problem)
// or when path is inside a jar/zip file
return getAbsoluteFilePath();
}
}
@Override
public String toString() {
return new StringBuilder(this.getClass().getSimpleName())
.append('[')
.append(path.toUri())
.append(']')
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((path == null) ? 0 : path.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("PMD.CloseResource")
PathDataSource other = (PathDataSource) obj;
if (path == null) {
if (other.path != null) {
return false;
}
} else if (!path.equals(other.path)) {
return false;
}
return true;
}
}
| 3,939 | 28.62406 | 104 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/log/MessageReporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.log;
import java.text.MessageFormat;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.event.Level;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.util.log.internal.QuietReporter;
/**
* Façade to report user-facing messages (info, warning and error).
* Note: messages are formatted using {@link MessageFormat}.
*
* <p>Internal API: this is a transitional API that will be significantly
* changed in PMD 7, with the transition to SLF4J. See https://github.com/pmd/pmd/issues/3816
*
* TODO rename to PmdReporter
*
* @author Clément Fournier
*/
@InternalApi
public interface MessageReporter {
// todo change String to MessageFormat in those arg lists, it's too confusing
// where to apply MessageFormat otherwise...
boolean isLoggable(Level level);
default void log(Level level, String message, Object... formatArgs) {
logEx(level, message, formatArgs, null);
}
void logEx(Level level, @Nullable String message, Object[] formatArgs, @Nullable Throwable error);
/**
* Logs and returns a new exception.
* Message and cause may not be null a the same time.
*/
default RuntimeException newException(Level level, @Nullable Throwable cause, @Nullable String message, Object... formatArgs) {
logEx(level, message, formatArgs, cause);
if (message == null) {
return new RuntimeException(cause);
}
return new RuntimeException(MessageFormat.format(message, formatArgs), cause);
}
default void info(String message, Object... formatArgs) {
log(Level.INFO, message, formatArgs);
}
default void warn(String message, Object... formatArgs) {
log(Level.WARN, message, formatArgs);
}
default void warnEx(String message, Throwable error) {
logEx(Level.WARN, message, new Object[0], error);
}
default void warnEx(String message, Object[] formatArgs, Throwable error) {
logEx(Level.WARN, message, formatArgs, error);
}
default RuntimeException error(String message, Object... formatArgs) {
return error(null, message, formatArgs);
}
/**
* Only one of the cause or the message can be null.
*/
default RuntimeException error(@Nullable Throwable cause, @Nullable String contextMessage, Object... formatArgs) {
return newException(Level.ERROR, cause, contextMessage, formatArgs);
}
default RuntimeException error(Throwable error) {
return error(error, null);
}
default void errorEx(String message, Throwable error) {
logEx(Level.ERROR, message, new Object[0], error);
}
default void errorEx(String message, Object[] formatArgs, Throwable error) {
logEx(Level.ERROR, message, formatArgs, error);
}
/**
* Returns the number of errors reported on this instance.
* Any call to {@link #log(Level, String, Object...)} or
* {@link #logEx(Level, String, Object[], Throwable)} with a level
* of {@link Level#ERROR} should increment this number.
*/
int numErrors();
/**
* Returns a reporter instance that does not output anything, but
* still counts errors.
*/
static MessageReporter quiet() {
return new QuietReporter();
}
}
| 3,428 | 30.458716 | 131 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/log/internal/MessageReporterBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.log.internal;
import static net.sourceforge.pmd.util.StringUtil.quoteMessageFormat;
import java.text.MessageFormat;
import java.util.Objects;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.event.Level;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Base implementation.
*
* @author Clément Fournier
*/
abstract class MessageReporterBase implements MessageReporter {
private int numErrors;
private @Nullable Level minLevel = Level.TRACE;
/**
* null level means off.
*/
public final void setLevel(@Nullable Level minLevel) {
this.minLevel = minLevel;
}
@Override
public final boolean isLoggable(Level level) {
return minLevel != null
&& minLevel.compareTo(level) >= 0
&& isLoggableImpl(level);
}
protected boolean isLoggableImpl(Level level) {
return true;
}
@Override
public void logEx(Level level, @Nullable String message, Object[] formatArgs, @Nullable Throwable error) {
if (isLoggable(level)) {
if (error == null) {
Objects.requireNonNull(message, "cannot call this method with null message and error");
log(level, message, formatArgs);
return;
}
if (level == Level.ERROR) {
this.numErrors++;
}
String fullMessage = getErrorMessage(error);
if (message != null) {
message = MessageFormat.format(message, formatArgs);
fullMessage = message + ": " + fullMessage;
}
logImpl(level, fullMessage);
if (isLoggable(Level.DEBUG)) {
String stackTrace = quoteMessageFormat(ExceptionUtils.getStackTrace(error));
log(Level.DEBUG, stackTrace);
}
} else {
// should be incremented even if not logged
if (level == Level.ERROR) {
this.numErrors++;
}
}
}
private @NonNull String getErrorMessage(Throwable error) {
String errorMessage = error.getMessage();
if (errorMessage == null) {
errorMessage = error.getClass().getSimpleName();
}
return errorMessage;
}
@Override
public final void log(Level level, String message, Object... formatArgs) {
if (level == Level.ERROR) {
this.numErrors++;
}
if (isLoggable(level)) {
logImpl(level, MessageFormat.format(message, formatArgs));
}
}
/**
* Perform logging assuming {@link #isLoggable(Level)} is true.
*/
protected abstract void logImpl(Level level, String message);
@Override
public int numErrors() {
return numErrors;
}
}
| 3,044 | 28 | 110 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/log/internal/ErrorsAsWarningsReporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.log.internal;
import org.slf4j.event.Level;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Turns errors into warnings reported on another logger.
*
* @author Clément Fournier
*/
@InternalApi
public final class ErrorsAsWarningsReporter extends MessageReporterBase {
private final MessageReporter backend;
public ErrorsAsWarningsReporter(MessageReporter backend) {
this.backend = backend;
}
@Override
protected boolean isLoggableImpl(Level level) {
if (level == Level.ERROR) {
level = Level.WARN;
}
return super.isLoggableImpl(level);
}
@Override
protected void logImpl(Level level, String message) {
if (level == Level.ERROR) {
level = Level.WARN;
}
backend.log(level, message);
}
}
| 993 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/log/internal/SimpleMessageReporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.log.internal;
import org.slf4j.Logger;
import org.slf4j.event.Level;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* A {@link Logger} (java.util) based logger impl.
*
* @author Clément Fournier
*/
@InternalApi
public class SimpleMessageReporter extends MessageReporterBase implements MessageReporter {
private final Logger backend;
public SimpleMessageReporter(Logger backend) {
this.backend = backend;
}
@Override
protected boolean isLoggableImpl(Level level) {
switch (level) {
case ERROR:
return backend.isErrorEnabled();
case WARN:
return backend.isWarnEnabled();
case INFO:
return backend.isInfoEnabled();
case DEBUG:
return backend.isDebugEnabled();
case TRACE:
return backend.isTraceEnabled();
default:
return false;
}
}
@Override
protected void logImpl(Level level, String message) {
switch (level) {
case ERROR:
backend.error(message);
break;
case WARN:
backend.warn(message);
break;
case INFO:
backend.info(message);
break;
case DEBUG:
backend.debug(message);
break;
case TRACE:
backend.trace(message);
break;
default:
throw new AssertionError("Invalid log level: " + level);
}
}
}
| 1,662 | 23.455882 | 91 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.