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/util/log/internal/QuietReporter.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;
/**
* A logger that ignores all messages.
*
* @author Clément Fournier
*/
@InternalApi
public class QuietReporter extends MessageReporterBase implements MessageReporter {
// note: not singleton because PmdLogger accumulates error count.
// note: not final because used as mock in tests.
@Override
protected boolean isLoggableImpl(Level level) {
return false;
}
@Override
protected void logImpl(Level level, String message) {
// noop
}
}
| 764 | 22.181818 | 83 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/internal/xml/XmlErrorMessages.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.internal.xml;
// CHECKSTYLE:OFF
public final class XmlErrorMessages {
private static final String THIS_WILL_BE_IGNORED = ", this will be ignored";
/** {0}: unexpected element name; {1}: parent node name; {2}: list of allowed elements in this context */
public static final String ERR__UNEXPECTED_ELEMENT = "Unexpected element ''{0}'' in {1}, expecting {2}";
/** {0}: unexpected element name; {1}: parent node name */
public static final String ERR__UNEXPECTED_ELEMENT_IN = "Unexpected element ''{0}'' in {1}";
/** {0}: unexpected attr name; {1}: parent node name */
public static final String ERR__UNEXPECTED_ATTRIBUTE_IN = "Unexpected attribute ''{0}'' in {1}";
public static final String ERR__MISSING_REQUIRED_ATTRIBUTE = "Required attribute ''{0}'' is missing";
public static final String ERR__BLANK_REQUIRED_ATTRIBUTE = "Required attribute ''{0}'' is blank";
public static final String ERR__MISSING_REQUIRED_ELEMENT = "Required child element named {0} is missing";
/** {0}: unexpected element name; {1}: parent node name; {2}: allowed elements in this context */
public static final String IGNORED__UNEXPECTED_ELEMENT = ERR__UNEXPECTED_ELEMENT + THIS_WILL_BE_IGNORED;
/** {0}: unexpected element name; {1}: parent node name */
public static final String IGNORED__UNEXPECTED_ELEMENT_IN = ERR__UNEXPECTED_ELEMENT_IN + THIS_WILL_BE_IGNORED;
public static final String IGNORED__UNEXPECTED_ATTRIBUTE_IN = ERR__UNEXPECTED_ATTRIBUTE_IN + THIS_WILL_BE_IGNORED;
public static final String IGNORED__DUPLICATE_CHILD_ELEMENT = "Duplicated child with name ''{0}''" + THIS_WILL_BE_IGNORED;
public static final String IGNORED__DUPLICATE_PROPERTY_SETTER = "Duplicate property tag with name ''{0}''" + THIS_WILL_BE_IGNORED;
public static final String ERR__UNSUPPORTED_VALUE_ATTRIBUTE = "This property does not support the attribute syntax.\nUse a nested element, e.g. {1}";
public static final String ERR__PROPERTY_DOES_NOT_EXIST = "Cannot set non-existent property ''{0}'' on rule {1}";
public static final String ERR__CONSTRAINT_NOT_SATISFIED = "Property constraint(s) not satisfied: {0}";
public static final String ERR__LIST_CONSTRAINT_NOT_SATISFIED = "Property constraint(s) not satisfied on items";
public static final String ERR__INVALID_VERSION_RANGE = "Invalid language version range, minimum version ''{0}'' is greater than maximum version ''{1}''";
public static final String ERR__INVALID_LANG_VERSION_NO_NAMED_VERSION = "Invalid language version ''{0}'' for language ''{1}'', the language has no named versions";
public static final String ERR__INVALID_LANG_VERSION = "Invalid language version ''{0}'' for language ''{1}'', supported versions are {2}";
public static final String WARN__DEPRECATED_USE_OF_ATTRIBUTE = "The use of the ''{0}'' attribute is deprecated. Use a nested element, e.g. {1}";
public static final String ERR__INVALID_PRIORITY_VALUE = "Not a valid priority: ''{0}'', expected a number in [1,5]";
public static final String ERR__UNSUPPORTED_PROPERTY_TYPE = "Unsupported property type ''{0}''";
private XmlErrorMessages() {
// utility class
}
}
| 3,314 | 71.065217 | 168 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/internal/xml/XmlUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.internal.xml;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.ERR__MISSING_REQUIRED_ELEMENT;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.IGNORED__DUPLICATE_CHILD_ELEMENT;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.IGNORED__UNEXPECTED_ELEMENT;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.IGNORED__UNEXPECTED_ELEMENT_IN;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import net.sourceforge.pmd.util.StringUtil;
import com.github.oowekyala.ooxml.DomUtils;
public final class XmlUtil {
private XmlUtil() {
}
public static Stream<Element> getElementChildren(Element parent) {
return DomUtils.asList(parent.getChildNodes()).stream()
.filter(it -> it.getNodeType() == Node.ELEMENT_NODE)
.map(Element.class::cast);
}
public static List<Element> getElementChildrenList(Element parent) {
return getElementChildren(parent).collect(Collectors.toList());
}
public static Stream<Element> getElementChildrenNamed(Element parent, Set<SchemaConstant> names) {
return getElementChildren(parent).filter(e -> matchesName(e, names));
}
public static Stream<Element> getElementChildrenNamedReportOthers(Element parent, Set<SchemaConstant> names, PmdXmlReporter err) {
return getElementChildren(parent)
.map(it -> {
if (matchesName(it, names)) {
return it;
} else {
err.at(it).warn(IGNORED__UNEXPECTED_ELEMENT_IN, it.getTagName(), formatPossibleNames(names));
return null;
}
}).filter(Objects::nonNull);
}
public static boolean matchesName(Element elt, Set<SchemaConstant> names) {
return names.stream().anyMatch(it -> it.xmlName().equals(elt.getTagName()));
}
public static void reportIgnoredUnexpectedElt(Element parent,
Element unexpectedChild,
Set<SchemaConstant> names,
PmdXmlReporter err) {
err.at(unexpectedChild).warn(IGNORED__UNEXPECTED_ELEMENT,
unexpectedChild.getTagName(),
parent.getTagName(),
formatPossibleNames(names));
}
public static Stream<Element> getElementChildrenNamed(Element parent, String name) {
return getElementChildren(parent).filter(e -> name.equals(e.getTagName()));
}
public static List<Element> getChildrenExpectSingleName(Element elt, String name, PmdXmlReporter err) {
return XmlUtil.getElementChildren(elt).peek(it -> {
if (!it.getTagName().equals(name)) {
err.at(it).warn(IGNORED__UNEXPECTED_ELEMENT_IN, it.getTagName(), name);
}
}).collect(Collectors.toList());
}
public static Element getSingleChildIn(Element elt, boolean throwOnMissing, PmdXmlReporter err, Set<SchemaConstant> names) {
List<Element> children = getElementChildrenNamed(elt, names).collect(Collectors.toList());
if (children.size() == 1) {
return children.get(0);
} else if (children.isEmpty()) {
if (throwOnMissing) {
throw err.at(elt).error(ERR__MISSING_REQUIRED_ELEMENT, formatPossibleNames(names));
} else {
return null;
}
} else {
for (int i = 1; i < children.size(); i++) {
Element child = children.get(i);
err.at(child).warn(IGNORED__DUPLICATE_CHILD_ELEMENT, child.getTagName());
}
return children.get(0);
}
}
public static @Nullable String formatPossibleNames(Set<SchemaConstant> names) {
if (names.isEmpty()) {
return null;
} else if (names.size() == 1) {
return StringUtil.inSingleQuotes(names.iterator().next().xmlName());
} else {
return "one of " + names.stream()
.map(SchemaConstant::xmlName)
.map(StringUtil::inSingleQuotes)
.collect(Collectors.joining(", "));
}
}
/**
* Parse a String from a textually type node.
*
* @param node The node.
*
* @return The String.
*/
public static String parseTextNode(Node node) {
final int nodeCount = node.getChildNodes().getLength();
if (nodeCount == 0) {
return "";
}
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < nodeCount; i++) {
Node childNode = node.getChildNodes().item(i);
if (childNode.getNodeType() == Node.CDATA_SECTION_NODE || childNode.getNodeType() == Node.TEXT_NODE) {
buffer.append(childNode.getNodeValue());
}
}
return buffer.toString();
}
}
| 5,422 | 37.460993 | 134 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/internal/xml/SchemaConstant.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.internal.xml;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Wraps the name of eg an attribute or element, and provides convenience
* methods to query the DOM.
*/
public class SchemaConstant {
private final String name;
public SchemaConstant(String name) {
this.name = name;
}
public boolean getAsBooleanAttr(Element e, boolean defaultValue) {
String attr = e.getAttribute(name);
return e.hasAttribute(name) ? Boolean.parseBoolean(attr) : defaultValue;
}
public @NonNull String getAttributeOrThrow(Element element, PmdXmlReporter err) {
String attribute = element.getAttribute(name);
if (!element.hasAttribute(name)) {
throw err.at(element).error(XmlErrorMessages.ERR__MISSING_REQUIRED_ATTRIBUTE, name);
}
return attribute;
}
public @NonNull String getNonBlankAttributeOrThrow(Element element, PmdXmlReporter err) {
String attribute = element.getAttribute(name);
if (!element.hasAttribute(name)) {
throw err.at(element).error(XmlErrorMessages.ERR__MISSING_REQUIRED_ATTRIBUTE, name);
} else if (StringUtils.isBlank(attribute)) {
throw err.at(element).error(XmlErrorMessages.ERR__BLANK_REQUIRED_ATTRIBUTE, name);
}
return attribute;
}
public @Nullable String getAttributeOrNull(Element element) {
if (element.hasAttribute(name)) {
return element.getAttribute(name);
}
return null;
}
public Optional<String> getAttributeOpt(Element element) {
Attr attr = element.getAttributeNode(name);
return Optional.ofNullable(attr).map(Attr::getValue);
}
public @Nullable Attr getAttributeNode(Element element) {
return element.getAttributeNode(name);
}
public boolean hasAttribute(Element element) {
return element.hasAttribute(name);
}
public List<Element> getChildrenIn(Element elt) {
return XmlUtil.getElementChildrenNamed(elt, name)
.collect(Collectors.toList());
}
public List<Element> getElementChildrenNamedReportOthers(Element elt, PmdXmlReporter err) {
return XmlUtil.getElementChildrenNamedReportOthers(elt, setOf(this), err)
.collect(Collectors.toList());
}
public Element getSingleChildIn(Element elt, PmdXmlReporter err) {
return XmlUtil.getSingleChildIn(elt, true, err, setOf(this));
}
public Element getOptChildIn(Element elt, PmdXmlReporter err) {
return XmlUtil.getSingleChildIn(elt, false, err, setOf(this));
}
public void setOn(Element element, String value) {
element.setAttribute(name, value);
}
/**
* Returns the String name of this attribute.
*
* @return The attribute's name
*/
public String xmlName() {
return name;
}
@Override
public String toString() {
return xmlName();
}
public boolean matchesElt(Node node) {
return node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SchemaConstant that = (SchemaConstant) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
public @NonNull String getNonBlankAttribute(Element ruleElement, PmdXmlReporter err) {
String clazz = getAttributeOrThrow(ruleElement, err);
if (StringUtils.isBlank(clazz)) {
Attr node = getAttributeNode(ruleElement);
throw err.at(node).error("Attribute {0} may not be blank", this);
}
return clazz;
}
}
| 4,364 | 28.493243 | 96 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/internal/xml/SchemaConstants.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.internal.xml;
/**
* Constants of the ruleset schema.
*/
public final class SchemaConstants {
public static final SchemaConstant PROPERTY_TYPE = new SchemaConstant("type");
public static final SchemaConstant NAME = new SchemaConstant("name");
public static final SchemaConstant MESSAGE = new SchemaConstant("message");
public static final SchemaConstant LANGUAGE = new SchemaConstant("language");
public static final SchemaConstant CLASS = new SchemaConstant("class");
public static final SchemaConstant DESCRIPTION = new SchemaConstant("description");
public static final SchemaConstant PROPERTY_VALUE = new SchemaConstant("value");
public static final SchemaConstant PROPERTIES = new SchemaConstant("properties");
public static final SchemaConstant PROPERTY_ELT = new SchemaConstant("property");
public static final SchemaConstant DEPRECATED = new SchemaConstant("deprecated");
public static final SchemaConstant RULESET = new SchemaConstant("ruleset");
public static final SchemaConstant EXCLUDE_PATTERN = new SchemaConstant("exclude-pattern");
public static final SchemaConstant INCLUDE_PATTERN = new SchemaConstant("include-pattern");
public static final SchemaConstant RULE = new SchemaConstant("rule");
public static final SchemaConstant REF = new SchemaConstant("ref");
public static final SchemaConstant EXCLUDE = new SchemaConstant("exclude");
public static final SchemaConstant PRIORITY = new SchemaConstant("priority");
public static final SchemaConstant MINIMUM_LANGUAGE_VERSION = new SchemaConstant("minimumLanguageVersion");
public static final SchemaConstant MAXIMUM_LANGUAGE_VERSION = new SchemaConstant("maximumLanguageVersion");
public static final SchemaConstant EXTERNAL_INFO_URL = new SchemaConstant("externalInfoUrl");
public static final SchemaConstant EXAMPLE = new SchemaConstant("example");
public static final SchemaConstant SINCE = new SchemaConstant("since");
private SchemaConstants() {
// utility class
}
}
| 2,172 | 49.534884 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/util/internal/xml/PmdXmlReporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.internal.xml;
import net.sourceforge.pmd.util.log.MessageReporter;
import com.github.oowekyala.ooxml.messages.XmlMessageReporter;
/**
* @author Clément Fournier
*/
public interface PmdXmlReporter extends XmlMessageReporter<MessageReporter> {
}
| 371 | 20.882353 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/SimpleRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.util.StringUtil;
public class SimpleRenderer implements CPDReportRenderer {
private String separator;
private boolean trimLeadingWhitespace;
public static final String DEFAULT_SEPARATOR = "=====================================================================";
public SimpleRenderer() {
this(false);
}
public SimpleRenderer(boolean trimLeadingWhitespace) {
this(DEFAULT_SEPARATOR);
this.trimLeadingWhitespace = trimLeadingWhitespace;
}
public SimpleRenderer(String theSeparator) {
separator = theSeparator;
}
@Override
public void render(CPDReport report, Writer writer0) throws IOException {
PrintWriter writer = new PrintWriter(writer0);
Iterator<Match> matches = report.getMatches().iterator();
if (matches.hasNext()) {
renderOn(writer, matches.next());
}
while (matches.hasNext()) {
Match match = matches.next();
writer.println(separator);
renderOn(writer, match);
}
writer.flush();
}
private void renderOn(PrintWriter writer, Match match) throws IOException {
writer.append("Found a ").append(String.valueOf(match.getLineCount())).append(" line (").append(String.valueOf(match.getTokenCount()))
.append(" tokens) duplication in the following files: ").println();
for (Mark mark : match) {
writer.append("Starting at line ").append(String.valueOf(mark.getBeginLine())).append(" of ").append(mark.getFilename())
.println();
}
writer.println(); // add a line to separate the source from the desc above
String source = match.getSourceCodeSlice();
if (trimLeadingWhitespace) {
for (Chars line : StringUtil.linesWithTrimIndent(source)) {
line.writeFully(writer);
writer.println();
}
return;
}
writer.println(source);
}
}
| 2,370 | 29.397436 | 142 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/Tokens.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Tokens {
private List<TokenEntry> tokens = new ArrayList<>();
public void add(TokenEntry tokenEntry) {
this.tokens.add(tokenEntry);
}
public Iterator<TokenEntry> iterator() {
return tokens.iterator();
}
private TokenEntry get(int index) {
return tokens.get(index);
}
public int size() {
return tokens.size();
}
public TokenEntry getEndToken(TokenEntry mark, Match match) {
return get(mark.getIndex() + match.getTokenCount() - 1);
}
public int getLineCount(TokenEntry mark, Match match) {
TokenEntry endTok = getEndToken(mark, match);
if (TokenEntry.EOF.equals(endTok)) {
endTok = get(mark.getIndex() + match.getTokenCount() - 2);
}
return endTok.getBeginLine() - mark.getBeginLine() + 1;
}
public List<TokenEntry> getTokens() {
return tokens;
}
}
| 1,122 | 22.893617 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/AnyLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
public class AnyLanguage extends AbstractLanguage {
public AnyLanguage(String... extensions) {
super("Any Language", "any", new AnyTokenizer(), extensions);
}
}
| 300 | 24.083333 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CPDNullListener.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.File;
public class CPDNullListener implements CPDListener {
@Override
public void addedFile(int fileCount, File file) {
// does nothing - override it if necessary
}
@Override
public void phaseUpdate(int phase) {
// does nothing - override it if necessary
}
}
| 439 | 21 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CPDReport.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.util.Predicate;
/**
* @since 6.48.0
*/
public class CPDReport {
private final List<Match> matches;
private final Map<String, Integer> numberOfTokensPerFile;
CPDReport(final List<Match> matches, final Map<String, Integer> numberOfTokensPerFile) {
this.matches = Collections.unmodifiableList(matches);
this.numberOfTokensPerFile = Collections.unmodifiableMap(new TreeMap<>(numberOfTokensPerFile));
}
public List<Match> getMatches() {
return matches;
}
public Map<String, Integer> getNumberOfTokensPerFile() {
return numberOfTokensPerFile;
}
/**
* Creates a new CPD report taking all the information from this report,
* but filtering the matches.
*
* @param filter when true, the match will be kept.
* @return copy of this report
*/
@Experimental
public CPDReport filterMatches(Predicate<Match> filter) {
List<Match> filtered = new ArrayList<>();
for (Match match : this.getMatches()) {
if (filter.test(match)) {
filtered.add(match);
}
}
return new CPDReport(filtered, this.getNumberOfTokensPerFile());
}
}
| 1,526 | 26.763636 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/Tokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
public interface Tokenizer {
String IGNORE_LITERALS = "ignore_literals";
String IGNORE_IDENTIFIERS = "ignore_identifiers";
String IGNORE_ANNOTATIONS = "ignore_annotations";
/**
* Ignore sequences of literals (e.g, <code>0,0,0,0...</code>).
*/
String OPTION_IGNORE_LITERAL_SEQUENCES = "net.sourceforge.pmd.cpd.Tokenizer.skipLiteralSequences";
/**
* Ignore comma separated sequences of identifies and literals (e.g, <code>a,b,0,0...</code>).
*
* @since 7.0.0
*/
String OPTION_IGNORE_IDENTIFIER_AND_LITERAL_SEQUENCES = "net.sourceforge.pmd.cpd.Tokenizer.skipSequences";
/**
* Ignore using directives in C#. The default value is <code>false</code>.
*/
String IGNORE_USINGS = "ignore_usings";
/**
* Enables or disabled skipping of blocks like a pre-processor. It is a
* boolean property. The default value is <code>true</code>.
*
* @see #OPTION_SKIP_BLOCKS_PATTERN
*/
String OPTION_SKIP_BLOCKS = "net.sourceforge.pmd.cpd.Tokenizer.skipBlocks";
/**
* Configures the pattern, to find the blocks to skip. It is a string
* property and contains of two parts, separated by {@code |}. The first
* part is the start pattern, the second part is the ending pattern. Default
* value is "{@code #if 0|#endif}".
*
* @see #DEFAULT_SKIP_BLOCKS_PATTERN
*/
String OPTION_SKIP_BLOCKS_PATTERN = "net.sourceforge.pmd.cpd.Tokenizer.skipBlocksPattern";
String DEFAULT_SKIP_BLOCKS_PATTERN = "#if 0|#endif";
void tokenize(SourceCode sourceCode, Tokens tokenEntries) throws IOException;
}
| 1,778 | 33.211538 | 110 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CPDConfiguration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FilenameFilter;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.sourceforge.pmd.AbstractConfiguration;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
import net.sourceforge.pmd.internal.util.FileFinder;
import net.sourceforge.pmd.internal.util.FileUtil;
/**
*
* @author Brian Remedios
* @author Romain Pelisse - <belaran@gmail.com>
*/
public class CPDConfiguration extends AbstractConfiguration {
public static final String DEFAULT_LANGUAGE = "java";
public static final String DEFAULT_RENDERER = "text";
private static final Map<String, Class<? extends CPDReportRenderer>> RENDERERS = new HashMap<>();
static {
RENDERERS.put(DEFAULT_RENDERER, SimpleRenderer.class);
RENDERERS.put("xml", XMLRenderer.class);
RENDERERS.put("csv", CSVRenderer.class);
RENDERERS.put("csv_with_linecount_per_file", CSVWithLinecountPerFileRenderer.class);
RENDERERS.put("vs", VSRenderer.class);
}
private Language language;
private int minimumTileSize;
private boolean skipDuplicates;
private String rendererName;
private CPDReportRenderer cpdReportRenderer;
private boolean ignoreLiterals;
private boolean ignoreIdentifiers;
private boolean ignoreAnnotations;
private boolean ignoreUsings;
private boolean ignoreLiteralSequences = false;
private boolean ignoreIdentifierAndLiteralSequences = false;
private boolean skipLexicalErrors = false;
private boolean noSkipBlocks = false;
private String skipBlocksPattern = Tokenizer.DEFAULT_SKIP_BLOCKS_PATTERN;
private List<File> files;
private String fileListPath;
private List<File> excludes;
private boolean nonRecursive;
private String uri;
private boolean help;
private boolean failOnViolation = true;
public SourceCode sourceCodeFor(File file) {
return new SourceCode(new SourceCode.FileCodeLoader(file, getSourceEncoding().name()));
}
public SourceCode sourceCodeFor(Reader reader, String sourceCodeName) {
return new SourceCode(new SourceCode.ReaderCodeLoader(reader, sourceCodeName));
}
public void postContruct() {
if (getLanguage() == null) {
setLanguage(CPDConfiguration.getLanguageFromString(DEFAULT_LANGUAGE));
}
if (getRendererName() == null) {
setRendererName(DEFAULT_RENDERER);
}
if (this.cpdReportRenderer == null) {
//may throw
CPDReportRenderer renderer = createRendererByName(getRendererName(), getSourceEncoding().name());
setRenderer(renderer);
}
}
static CPDReportRenderer createRendererByName(String name, String encoding) {
if (name == null || "".equals(name)) {
name = DEFAULT_RENDERER;
}
Class<? extends CPDReportRenderer> rendererClass = RENDERERS.get(name.toLowerCase(Locale.ROOT));
if (rendererClass == null) {
Class<?> klass;
try {
klass = Class.forName(name);
if (CPDReportRenderer.class.isAssignableFrom(klass)) {
rendererClass = (Class) klass;
} else {
throw new IllegalArgumentException("Class " + name + " does not implement " + CPDReportRenderer.class);
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot find class " + name);
}
}
CPDReportRenderer renderer = null;
try {
renderer = rendererClass.getDeclaredConstructor().newInstance();
setRendererEncoding(renderer, encoding);
} catch (Exception e) {
System.err.println("Couldn't instantiate renderer, defaulting to SimpleRenderer: " + e);
renderer = new SimpleRenderer();
}
return renderer;
}
private static void setRendererEncoding(Object renderer, String encoding)
throws IllegalAccessException, InvocationTargetException {
try {
PropertyDescriptor encodingProperty = new PropertyDescriptor("encoding", renderer.getClass());
Method method = encodingProperty.getWriteMethod();
if (method != null) {
method.invoke(renderer, encoding);
}
} catch (IntrospectionException ignored) {
// ignored - maybe this renderer doesn't have a encoding property
}
}
public static String[] getRenderers() {
String[] result = RENDERERS.keySet().toArray(new String[0]);
Arrays.sort(result);
return result;
}
public static Language getLanguageFromString(String languageString) {
return LanguageFactory.createLanguage(languageString);
}
public static void setSystemProperties(CPDConfiguration configuration) {
Properties properties = new Properties();
if (configuration.isIgnoreLiterals()) {
properties.setProperty(Tokenizer.IGNORE_LITERALS, "true");
} else {
properties.remove(Tokenizer.IGNORE_LITERALS);
}
if (configuration.isIgnoreIdentifiers()) {
properties.setProperty(Tokenizer.IGNORE_IDENTIFIERS, "true");
} else {
properties.remove(Tokenizer.IGNORE_IDENTIFIERS);
}
if (configuration.isIgnoreAnnotations()) {
properties.setProperty(Tokenizer.IGNORE_ANNOTATIONS, "true");
} else {
properties.remove(Tokenizer.IGNORE_ANNOTATIONS);
}
if (configuration.isIgnoreUsings()) {
properties.setProperty(Tokenizer.IGNORE_USINGS, "true");
} else {
properties.remove(Tokenizer.IGNORE_USINGS);
}
if (configuration.isIgnoreLiteralSequences()) {
properties.setProperty(Tokenizer.OPTION_IGNORE_LITERAL_SEQUENCES, "true");
} else {
properties.remove(Tokenizer.OPTION_IGNORE_LITERAL_SEQUENCES);
}
if (configuration.isIgnoreIdentifierAndLiteralSequences()) {
properties.setProperty(Tokenizer.OPTION_IGNORE_IDENTIFIER_AND_LITERAL_SEQUENCES, "true");
} else {
properties.remove(Tokenizer.OPTION_IGNORE_IDENTIFIER_AND_LITERAL_SEQUENCES);
}
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS, Boolean.toString(!configuration.isNoSkipBlocks()));
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS_PATTERN, configuration.getSkipBlocksPattern());
configuration.getLanguage().setProperties(properties);
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public int getMinimumTileSize() {
return minimumTileSize;
}
public void setMinimumTileSize(int minimumTileSize) {
this.minimumTileSize = minimumTileSize;
}
public boolean isSkipDuplicates() {
return skipDuplicates;
}
public void setSkipDuplicates(boolean skipDuplicates) {
this.skipDuplicates = skipDuplicates;
}
public String getRendererName() {
return rendererName;
}
public void setRendererName(String rendererName) {
this.rendererName = rendererName;
}
public CPDReportRenderer getCPDReportRenderer() {
return cpdReportRenderer;
}
public Tokenizer tokenizer() {
if (language == null) {
throw new IllegalStateException("Language is null.");
}
return language.getTokenizer();
}
public FilenameFilter filenameFilter() {
if (language == null) {
throw new IllegalStateException("Language is null.");
}
final FilenameFilter languageFilter = language.getFileFilter();
final Set<String> exclusions = new HashSet<>();
if (excludes != null) {
FileFinder finder = new FileFinder();
for (File excludedFile : excludes) {
if (excludedFile.isDirectory()) {
List<File> files = finder.findFilesFrom(excludedFile, languageFilter, true);
for (File f : files) {
exclusions.add(FileUtil.normalizeFilename(f.getAbsolutePath()));
}
} else {
exclusions.add(FileUtil.normalizeFilename(excludedFile.getAbsolutePath()));
}
}
}
return (dir, name) -> {
File f = new File(dir, name);
if (exclusions.contains(FileUtil.normalizeFilename(f.getAbsolutePath()))) {
System.err.println("Excluding " + f.getAbsolutePath());
return false;
}
return languageFilter.accept(dir, name);
};
}
void setRenderer(CPDReportRenderer renderer) {
this.cpdReportRenderer = renderer;
}
public boolean isIgnoreLiterals() {
return ignoreLiterals;
}
public void setIgnoreLiterals(boolean ignoreLiterals) {
this.ignoreLiterals = ignoreLiterals;
}
public boolean isIgnoreIdentifiers() {
return ignoreIdentifiers;
}
public void setIgnoreIdentifiers(boolean ignoreIdentifiers) {
this.ignoreIdentifiers = ignoreIdentifiers;
}
public boolean isIgnoreAnnotations() {
return ignoreAnnotations;
}
public void setIgnoreAnnotations(boolean ignoreAnnotations) {
this.ignoreAnnotations = ignoreAnnotations;
}
public boolean isIgnoreUsings() {
return ignoreUsings;
}
public void setIgnoreUsings(boolean ignoreUsings) {
this.ignoreUsings = ignoreUsings;
}
public boolean isIgnoreLiteralSequences() {
return ignoreLiteralSequences;
}
public void setIgnoreLiteralSequences(boolean ignoreLiteralSequences) {
this.ignoreLiteralSequences = ignoreLiteralSequences;
}
public boolean isIgnoreIdentifierAndLiteralSequences() {
return ignoreIdentifierAndLiteralSequences;
}
public void setIgnoreIdentifierAndLiteralSequences(boolean ignoreIdentifierAndLiteralSequences) {
this.ignoreIdentifierAndLiteralSequences = ignoreIdentifierAndLiteralSequences;
}
public boolean isSkipLexicalErrors() {
return skipLexicalErrors;
}
public void setSkipLexicalErrors(boolean skipLexicalErrors) {
this.skipLexicalErrors = skipLexicalErrors;
}
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
public String getFileListPath() {
return fileListPath;
}
public void setFileListPath(String fileListPath) {
this.fileListPath = fileListPath;
}
public String getURI() {
return uri;
}
public void setURI(String uri) {
this.uri = uri;
}
public List<File> getExcludes() {
return excludes;
}
public void setExcludes(List<File> excludes) {
this.excludes = excludes;
}
public boolean isNonRecursive() {
return nonRecursive;
}
public void setNonRecursive(boolean nonRecursive) {
this.nonRecursive = nonRecursive;
}
public boolean isHelp() {
return help;
}
public void setHelp(boolean help) {
this.help = help;
}
public boolean isNoSkipBlocks() {
return noSkipBlocks;
}
public void setNoSkipBlocks(boolean noSkipBlocks) {
this.noSkipBlocks = noSkipBlocks;
}
public String getSkipBlocksPattern() {
return skipBlocksPattern;
}
public void setSkipBlocksPattern(String skipBlocksPattern) {
this.skipBlocksPattern = skipBlocksPattern;
}
public boolean isFailOnViolation() {
return failOnViolation;
}
public void setFailOnViolation(boolean failOnViolation) {
this.failOnViolation = failOnViolation;
}
}
| 12,468 | 29.191283 | 123 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/AnyTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.util.StringUtil;
/**
* Simple tokenization into words and separators. Can ignore end-of-line
* comments and recognize double/single quoted string literals. It is
* not a goal to be very customizable, or have very high quality.
* Higher-quality lexers should be implemented with a lexer generator.
*
* <p>In PMD 7, this replaces AbstractTokenizer, which provided nearly
* no more functionality.
*/
public class AnyTokenizer implements Tokenizer {
private static final Pattern DEFAULT_PATTERN = makePattern("");
private static Pattern makePattern(String singleLineCommentStart) {
return Pattern.compile(
"\\w++" // either a word
+ eolCommentFragment(singleLineCommentStart) // a comment
+ "|[^\"'\\s]" // a single separator char
+ "|\"(?:[^\"\\\\]++|\\\\.)*+\"" // a double-quoted string
+ "|'(?:[^'\\\\]++|\\\\.)*+'" // a single-quoted string
+ "|\n" // or a newline (to count lines), note that sourcecode normalizes line endings
);
}
private final Pattern pattern;
private final String commentStart;
public AnyTokenizer() {
this(DEFAULT_PATTERN, "");
}
public AnyTokenizer(String eolCommentStart) {
this(makePattern(eolCommentStart), eolCommentStart);
}
private AnyTokenizer(Pattern pattern, String commentStart) {
this.pattern = pattern;
this.commentStart = commentStart;
}
private static String eolCommentFragment(String start) {
if (StringUtils.isBlank(start)) {
return "";
} else {
return "|(?:" + Pattern.quote(start) + "[^\n]*+)"; // note: sourcecode normalizes line endings
}
}
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) {
CharSequence text = sourceCode.getCodeBuffer();
Matcher matcher = pattern.matcher(text);
int lineNo = 1;
int lastLineStart = 0;
try {
while (matcher.find()) {
String image = matcher.group();
if (isComment(image)) {
continue;
} else if (StringUtils.isWhitespace(image)) {
lineNo++;
lastLineStart = matcher.end();
continue;
}
int bline = lineNo;
int bcol = 1 + matcher.start() - lastLineStart; // + 1 because columns are 1 based
int ecol = StringUtil.columnNumberAt(image, image.length()); // this already outputs a 1-based column
if (ecol == image.length() + 1) {
ecol = bcol + image.length(); // single-line token
} else {
// multiline, need to update the line count
lineNo += StringUtil.lineNumberAt(image, image.length()) - 1;
lastLineStart = matcher.start() + image.length() - ecol + 1;
}
tokenEntries.add(new TokenEntry(image, sourceCode.getFileName(), bline, bcol, ecol));
}
} finally {
tokenEntries.add(TokenEntry.getEOF());
}
}
private boolean isComment(String tok) {
return !commentStart.isEmpty() && tok.startsWith(commentStart);
}
}
| 3,581 | 34.82 | 117 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/Language.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.FilenameFilter;
import java.util.List;
import java.util.Properties;
public interface Language {
String getName();
String getTerseName();
Tokenizer getTokenizer();
FilenameFilter getFileFilter();
void setProperties(Properties properties);
List<String> getExtensions();
}
| 438 | 17.291667 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/VSRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
import java.io.Writer;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
public class VSRenderer implements CPDReportRenderer {
@Override
public void render(CPDReport report, Writer writer) throws IOException {
for (Match match: report.getMatches()) {
for (Mark mark : match) {
writer.append(mark.getFilename())
.append('(').append(String.valueOf(mark.getBeginLine())).append("):")
.append(" Between lines ").append(String.valueOf(mark.getBeginLine()))
.append(" and ").append(String.valueOf(mark.getBeginLine() + match.getLineCount()))
.append(System.lineSeparator());
}
}
writer.flush();
}
}
| 921 | 31.928571 | 105 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/Match.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Match implements Comparable<Match>, Iterable<Mark> {
private int tokenCount;
private Set<Mark> markSet = new TreeSet<>();
private String label;
public static final Comparator<Match> MATCHES_COMPARATOR = new Comparator<Match>() {
@Override
public int compare(Match ma, Match mb) {
return mb.getMarkCount() - ma.getMarkCount();
}
};
public static final Comparator<Match> LINES_COMPARATOR = new Comparator<Match>() {
@Override
public int compare(Match ma, Match mb) {
return mb.getLineCount() - ma.getLineCount();
}
};
public static final Comparator<Match> LABEL_COMPARATOR = new Comparator<Match>() {
@Override
public int compare(Match ma, Match mb) {
if (ma.getLabel() == null) {
return 1;
}
if (mb.getLabel() == null) {
return -1;
}
return mb.getLabel().compareTo(ma.getLabel());
}
};
public static final Comparator<Match> LENGTH_COMPARATOR = new Comparator<Match>() {
@Override
public int compare(Match ma, Match mb) {
return mb.getLineCount() - ma.getLineCount();
}
};
public Match(int tokenCount, Mark first, Mark second) {
markSet.add(first);
markSet.add(second);
this.tokenCount = tokenCount;
}
public Match(int tokenCount, TokenEntry first, TokenEntry second) {
this(tokenCount, new Mark(first), new Mark(second));
}
public int getMarkCount() {
return markSet.size();
}
public int getLineCount() {
return getMark(0).getLineCount();
}
public int getTokenCount() {
return this.tokenCount;
}
/** Newlines are normalized to \n. */
public String getSourceCodeSlice() {
return this.getMark(0).getSourceCodeSlice();
}
@Override
public Iterator<Mark> iterator() {
return markSet.iterator();
}
@Override
public int compareTo(Match other) {
int diff = other.getTokenCount() - getTokenCount();
if (diff != 0) {
return diff;
}
return getFirstMark().compareTo(other.getFirstMark());
}
public Mark getFirstMark() {
return getMark(0);
}
public Mark getSecondMark() {
return getMark(1);
}
@Override
public String toString() {
return "Match: \ntokenCount = " + tokenCount + "\nmarks = " + markSet.size();
}
public Set<Mark> getMarkSet() {
return markSet;
}
public int getEndIndex() {
return getMark(0).getToken().getIndex() + getTokenCount() - 1;
}
public void setMarkSet(Set<Mark> markSet) {
this.markSet = markSet;
}
public void setLabel(String aLabel) {
label = aLabel;
}
public String getLabel() {
return label;
}
public void addTokenEntry(TokenEntry entry) {
markSet.add(new Mark(entry));
}
private Mark getMark(int index) {
Mark result = null;
int i = 0;
for (Iterator<Mark> it = markSet.iterator(); it.hasNext() && i < index + 1;) {
result = it.next();
i++;
}
return result;
}
}
| 3,519 | 24.142857 | 88 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class MatchCollector {
private List<Match> matchList = new ArrayList<>();
private Map<Integer, Map<Integer, Match>> matchTree = new TreeMap<>();
private MatchAlgorithm ma;
public MatchCollector(MatchAlgorithm ma) {
this.ma = ma;
}
public void collect(List<TokenEntry> marks) {
// first get a pairwise collection of all maximal matches
for (int i = 0; i < marks.size() - 1; i++) {
TokenEntry mark1 = marks.get(i);
for (int j = i + 1; j < marks.size(); j++) {
TokenEntry mark2 = marks.get(j);
int diff = mark1.getIndex() - mark2.getIndex();
if (-diff < ma.getMinimumTileSize()) {
continue;
}
if (hasPreviousDupe(mark1, mark2)) {
continue;
}
// "match too small" check
int dupes = countDuplicateTokens(mark1, mark2);
if (dupes < ma.getMinimumTileSize()) {
continue;
}
// is it still too close together
if (diff + dupes >= 1) {
continue;
}
reportMatch(mark1, mark2, dupes);
}
}
}
private void reportMatch(TokenEntry mark1, TokenEntry mark2, int dupes) {
Map<Integer, Match> matches = matchTree.get(dupes);
if (matches == null) {
matches = new TreeMap<>();
matchTree.put(dupes, matches);
addNewMatch(mark1, mark2, dupes, matches);
} else {
Match matchA = matchTree.get(dupes).get(mark1.getIndex());
Match matchB = matchTree.get(dupes).get(mark2.getIndex());
if (matchA == null && matchB == null) {
addNewMatch(mark1, mark2, dupes, matches);
} else if (matchA == null) {
matchB.addTokenEntry(mark1);
matches.put(mark1.getIndex(), matchB);
} else if (matchB == null) {
matchA.addTokenEntry(mark2);
matches.put(mark2.getIndex(), matchA);
}
}
}
private void addNewMatch(TokenEntry mark1, TokenEntry mark2, int dupes, Map<Integer, Match> matches) {
Match match = new Match(dupes, mark1, mark2);
matches.put(mark1.getIndex(), match);
matches.put(mark2.getIndex(), match);
matchList.add(match);
}
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public List<Match> getMatches() {
Collections.sort(matchList);
return matchList;
}
private boolean hasPreviousDupe(TokenEntry mark1, TokenEntry mark2) {
return mark1.getIndex() != 0 && !matchEnded(ma.tokenAt(-1, mark1), ma.tokenAt(-1, mark2));
}
private int countDuplicateTokens(TokenEntry mark1, TokenEntry mark2) {
int index = 0;
while (!matchEnded(ma.tokenAt(index, mark1), ma.tokenAt(index, mark2))) {
index++;
}
return index;
}
private boolean matchEnded(TokenEntry token1, TokenEntry token2) {
return token1.getIdentifier() != token2.getIdentifier()
|| TokenEntry.EOF.equals(token1)
|| TokenEntry.EOF.equals(token2);
}
}
| 3,544 | 33.417476 | 106 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CSVWithLinecountPerFileRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
public class CSVWithLinecountPerFileRenderer extends CSVRenderer {
public CSVWithLinecountPerFileRenderer() {
super(true);
}
}
| 267 | 19.615385 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/XMLRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
import net.sourceforge.pmd.util.StringUtil;
/**
* @author Philippe T'Seyen - original implementation
* @author Romain Pelisse - javax.xml implementation
*
*/
public final class XMLRenderer implements CPDReportRenderer {
private String encoding;
/**
* Creates a XML Renderer with the default (platform dependent) encoding.
*/
public XMLRenderer() {
this(null);
}
/**
* Creates a XML Renderer with a specific output encoding.
*
* @param encoding
* the encoding to use or null. If null, default (platform
* dependent) encoding is used.
*/
public XMLRenderer(String encoding) {
setEncoding(encoding);
}
public void setEncoding(String encoding) {
if (encoding != null) {
this.encoding = encoding;
} else {
this.encoding = System.getProperty("file.encoding");
}
}
public String getEncoding() {
return this.encoding;
}
private Document createDocument() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
return parser.newDocument();
} catch (ParserConfigurationException e) {
throw new IllegalStateException(e);
}
}
private void dumpDocToWriter(Document doc, Writer writer) {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "codefragment");
transformer.transform(new DOMSource(doc), new StreamResult(writer));
} catch (TransformerException e) {
throw new IllegalStateException(e);
}
}
@Override
public void render(final CPDReport report, final Writer writer) throws IOException {
final Document doc = createDocument();
final Element root = doc.createElement("pmd-cpd");
final Map<String, Integer> numberOfTokensPerFile = report.getNumberOfTokensPerFile();
doc.appendChild(root);
final List<Map.Entry<String, Integer>> entries = new ArrayList<>(numberOfTokensPerFile.entrySet());
for (final Map.Entry<String, Integer> pair : entries) {
final Element fileElement = doc.createElement("file");
fileElement.setAttribute("path", pair.getKey());
fileElement.setAttribute("totalNumberOfTokens", String.valueOf(pair.getValue()));
root.appendChild(fileElement);
}
for (Match match : report.getMatches()) {
root.appendChild(addCodeSnippet(doc,
addFilesToDuplicationElement(doc, createDuplicationElement(doc, match), match), match));
}
dumpDocToWriter(doc, writer);
writer.flush();
}
private Element addFilesToDuplicationElement(Document doc, Element duplication, Match match) {
for (Mark mark : match) {
final Element file = doc.createElement("file");
file.setAttribute("line", String.valueOf(mark.getBeginLine()));
// only remove invalid characters, escaping is done by the DOM impl.
String filenameXml10 = StringUtil.removedInvalidXml10Characters(mark.getFilename());
file.setAttribute("path", filenameXml10);
file.setAttribute("endline", String.valueOf(mark.getEndLine()));
final int beginCol = mark.getBeginColumn();
final int endCol = mark.getEndColumn();
if (beginCol != -1) {
file.setAttribute("column", String.valueOf(beginCol));
}
if (endCol != -1) {
file.setAttribute("endcolumn", String.valueOf(endCol));
}
final int beginIndex = mark.getBeginTokenIndex();
final int endIndex = mark.getEndTokenIndex();
file.setAttribute("begintoken", String.valueOf(beginIndex));
if (endIndex != -1) {
file.setAttribute("endtoken", String.valueOf(endIndex));
}
duplication.appendChild(file);
}
return duplication;
}
private Element addCodeSnippet(Document doc, Element duplication, Match match) {
String codeSnippet = match.getSourceCodeSlice();
if (codeSnippet != null) {
// the code snippet has normalized line endings
String platformSpecific = codeSnippet.replace("\n", System.lineSeparator());
Element codefragment = doc.createElement("codefragment");
// only remove invalid characters, escaping is not necessary in CDATA.
// if the string contains the end marker of a CDATA section, then the DOM impl will
// create two cdata sections automatically.
codefragment.appendChild(doc.createCDATASection(StringUtil.removedInvalidXml10Characters(platformSpecific)));
duplication.appendChild(codefragment);
}
return duplication;
}
private Element createDuplicationElement(Document doc, Match match) {
Element duplication = doc.createElement("duplication");
duplication.setAttribute("lines", String.valueOf(match.getLineCount()));
duplication.setAttribute("tokens", String.valueOf(match.getTokenCount()));
return duplication;
}
}
| 6,493 | 38.357576 | 121 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/AbstractLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.sourceforge.pmd.internal.util.PredicateUtil;
public abstract class AbstractLanguage implements Language {
private final String name;
private final String terseName;
private final Tokenizer tokenizer;
private final Predicate<String> fileFilter;
private final List<String> extensions;
public AbstractLanguage(String name, String terseName, Tokenizer tokenizer, String... extensions) {
this(name, terseName, tokenizer, Arrays.asList(extensions));
}
protected AbstractLanguage(String name, String terseName, Tokenizer tokenizer, List<String> extensions) {
this.name = name;
this.terseName = terseName;
this.tokenizer = tokenizer;
List<String> extensionsWithDot = extensions.stream().map(e -> {
if (e.length() > 0 && e.charAt(0) != '.') {
return "." + e;
}
return e;
}).collect(Collectors.toList());
this.fileFilter = PredicateUtil.toNormalizedFileFilter(
PredicateUtil.getFileExtensionFilter(extensionsWithDot.toArray(new String[0]))
.or(it -> Files.isDirectory(Paths.get(it))));
this.extensions = extensionsWithDot;
}
@Override
public FilenameFilter getFileFilter() {
return (dir, name) -> fileFilter.test(dir.toPath().resolve(name).toString());
}
@Override
public Tokenizer getTokenizer() {
return tokenizer;
}
@Override
public void setProperties(Properties properties) {
// needs to be implemented by subclasses.
}
@Override
public String getName() {
return name;
}
@Override
public String getTerseName() {
return terseName;
}
@Override
public List<String> getExtensions() {
return extensions;
}
}
| 2,190 | 28.213333 | 109 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchAlgorithm.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class MatchAlgorithm {
private static final int MOD = 37;
private int lastMod = 1;
private List<Match> matches;
private Map<String, SourceCode> source;
private Tokens tokens;
private List<TokenEntry> code;
private CPDListener cpdListener;
private int min;
public MatchAlgorithm(Map<String, SourceCode> sourceCode, Tokens tokens, int min) {
this(sourceCode, tokens, min, new CPDNullListener());
}
public MatchAlgorithm(Map<String, SourceCode> sourceCode, Tokens tokens, int min, CPDListener listener) {
this.source = sourceCode;
this.tokens = tokens;
this.code = tokens.getTokens();
this.min = min;
this.cpdListener = listener;
for (int i = 0; i < min; i++) {
lastMod *= MOD;
}
}
public void setListener(CPDListener listener) {
this.cpdListener = listener;
}
public Iterator<Match> matches() {
return matches.iterator();
}
List<Match> getMatches() {
return matches;
}
public TokenEntry tokenAt(int offset, TokenEntry m) {
return code.get(offset + m.getIndex());
}
public int getMinimumTileSize() {
return this.min;
}
public void findMatches() {
cpdListener.phaseUpdate(CPDListener.HASH);
Map<TokenEntry, Object> markGroups = hash();
cpdListener.phaseUpdate(CPDListener.MATCH);
MatchCollector matchCollector = new MatchCollector(this);
for (Iterator<Object> i = markGroups.values().iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof List) {
@SuppressWarnings("unchecked")
List<TokenEntry> l = (List<TokenEntry>) o;
Collections.reverse(l);
matchCollector.collect(l);
}
i.remove();
}
cpdListener.phaseUpdate(CPDListener.GROUPING);
matches = matchCollector.getMatches();
for (Match match : matches) {
for (Mark mark : match) {
TokenEntry token = mark.getToken();
int lineCount = tokens.getLineCount(token, match);
TokenEntry endToken = tokens.getEndToken(token, match);
mark.setLineCount(lineCount);
mark.setEndToken(endToken);
SourceCode sourceCode = source.get(token.getTokenSrcID());
assert sourceCode != null : token.getTokenSrcID() + " is not registered in " + source.keySet();
mark.setSourceCode(sourceCode);
}
}
cpdListener.phaseUpdate(CPDListener.DONE);
}
@SuppressWarnings("PMD.JumbledIncrementer")
private Map<TokenEntry, Object> hash() {
int lastHash = 0;
Map<TokenEntry, Object> markGroups = new HashMap<>(tokens.size());
for (int i = code.size() - 1; i >= 0; i--) {
TokenEntry token = code.get(i);
if (!TokenEntry.EOF.equals(token)) {
int last = tokenAt(min, token).getIdentifier();
lastHash = MOD * lastHash + token.getIdentifier() - lastMod * last;
token.setHashCode(lastHash);
Object o = markGroups.get(token);
// Note that this insertion method is worthwhile since the vast
// majority
// markGroup keys will have only one value.
if (o == null) {
markGroups.put(token, token);
} else if (o instanceof TokenEntry) {
List<TokenEntry> l = new ArrayList<>();
l.add((TokenEntry) o);
l.add(token);
markGroups.put(token, l);
} else {
@SuppressWarnings("unchecked")
List<TokenEntry> l = (List<TokenEntry>) o;
l.add(token);
}
} else {
lastHash = 0;
for (int end = Math.max(0, i - min + 1); i > end; i--) {
token = code.get(i - 1);
lastHash = MOD * lastHash + token.getIdentifier();
if (TokenEntry.EOF.equals(token)) {
break;
}
}
}
}
return markGroups;
}
}
| 4,628 | 32.788321 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/GridBagHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
// stolen from XPath Explorer (http://www.xpathexplorer.com)
package net.sourceforge.pmd.cpd;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* @deprecated Is internal API
*/
@Deprecated
@InternalApi
public class GridBagHelper {
GridBagLayout gridbag;
Container container;
GridBagConstraints c;
int x = 0;
int y = 0;
int labelAlignment = SwingConstants.RIGHT;
double[] weights;
public GridBagHelper(Container container, double[] weights) {
this.container = container;
this.weights = weights;
gridbag = new GridBagLayout();
container.setLayout(gridbag);
c = new GridBagConstraints();
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.HORIZONTAL;
}
public void add(Component component) {
add(component, 1);
}
public void add(Component component, int width) {
c.gridx = x;
c.gridy = y;
c.weightx = weights[x];
c.gridwidth = width;
gridbag.setConstraints(component, c);
container.add(component);
x += width;
}
public void nextRow() {
y++;
x = 0;
}
public void addLabel(String label) {
add(new JLabel(label, labelAlignment));
}
}
| 1,610 | 22.014286 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CSVRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.apache.commons.lang3.StringEscapeUtils;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
public class CSVRenderer implements CPDReportRenderer {
private final char separator;
private final boolean lineCountPerFile;
public static final char DEFAULT_SEPARATOR = ',';
public static final boolean DEFAULT_LINECOUNTPERFILE = false;
public CSVRenderer() {
this(DEFAULT_SEPARATOR, DEFAULT_LINECOUNTPERFILE);
}
public CSVRenderer(boolean lineCountPerFile) {
this(DEFAULT_SEPARATOR, lineCountPerFile);
}
public CSVRenderer(char separatorChar) {
this(separatorChar, DEFAULT_LINECOUNTPERFILE);
}
public CSVRenderer(char separatorChar, boolean lineCountPerFile) {
this.separator = separatorChar;
this.lineCountPerFile = lineCountPerFile;
}
@Override
public void render(CPDReport report, Writer writer) throws IOException {
Iterator<Match> matches = report.getMatches().iterator();
if (!lineCountPerFile) {
writer.append("lines").append(separator);
}
writer.append("tokens").append(separator).append("occurrences").append(System.lineSeparator());
while (matches.hasNext()) {
Match match = matches.next();
if (!lineCountPerFile) {
writer.append(String.valueOf(match.getLineCount())).append(separator);
}
writer.append(String.valueOf(match.getTokenCount())).append(separator)
.append(String.valueOf(match.getMarkCount())).append(separator);
for (Iterator<Mark> marks = match.iterator(); marks.hasNext();) {
Mark mark = marks.next();
writer.append(String.valueOf(mark.getBeginLine())).append(separator);
if (lineCountPerFile) {
writer.append(String.valueOf(mark.getLineCount())).append(separator);
}
writer.append(StringEscapeUtils.escapeCsv(mark.getFilename()));
if (marks.hasNext()) {
writer.append(separator);
}
}
writer.append(System.lineSeparator());
}
writer.flush();
}
}
| 2,433 | 32.342466 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/AbstractTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.List;
import java.util.Locale;
/**
*
* @author Zev Blut zb@ubit.com
* @author Romain PELISSE belaran@gmail.com
*
* @deprecated Use an {@link AnyTokenizer} instead, it's basically as powerful.
*/
@Deprecated
public abstract class AbstractTokenizer implements Tokenizer {
// FIXME depending on subclasses to assign local vars is rather fragile -
// better to make private and setup via explicit hook methods
protected List<String> stringToken; // List<String>, should be set by sub
// classes
protected List<String> ignorableCharacter; // List<String>, should be set by
// sub classes
// FIXME:Maybe an array of 'char'
// would be better for
// performance ?
protected List<String> ignorableStmt; // List<String>, should be set by sub
// classes
protected char oneLineCommentChar = '#'; // Most script languages ( shell,
// ruby, python,...) use this
// symbol for comment line
private List<String> code;
private int lineNumber = 0;
private String currentLine;
// both zero-based
private int tokBeginLine;
private int tokBeginCol;
protected boolean spanMultipleLinesString = true; // Most languages do, so
// default is true
protected Character spanMultipleLinesLineContinuationCharacter = null;
private boolean downcaseString = true;
@Override
public void tokenize(SourceCode tokens, Tokens tokenEntries) {
code = tokens.getCode();
for (lineNumber = 0; lineNumber < code.size(); lineNumber++) {
currentLine = code.get(lineNumber);
int loc = 0;
while (loc < currentLine.length()) {
StringBuilder token = new StringBuilder();
loc = getTokenFromLine(token, loc); // may jump several lines
if (token.length() > 0 && !isIgnorableString(token.toString())) {
final String image;
if (downcaseString) {
image = token.toString().toLowerCase(Locale.ROOT);
} else {
image = token.toString();
}
tokenEntries.add(new TokenEntry(image,
tokens.getFileName(),
tokBeginLine + 1,
tokBeginCol + 1,
loc + 1));
}
}
}
tokenEntries.add(TokenEntry.getEOF());
}
/**
* Returns (0-based) EXclusive offset of the end of the token,
* may jump several lines (sets {@link #lineNumber} in this case).
*/
private int getTokenFromLine(StringBuilder token, int loc) {
tokBeginLine = lineNumber;
tokBeginCol = loc;
for (int j = loc; j < currentLine.length(); j++) {
char tok = currentLine.charAt(j);
if (!Character.isWhitespace(tok) && !ignoreCharacter(tok)) {
if (isComment(tok)) {
if (token.length() > 0) {
return j;
} else {
return getCommentToken(token, loc);
}
} else if (isString(tok)) {
if (token.length() > 0) {
return j; // we need to now parse the string as a
// separate token.
} else {
// we are at the start of a string
return parseString(token, j, tok);
}
} else {
token.append(tok);
}
} else {
if (token.length() > 0) {
return j;
} else {
// ignored char
tokBeginCol++;
}
}
loc = j;
}
return loc + 1;
}
private int parseString(StringBuilder token, int loc, char stringDelimiter) {
boolean escaped = false;
boolean done = false;
char tok;
while (loc < currentLine.length() && !done) {
tok = currentLine.charAt(loc);
if (escaped && tok == stringDelimiter) { // Found an escaped string
escaped = false;
} else if (tok == stringDelimiter && token.length() > 0) {
// We are done, we found the end of the string...
done = true;
} else {
// Found an escaped char?
escaped = tok == '\\';
}
// Adding char to String:" + token.toString());
token.append(tok);
loc++;
}
// Handling multiple lines string
if (!done // ... we didn't find the end of the string (but the end of the line)
&& spanMultipleLinesString // ... the language allow multiple line span Strings
&& lineNumber < code.size() - 1 // ... there is still more lines to parse
) {
// removes last character, if it is the line continuation (e.g.
// backslash) character
if (spanMultipleLinesLineContinuationCharacter != null
&& token.length() > 0
&& token.charAt(token.length() - 1) == spanMultipleLinesLineContinuationCharacter) {
token.setLength(token.length() - 1);
}
// parsing new line
currentLine = code.get(++lineNumber);
// Warning : recursive call !
loc = parseString(token, 0, stringDelimiter);
}
return loc;
}
private boolean ignoreCharacter(char tok) {
return ignorableCharacter.contains(String.valueOf(tok));
}
private boolean isString(char tok) {
return stringToken.contains(String.valueOf(tok));
}
private boolean isComment(char tok) {
return tok == oneLineCommentChar;
}
private int getCommentToken(StringBuilder token, int loc) {
while (loc < currentLine.length()) {
token.append(currentLine.charAt(loc++));
}
return loc;
}
private boolean isIgnorableString(String token) {
return ignorableStmt.contains(token);
}
}
| 6,454 | 34.273224 | 100 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/LanguageFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Comparator;
import java.util.Locale;
import java.util.Properties;
import net.sourceforge.pmd.internal.LanguageServiceBase;
public final class LanguageFactory extends LanguageServiceBase<Language> {
public static final String EXTENSION = "extension";
public static final String BY_EXTENSION = "by_extension";
private static final Comparator<Language> LANGUAGE_COMPARATOR = new Comparator<Language>() {
@Override
public int compare(Language o1, Language o2) {
return o1.getTerseName().compareToIgnoreCase(o2.getTerseName());
}
};
private static final NameExtractor<Language> NAME_EXTRACTOR = new NameExtractor<Language>() {
@Override
public String getName(Language language) {
return language.getName().toLowerCase(Locale.ROOT);
}
};
private static final NameExtractor<Language> TERSE_NAME_EXTRACTOR = new NameExtractor<Language>() {
@Override
public String getName(Language language) {
return language.getTerseName().toLowerCase(Locale.ROOT);
}
};
// Important: the "instance" needs to be defined *after* LANGUAGE_COMPARATOR and *NAME_EXTRACTOR
// as these are needed in the constructor.
private static final LanguageFactory INSTANCE = new LanguageFactory();
public static String[] supportedLanguages;
static {
supportedLanguages = INSTANCE.languagesByTerseName.keySet().toArray(new String[0]);
}
private LanguageFactory() {
super(Language.class, LANGUAGE_COMPARATOR, NAME_EXTRACTOR, TERSE_NAME_EXTRACTOR);
}
public static Language createLanguage(String language) {
return createLanguage(language, new Properties());
}
public static Language createLanguage(String language, Properties properties) {
Language implementation;
if (BY_EXTENSION.equals(language)) {
implementation = INSTANCE.getLanguageByExtension(properties.getProperty(EXTENSION));
} else {
implementation = INSTANCE.languagesByTerseName.get(INSTANCE.languageAliases(language).toLowerCase(Locale.ROOT));
}
if (implementation == null) {
// No proper implementation
// FIXME: We should log a warning, shouldn't we ?
implementation = new AnyLanguage(language);
}
implementation.setProperties(properties);
return implementation;
}
private String languageAliases(String language) {
// CPP and C language share the same parser
if ("c".equals(language)) {
return "cpp";
}
return language;
}
private Language getLanguageByExtension(String extension) {
Language result = null;
for (Language language : languages) {
if (language.getExtensions().contains(extension)) {
result = language;
break;
}
}
return result;
}
}
| 3,108 | 32.430108 | 124 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/SourceCode.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.ref.SoftReference;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.internal.util.IOUtil;
public class SourceCode {
public abstract static class CodeLoader {
private SoftReference<List<String>> code;
public List<String> getCode() {
List<String> c = null;
if (code != null) {
c = code.get();
}
if (c != null) {
return c;
}
this.code = new SoftReference<>(load());
return code.get();
}
/**
* Loads a range of lines.
*
* @param startLine Start line (inclusive, 1-based)
* @param endLine End line (inclusive, 1-based)
*/
public List<String> getCodeSlice(int startLine, int endLine) {
List<String> c = null;
if (code != null) {
c = code.get();
}
if (c != null) {
return c.subList(startLine - 1, endLine);
}
return load(startLine, endLine);
}
public abstract String getFileName();
protected abstract Reader getReader() throws Exception;
protected List<String> load() {
try (BufferedReader reader = new BufferedReader(getReader())) {
List<String> lines = new ArrayList<>();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
lines.add(currentLine);
}
return lines;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Problem while reading " + getFileName() + ":" + e.getMessage());
}
}
/**
* Loads a range of lines.
*
* @param startLine Start line (inclusive, 1-based)
* @param endLine End line (inclusive, 1-based)
*/
protected List<String> load(int startLine, int endLine) {
try (BufferedReader reader = new BufferedReader(getReader())) {
int linesToRead = 1 + endLine - startLine; // +1 because endLine is inclusive
List<String> lines = new ArrayList<>(linesToRead);
// Skip lines until we reach the start point
for (int i = 0; i < startLine - 1; i++) {
reader.readLine();
}
String currentLine;
while ((currentLine = reader.readLine()) != null) {
lines.add(currentLine);
if (lines.size() == linesToRead) {
break;
}
}
return lines;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Problem while reading " + getFileName() + ":" + e.getMessage());
}
}
}
public static class FileCodeLoader extends CodeLoader {
private File file;
private String encoding;
public FileCodeLoader(File file, String encoding) {
this.file = file;
this.encoding = encoding;
}
@Override
public Reader getReader() throws Exception {
IOUtil.BomAwareInputStream inputStream = new IOUtil.BomAwareInputStream(Files.newInputStream(file.toPath()));
if (inputStream.hasBom()) {
encoding = inputStream.getBomCharsetName();
}
return new InputStreamReader(inputStream, encoding);
}
public String getEncoding() {
return encoding;
}
@Override
public String getFileName() {
return file.getAbsolutePath();
}
}
public static class StringCodeLoader extends CodeLoader {
public static final String DEFAULT_NAME = "CODE_LOADED_FROM_STRING";
private String code;
private String name;
public StringCodeLoader(String code) {
this(code, DEFAULT_NAME);
}
public StringCodeLoader(String code, String name) {
this.code = code;
this.name = name;
}
@Override
public Reader getReader() {
return new StringReader(code);
}
@Override
public String getFileName() {
return name;
}
}
public static class ReaderCodeLoader extends CodeLoader {
public static final String DEFAULT_NAME = "CODE_LOADED_FROM_READER";
private Reader code;
private String name;
public ReaderCodeLoader(Reader code) {
this(code, DEFAULT_NAME);
}
public ReaderCodeLoader(Reader code, String name) {
this.code = code;
this.name = name;
}
@Override
public Reader getReader() {
return code;
}
@Override
public String getFileName() {
return name;
}
}
private CodeLoader cl;
public SourceCode(CodeLoader cl) {
this.cl = cl;
}
public List<String> getCode() {
return cl.getCode();
}
/** Newlines are normalized to \n. */
public StringBuilder getCodeBuffer() {
StringBuilder sb = new StringBuilder();
List<String> lines = cl.getCode();
for (String line : lines) {
sb.append(line).append('\n');
}
return sb;
}
/**
* Loads a range of lines. Newlines are normalized to \n
*
* @param startLine Start line (inclusive, 1-based)
* @param endLine End line (inclusive, 1-based)
*/
public String getSlice(int startLine, int endLine) {
List<String> lines = cl.getCodeSlice(startLine, endLine);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
if (sb.length() != 0) {
sb.append('\n');
}
sb.append(line);
}
return sb.toString();
}
public String getFileName() {
return cl.getFileName();
}
public Reader getReader() throws Exception {
return cl.getReader();
}
}
| 6,538 | 27.064378 | 121 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/Mark.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
public class Mark implements Comparable<Mark> {
private TokenEntry token;
private TokenEntry endToken;
private int lineCount;
private SourceCode code;
public Mark(TokenEntry token) {
this.token = token;
}
public TokenEntry getToken() {
return this.token;
}
public String getFilename() {
return this.token.getTokenSrcID();
}
public int getBeginLine() {
return this.token.getBeginLine();
}
/**
* The column number where this duplication begins.
* returns -1 if not available
* @return the begin column number
*/
public int getBeginColumn() {
return this.token.getBeginColumn(); // TODO Java 1.8 make optional
}
public int getBeginTokenIndex() {
return this.token.getIndex();
}
public int getEndLine() {
return getBeginLine() + getLineCount() - 1;
}
/**
* The column number where this duplication ends.
* returns -1 if not available
* @return the end column number
*/
public int getEndColumn() {
return this.endToken == null ? -1 : this.endToken.getEndColumn(); // TODO Java 1.8 make optional
}
public int getEndTokenIndex() {
return this.endToken == null ? -1 : this.endToken.getIndex();
}
public int getLineCount() {
return this.lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
public void setEndToken(TokenEntry endToken) {
this.endToken = endToken;
}
/** Newlines are normalized to \n. */
public String getSourceCodeSlice() {
return this.code.getSlice(getBeginLine(), getEndLine());
}
public void setSourceCode(SourceCode code) {
this.code = code;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((token == null) ? 0 : token.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;
}
Mark other = (Mark) obj;
if (token == null) {
if (other.token != null) {
return false;
}
} else if (!token.equals(other.token)) {
return false;
}
return true;
}
@Override
public int compareTo(Mark other) {
return getToken().compareTo(other.getToken());
}
}
| 2,752 | 22.93913 | 104 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/GUI.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.cpd.renderer.CPDReportRenderer;
public class GUI implements CPDListener {
private static final Object[][] RENDERER_SETS = {
{ "Text", new SimpleRenderer(), },
{ "XML", new XMLRenderer(), },
{ "CSV (comma)", new CSVRenderer(','), },
{ "CSV (tab)", new CSVRenderer('\t'), }, };
private abstract static class LanguageConfig {
public abstract Language languageFor(Properties p);
public boolean canIgnoreIdentifiers() {
return false;
}
public boolean canIgnoreLiterals() {
return false;
}
public boolean canIgnoreAnnotations() {
return false;
}
public boolean canIgnoreUsings() {
return false;
}
public boolean canIgnoreLiteralSequences() {
return false;
}
public boolean canIgnoreIdentifierAndLiteralSequences() {
return false;
}
public abstract String[] extensions();
}
private static final Object[][] LANGUAGE_SETS;
static {
LANGUAGE_SETS = new Object[LanguageFactory.supportedLanguages.length + 1][2];
int index;
for (index = 0; index < LanguageFactory.supportedLanguages.length; index++) {
final String terseName = LanguageFactory.supportedLanguages[index];
final Language lang = LanguageFactory.createLanguage(terseName);
LANGUAGE_SETS[index][0] = lang.getName();
LANGUAGE_SETS[index][1] = new LanguageConfig() {
@Override
public Language languageFor(Properties p) {
lang.setProperties(p);
return lang;
}
@Override
public String[] extensions() {
List<String> exts = lang.getExtensions();
return exts.toArray(new String[0]);
}
@Override
public boolean canIgnoreAnnotations() {
if (terseName == null) {
return false;
}
switch (terseName) {
case "cs":
case "java":
return true;
default:
return false;
}
}
@Override
public boolean canIgnoreIdentifiers() {
return "java".equals(terseName);
}
@Override
public boolean canIgnoreLiterals() {
return "java".equals(terseName);
}
@Override
public boolean canIgnoreUsings() {
return "cs".equals(terseName);
}
@Override
public boolean canIgnoreLiteralSequences() {
if (terseName == null) {
return false;
}
switch (terseName) {
case "cpp":
case "cs":
case "lua":
return true;
default:
return false;
}
}
@Override
public boolean canIgnoreIdentifierAndLiteralSequences() {
return "cpp".equals(terseName);
}
};
}
LANGUAGE_SETS[index][0] = "by extension...";
LANGUAGE_SETS[index][1] = new LanguageConfig() {
@Override
public Language languageFor(Properties p) {
return LanguageFactory.createLanguage(LanguageFactory.BY_EXTENSION, p);
}
@Override
public String[] extensions() {
return new String[] { "" };
}
};
}
private static final int DEFAULT_CPD_MINIMUM_LENGTH = 75;
private static final Map<String, LanguageConfig> LANGUAGE_CONFIGS_BY_LABEL = new HashMap<>(LANGUAGE_SETS.length);
private static final KeyStroke COPY_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK,
false);
private static final KeyStroke DELETE_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
private class ColumnSpec {
private String label;
private int alignment;
private int width;
private Comparator<Match> sorter;
ColumnSpec(String aLabel, int anAlignment, int aWidth, Comparator<Match> aSorter) {
label = aLabel;
alignment = anAlignment;
width = aWidth;
sorter = aSorter;
}
public String label() {
return label;
}
public int alignment() {
return alignment;
}
public int width() {
return width;
}
public Comparator<Match> sorter() {
return sorter;
}
}
private final ColumnSpec[] matchColumns = new ColumnSpec[] {
new ColumnSpec("Source", SwingConstants.LEFT, -1, Match.LABEL_COMPARATOR),
new ColumnSpec("Matches", SwingConstants.RIGHT, 60, Match.MATCHES_COMPARATOR),
new ColumnSpec("Lines", SwingConstants.RIGHT, 45, Match.LINES_COMPARATOR), };
static {
for (int i = 0; i < LANGUAGE_SETS.length; i++) {
LANGUAGE_CONFIGS_BY_LABEL.put((String) LANGUAGE_SETS[i][0], (LanguageConfig) LANGUAGE_SETS[i][1]);
}
}
private static LanguageConfig languageConfigFor(String label) {
return LANGUAGE_CONFIGS_BY_LABEL.get(label);
}
private static final class CancelListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private final class GoListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
tokenizingFilesBar.setValue(0);
tokenizingFilesBar.setString("");
resultsTextArea.setText("");
phaseLabel.setText("");
timeField.setText("");
go();
}
}).start();
}
}
private class SaveListener implements ActionListener {
final CPDReportRenderer renderer;
SaveListener(CPDReportRenderer theRenderer) {
renderer = theRenderer;
}
@Override
public void actionPerformed(ActionEvent evt) {
JFileChooser fcSave = new JFileChooser();
int ret = fcSave.showSaveDialog(GUI.this.frame);
File f = fcSave.getSelectedFile();
if (f == null || ret != JFileChooser.APPROVE_OPTION) {
return;
}
if (!f.canWrite()) {
final CPDReport report = new CPDReport(matches, numberOfTokensPerFile);
try (PrintWriter pw = new PrintWriter(Files.newOutputStream(f.toPath()))) {
renderer.render(report, pw);
pw.flush();
JOptionPane.showMessageDialog(frame, "Saved " + matches.size() + " matches");
} catch (IOException e) {
error("Couldn't save file" + f.getAbsolutePath(), e);
}
} else {
error("Could not write to file " + f.getAbsolutePath(), null);
}
}
private void error(String message, Exception e) {
if (e != null) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(GUI.this.frame, message);
}
}
private final class BrowseListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser(rootDirectoryField.getText());
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.showDialog(frame, "Select");
if (fc.getSelectedFile() != null) {
rootDirectoryField.setText(fc.getSelectedFile().getAbsolutePath());
}
}
}
private class AlignmentRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = -2190382865483285032L;
private int[] alignments;
AlignmentRenderer(int[] theAlignments) {
alignments = theAlignments;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(alignments[column]);
return this;
}
}
private JTextField rootDirectoryField = new JTextField(System.getProperty("user.home"));
private JTextField minimumLengthField = new JTextField(Integer.toString(DEFAULT_CPD_MINIMUM_LENGTH));
private JTextField encodingField = new JTextField(System.getProperty("file.encoding"));
private JTextField timeField = new JTextField(6);
private JLabel phaseLabel = new JLabel();
private JProgressBar tokenizingFilesBar = new JProgressBar();
private JTextArea resultsTextArea = new JTextArea();
private JCheckBox recurseCheckbox = new JCheckBox("", true);
private JCheckBox ignoreIdentifiersCheckbox = new JCheckBox("", false);
private JCheckBox ignoreLiteralsCheckbox = new JCheckBox("", false);
private JCheckBox ignoreAnnotationsCheckbox = new JCheckBox("", false);
private JCheckBox ignoreUsingsCheckbox = new JCheckBox("", false);
private JCheckBox ignoreLiteralSequencesCheckbox = new JCheckBox("", false);
private JCheckBox ignoreIdentifierAndLiteralSequencesCheckbox = new JCheckBox("", false);
private JComboBox<String> languageBox = new JComboBox<>();
private JTextField extensionField = new JTextField();
private JLabel extensionLabel = new JLabel("Extension:", SwingConstants.RIGHT);
private JTable resultsTable = new JTable();
private JButton goButton;
private JButton cancelButton;
private JPanel progressPanel;
private JFrame frame;
private boolean trimLeadingWhitespace;
private List<Match> matches = new ArrayList<>();
private Map<String, Integer> numberOfTokensPerFile;
private void addSaveOptionsTo(JMenu menu) {
JMenuItem saveItem;
for (final Object[] rendererSet : RENDERER_SETS) {
saveItem = new JMenuItem("Save as " + rendererSet[0]);
saveItem.addActionListener(new SaveListener((CPDReportRenderer) rendererSet[1]));
menu.add(saveItem);
}
}
public GUI() {
frame = new JFrame("PMD Duplicate Code Detector (v " + PMDVersion.VERSION + ')');
timeField.setEditable(false);
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('f');
addSaveOptionsTo(fileMenu);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
exitItem.addActionListener(new CancelListener());
fileMenu.add(exitItem);
JMenu viewMenu = new JMenu("View");
fileMenu.setMnemonic('v');
JMenuItem trimItem = new JCheckBoxMenuItem("Trim leading whitespace");
trimItem.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
AbstractButton button = (AbstractButton) e.getItem();
GUI.this.trimLeadingWhitespace = button.isSelected();
}
});
viewMenu.add(trimItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(viewMenu);
frame.setJMenuBar(menuBar);
// first make all the buttons
JButton browseButton = new JButton("Browse");
browseButton.setMnemonic('b');
browseButton.addActionListener(new BrowseListener());
goButton = new JButton("Go");
goButton.setMnemonic('g');
goButton.addActionListener(new GoListener());
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new CancelListener());
JPanel settingsPanel = makeSettingsPanel(browseButton, goButton, cancelButton);
progressPanel = makeProgressPanel();
JPanel resultsPanel = makeResultsPanel();
adjustLanguageControlsFor((LanguageConfig) LANGUAGE_SETS[0][1]);
frame.getContentPane().setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.add(settingsPanel, BorderLayout.NORTH);
topPanel.add(progressPanel, BorderLayout.CENTER);
setProgressControls(false); // not running now
frame.getContentPane().add(topPanel, BorderLayout.NORTH);
frame.getContentPane().add(resultsPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void adjustLanguageControlsFor(LanguageConfig current) {
ignoreIdentifiersCheckbox.setEnabled(current.canIgnoreIdentifiers());
ignoreLiteralsCheckbox.setEnabled(current.canIgnoreLiterals());
ignoreAnnotationsCheckbox.setEnabled(current.canIgnoreAnnotations());
ignoreUsingsCheckbox.setEnabled(current.canIgnoreUsings());
ignoreLiteralSequencesCheckbox.setEnabled(current.canIgnoreLiteralSequences());
ignoreIdentifierAndLiteralSequencesCheckbox.setEnabled(current.canIgnoreIdentifierAndLiteralSequences());
extensionField.setText(current.extensions()[0]);
boolean enableExtension = current.extensions()[0].isEmpty();
extensionField.setEnabled(enableExtension);
extensionLabel.setEnabled(enableExtension);
}
private JPanel makeSettingsPanel(JButton browseButton, JButton goButton, JButton cxButton) {
JPanel settingsPanel = new JPanel();
GridBagHelper helper = new GridBagHelper(settingsPanel, new double[] { 0.2, 0.7, 0.1, 0.1 });
helper.addLabel("Root source directory:");
helper.add(rootDirectoryField);
helper.add(browseButton, 2);
helper.nextRow();
helper.addLabel("Report duplicate chunks larger than:");
minimumLengthField.setColumns(4);
helper.add(minimumLengthField);
helper.addLabel("Language:");
for (int i = 0; i < LANGUAGE_SETS.length; i++) {
languageBox.addItem(String.valueOf(LANGUAGE_SETS[i][0]));
}
languageBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
adjustLanguageControlsFor(languageConfigFor((String) languageBox.getSelectedItem()));
}
});
helper.add(languageBox);
helper.nextRow();
helper.addLabel("Also scan subdirectories?");
helper.add(recurseCheckbox);
helper.add(extensionLabel);
helper.add(extensionField);
helper.nextRow();
helper.addLabel("Ignore literals?");
helper.add(ignoreLiteralsCheckbox);
helper.addLabel("");
helper.addLabel("");
helper.nextRow();
helper.nextRow();
helper.addLabel("Ignore identifiers?");
helper.add(ignoreIdentifiersCheckbox);
helper.addLabel("");
helper.addLabel("");
helper.nextRow();
helper.nextRow();
helper.addLabel("Ignore annotations?");
helper.add(ignoreAnnotationsCheckbox);
helper.addLabel("");
helper.addLabel("");
helper.nextRow();
helper.nextRow();
helper.addLabel("Ignore usings?");
helper.add(ignoreUsingsCheckbox);
helper.addLabel("");
helper.addLabel("");
helper.nextRow();
helper.nextRow();
helper.addLabel("Ignore literal sequences?");
helper.add(ignoreLiteralSequencesCheckbox);
helper.add(goButton);
helper.add(cxButton);
helper.nextRow();
helper.nextRow();
helper.addLabel("Ignore identifier and literal sequences?");
helper.add(ignoreIdentifierAndLiteralSequencesCheckbox);
helper.add(goButton);
helper.add(cxButton);
helper.nextRow();
helper.addLabel("File encoding (defaults based upon locale):");
encodingField.setColumns(1);
helper.add(encodingField);
helper.addLabel("");
helper.addLabel("");
helper.nextRow();
// settingsPanel.setBorder(BorderFactory.createTitledBorder("Settings"));
return settingsPanel;
}
private JPanel makeProgressPanel() {
JPanel progressPanel = new JPanel();
final double[] weights = { 0.0, 0.8, 0.4, 0.2 };
GridBagHelper helper = new GridBagHelper(progressPanel, weights);
helper.addLabel("Tokenizing files:");
helper.add(tokenizingFilesBar, 3);
helper.nextRow();
helper.addLabel("Phase:");
helper.add(phaseLabel);
helper.addLabel("Time elapsed:");
helper.add(timeField);
helper.nextRow();
progressPanel.setBorder(BorderFactory.createTitledBorder("Progress"));
return progressPanel;
}
private JPanel makeResultsPanel() {
JPanel resultsPanel = new JPanel();
resultsPanel.setLayout(new BorderLayout());
JScrollPane areaScrollPane = new JScrollPane(resultsTextArea);
resultsTextArea.setEditable(false);
areaScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(600, 300));
resultsPanel.add(makeMatchList(), BorderLayout.WEST);
resultsPanel.add(areaScrollPane, BorderLayout.CENTER);
return resultsPanel;
}
private void populateResultArea() {
int[] selectionIndices = resultsTable.getSelectedRows();
TableModel model = resultsTable.getModel();
List<Match> selections = new ArrayList<>(selectionIndices.length);
for (int selectionIndex : selectionIndices) {
selections.add((Match) model.getValueAt(selectionIndex, 99));
}
CPDReport toRender = new CPDReport(selections, Collections.emptyMap());
String report = new SimpleRenderer(trimLeadingWhitespace).renderToString(toRender);
resultsTextArea.setText(report);
resultsTextArea.setCaretPosition(0); // move to the top
}
private void copyMatchListSelectionsToClipboard() {
int[] selectionIndices = resultsTable.getSelectedRows();
int colCount = resultsTable.getColumnCount();
StringBuilder sb = new StringBuilder();
for (int r = 0; r < selectionIndices.length; r++) {
if (r > 0) {
sb.append('\n');
}
sb.append(resultsTable.getValueAt(selectionIndices[r], 0));
for (int c = 1; c < colCount; c++) {
sb.append('\t');
sb.append(resultsTable.getValueAt(selectionIndices[r], c));
}
}
StringSelection ss = new StringSelection(sb.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
private void deleteMatchlistSelections() {
int[] selectionIndices = resultsTable.getSelectedRows();
for (int i = selectionIndices.length - 1; i >= 0; i--) {
matches.remove(selectionIndices[i]);
}
resultsTable.getSelectionModel().clearSelection();
resultsTable.addNotify();
}
private JComponent makeMatchList() {
resultsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
populateResultArea();
}
});
resultsTable.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyMatchListSelectionsToClipboard();
}
}, "Copy", COPY_KEY_STROKE, JComponent.WHEN_FOCUSED);
resultsTable.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteMatchlistSelections();
}
}, "Del", DELETE_KEY_STROKE, JComponent.WHEN_FOCUSED);
int[] alignments = new int[matchColumns.length];
for (int i = 0; i < alignments.length; i++) {
alignments[i] = matchColumns[i].alignment();
}
resultsTable.setDefaultRenderer(Object.class, new AlignmentRenderer(alignments));
final JTableHeader header = resultsTable.getTableHeader();
header.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
sortOnColumn(header.columnAtPoint(new Point(e.getX(), e.getY())));
}
});
return new JScrollPane(resultsTable);
}
private boolean isLegalPath(String path, LanguageConfig config) {
String[] extensions = config.extensions();
for (int i = 0; i < extensions.length; i++) {
if (path.endsWith(extensions[i]) && !extensions[i].isEmpty()) {
return true;
}
}
return false;
}
private String setLabelFor(Match match) {
Set<String> sourceIDs = new HashSet<>(match.getMarkCount());
for (Iterator<Mark> occurrences = match.iterator(); occurrences.hasNext();) {
sourceIDs.add(occurrences.next().getFilename());
}
String label;
if (sourceIDs.size() == 1) {
String sourceId = sourceIDs.iterator().next();
int separatorPos = sourceId.lastIndexOf(File.separatorChar);
label = "..." + sourceId.substring(separatorPos);
} else {
label = String.format("(%d separate files)", sourceIDs.size());
}
match.setLabel(label);
return label;
}
private void setProgressControls(boolean isRunning) {
progressPanel.setVisible(isRunning);
goButton.setEnabled(!isRunning);
cancelButton.setEnabled(isRunning);
}
private void go() {
try {
File dirPath = new File(rootDirectoryField.getText());
if (!dirPath.exists()) {
JOptionPane.showMessageDialog(frame, "Can't read from that root source directory", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
setProgressControls(true);
Properties p = new Properties();
CPDConfiguration config = new CPDConfiguration();
config.setMinimumTileSize(Integer.parseInt(minimumLengthField.getText()));
config.setSourceEncoding(encodingField.getText());
config.setIgnoreIdentifiers(ignoreIdentifiersCheckbox.isSelected());
config.setIgnoreLiterals(ignoreLiteralsCheckbox.isSelected());
config.setIgnoreAnnotations(ignoreAnnotationsCheckbox.isSelected());
config.setIgnoreUsings(ignoreUsingsCheckbox.isSelected());
config.setIgnoreLiteralSequences(ignoreLiteralSequencesCheckbox.isSelected());
config.setIgnoreIdentifierAndLiteralSequences(ignoreIdentifierAndLiteralSequencesCheckbox.isSelected());
p.setProperty(LanguageFactory.EXTENSION, extensionField.getText());
LanguageConfig conf = languageConfigFor((String) languageBox.getSelectedItem());
Language language = conf.languageFor(p);
config.setLanguage(language);
CPDConfiguration.setSystemProperties(config);
CPD cpd = new CPD(config);
cpd.setCpdListener(this);
tokenizingFilesBar.setMinimum(0);
phaseLabel.setText("");
if (isLegalPath(dirPath.getPath(), conf)) { // should use the
// language file filter
// instead?
cpd.add(dirPath);
} else {
if (recurseCheckbox.isSelected()) {
cpd.addRecursively(dirPath);
} else {
cpd.addAllInDirectory(dirPath);
}
}
Timer t = createTimer();
t.start();
cpd.go();
t.stop();
CPDReport cpdReport = cpd.toReport();
numberOfTokensPerFile = cpdReport.getNumberOfTokensPerFile();
matches = new ArrayList<>();
for (Match match : cpdReport.getMatches()) {
setLabelFor(match);
matches.add(match);
}
setListDataFrom(matches);
String report = new SimpleRenderer().renderToString(cpdReport);
if (report.length() == 0) {
JOptionPane.showMessageDialog(frame,
"Done. Couldn't find any duplicates longer than " + minimumLengthField.getText() + " tokens");
} else {
resultsTextArea.setText(report);
}
} catch (IOException | RuntimeException t) {
t.printStackTrace();
JOptionPane.showMessageDialog(frame, "Halted due to " + t.getClass().getName() + "; " + t.getMessage());
}
setProgressControls(false);
}
private Timer createTimer() {
final long start = System.currentTimeMillis();
return new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
long now = System.currentTimeMillis();
long elapsedMillis = now - start;
long elapsedSeconds = elapsedMillis / 1000;
long minutes = (long) Math.floor(elapsedSeconds / 60);
long seconds = elapsedSeconds - minutes * 60;
timeField.setText(formatTime(minutes, seconds));
}
});
}
private static String formatTime(long minutes, long seconds) {
StringBuilder sb = new StringBuilder(5);
if (minutes < 10) {
sb.append('0');
}
sb.append(minutes).append(':');
if (seconds < 10) {
sb.append('0');
}
sb.append(seconds);
return sb.toString();
}
private abstract class SortingTableModel<E> extends AbstractTableModel {
abstract int sortColumn();
abstract void sortColumn(int column);
abstract boolean sortDescending();
abstract void sortDescending(boolean flag);
abstract void sort(Comparator<E> comparator);
}
private TableModel tableModelFrom(final List<Match> items) {
return new SortingTableModel<Match>() {
private int sortColumn;
private boolean sortDescending;
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Match match = items.get(rowIndex);
switch (columnIndex) {
case 0:
return match.getLabel();
case 2:
return Integer.toString(match.getLineCount());
case 1:
return match.getMarkCount() > 2 ? Integer.toString(match.getMarkCount()) : "";
case 99:
return match;
default:
return "";
}
}
@Override
public int getColumnCount() {
return matchColumns.length;
}
@Override
public int getRowCount() {
return items.size();
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
@Override
public String getColumnName(int i) {
return matchColumns[i].label();
}
@Override
public int sortColumn() {
return sortColumn;
}
@Override
public void sortColumn(int column) {
sortColumn = column;
}
@Override
public boolean sortDescending() {
return sortDescending;
}
@Override
public void sortDescending(boolean flag) {
sortDescending = flag;
}
@Override
public void sort(Comparator<Match> comparator) {
Collections.sort(items, comparator);
if (sortDescending) {
Collections.reverse(items);
}
}
};
}
private void sortOnColumn(int columnIndex) {
Comparator<Match> comparator = matchColumns[columnIndex].sorter();
SortingTableModel<Match> model = (SortingTableModel<Match>) resultsTable.getModel();
if (model.sortColumn() == columnIndex) {
model.sortDescending(!model.sortDescending());
}
model.sortColumn(columnIndex);
model.sort(comparator);
resultsTable.getSelectionModel().clearSelection();
resultsTable.repaint();
}
private void setListDataFrom(List<Match> matches) {
resultsTable.setModel(tableModelFrom(matches));
TableColumnModel colModel = resultsTable.getColumnModel();
TableColumn column;
int width;
for (int i = 0; i < matchColumns.length; i++) {
if (matchColumns[i].width() > 0) {
column = colModel.getColumn(i);
width = matchColumns[i].width();
column.setPreferredWidth(width);
column.setMinWidth(width);
column.setMaxWidth(width);
}
}
}
// CPDListener
@Override
public void phaseUpdate(int phase) {
phaseLabel.setText(getPhaseText(phase));
}
public String getPhaseText(int phase) {
switch (phase) {
case CPDListener.INIT:
return "Initializing";
case CPDListener.HASH:
return "Hashing";
case CPDListener.MATCH:
return "Matching";
case CPDListener.GROUPING:
return "Grouping";
case CPDListener.DONE:
return "Done";
default:
return "Unknown";
}
}
@Override
public void addedFile(int fileCount, File file) {
tokenizingFilesBar.setMaximum(fileCount);
tokenizingFilesBar.setValue(tokenizingFilesBar.getValue() + 1);
}
// CPDListener
public static void main(String[] args) {
// this should prevent the disk not found popup
// System.setSecurityManager(null);
new GUI();
}
}
| 33,337 | 34.203801 | 120 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CPD.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.internal.util.FileFinder;
import net.sourceforge.pmd.internal.util.FileUtil;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.ast.TokenMgrError;
import net.sourceforge.pmd.util.database.DBMSMetadata;
import net.sourceforge.pmd.util.database.DBURI;
import net.sourceforge.pmd.util.database.SourceObject;
/**
* @deprecated Use the module pmd-cli for CLI support.
*/
@Deprecated
public class CPD {
// not final, in order to re-initialize logging
private static Logger log = LoggerFactory.getLogger(CPD.class);
private CPDConfiguration configuration;
private Map<String, SourceCode> source = new TreeMap<>();
private CPDListener listener = new CPDNullListener();
private Tokens tokens = new Tokens();
private MatchAlgorithm matchAlgorithm;
private Set<String> current = new HashSet<>();
private final Map<String, Integer> numberOfTokensPerFile = new HashMap<>();
private int lastTokenSize = 0;
public CPD(CPDConfiguration theConfiguration) {
configuration = theConfiguration;
// before we start any tokenizing (add(File...)), we need to reset the
// static TokenEntry status
TokenEntry.clearImages();
// Add all sources
extractAllSources();
}
private void extractAllSources() {
// Add files
if (null != configuration.getFiles() && !configuration.getFiles().isEmpty()) {
addSourcesFilesToCPD(configuration.getFiles());
}
// Add Database URIS
if (null != configuration.getURI() && !"".equals(configuration.getURI())) {
addSourceURIToCPD(configuration.getURI());
}
if (null != configuration.getFileListPath() && !"".equals(configuration.getFileListPath())) {
addFilesFromFilelist(configuration.getFileListPath());
}
}
private void addSourcesFilesToCPD(List<File> files) {
try {
for (File file : files) {
if (!file.exists()) {
throw new FileNotFoundException("Could not find directory/file '" + file + "'");
} else if (file.isDirectory()) {
if (configuration.isNonRecursive()) {
addAllInDirectory(file);
} else {
addRecursively(file);
}
} else {
add(file);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private void addFilesFromFilelist(String inputFilePath) {
List<File> files = new ArrayList<>();
try {
Path file = FileUtil.toExistingPath(inputFilePath);
for (Path fileToAdd : FileUtil.readFilelistEntries(file)) {
if (!Files.exists(fileToAdd)) {
throw new RuntimeException("No such file " + fileToAdd);
}
files.add(fileToAdd.toFile());
}
addSourcesFilesToCPD(files);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
private void addSourceURIToCPD(String uri) {
try {
log.debug("Attempting DBURI={}", uri);
DBURI dburi = new DBURI(uri);
log.debug("Initialised DBURI={}", dburi);
log.debug("Adding DBURI={} with DBType={}", dburi, dburi.getDbType());
add(dburi);
} catch (IOException | URISyntaxException e) {
throw new IllegalStateException("uri=" + uri, e);
}
}
public void setCpdListener(CPDListener cpdListener) {
this.listener = cpdListener;
}
public void go() {
log.debug("Running match algorithm on {} files...", source.size());
matchAlgorithm = new MatchAlgorithm(source, tokens, configuration.getMinimumTileSize(), listener);
matchAlgorithm.findMatches();
log.debug("Finished: {} duplicates found", matchAlgorithm.getMatches().size());
}
/**
* @deprecated Use {@link #toReport()}.
*/
@Deprecated
public Iterator<Match> getMatches() {
return matchAlgorithm.matches();
}
public void addAllInDirectory(File dir) throws IOException {
addDirectory(dir, false);
}
public void addRecursively(File dir) throws IOException {
addDirectory(dir, true);
}
public void add(List<File> files) throws IOException {
for (File f : files) {
add(f);
}
}
private void addDirectory(File dir, boolean recurse) throws IOException {
if (!dir.exists()) {
throw new FileNotFoundException("Couldn't find directory " + dir);
}
log.debug("Searching directory " + dir + " for files");
FileFinder finder = new FileFinder();
// TODO - could use SourceFileSelector here
add(finder.findFilesFrom(dir, configuration.filenameFilter(), recurse));
}
public void add(File file) throws IOException {
if (configuration.isSkipDuplicates()) {
// TODO refactor this thing into a separate class
String signature = file.getName() + '_' + file.length();
if (current.contains(signature)) {
System.err.println("Skipping " + file.getAbsolutePath()
+ " since it appears to be a duplicate file and --skip-duplicate-files is set");
return;
}
current.add(signature);
}
if (!IOUtil.equalsNormalizedPaths(file.getAbsoluteFile().getCanonicalPath(), file.getAbsolutePath())) {
System.err.println("Skipping " + file + " since it appears to be a symlink");
return;
}
if (!file.exists()) {
System.err.println("Skipping " + file + " since it doesn't exist (broken symlink?)");
return;
}
SourceCode sourceCode = configuration.sourceCodeFor(file);
add(sourceCode);
}
public void add(DBURI dburi) {
try {
DBMSMetadata dbmsmetadata = new DBMSMetadata(dburi);
List<SourceObject> sourceObjectList = dbmsmetadata.getSourceObjectList();
log.debug("Located {} database source objects", sourceObjectList.size());
for (SourceObject sourceObject : sourceObjectList) {
// Add DBURI as a faux-file
String falseFilePath = sourceObject.getPseudoFileName();
log.trace("Adding database source object {}", falseFilePath);
SourceCode sourceCode = configuration.sourceCodeFor(dbmsmetadata.getSourceCode(sourceObject),
falseFilePath);
add(sourceCode);
}
} catch (Exception sqlException) {
log.error("Problem with Input URI", sqlException);
throw new RuntimeException("Problem with DBURI: " + dburi, sqlException);
}
}
@Experimental
public void add(SourceCode sourceCode) throws IOException {
if (configuration.isSkipLexicalErrors()) {
addAndSkipLexicalErrors(sourceCode);
} else {
addAndThrowLexicalError(sourceCode);
}
}
private void addAndThrowLexicalError(SourceCode sourceCode) throws IOException {
log.debug("Tokenizing {}", sourceCode.getFileName());
configuration.tokenizer().tokenize(sourceCode, tokens);
listener.addedFile(1, new File(sourceCode.getFileName()));
source.put(sourceCode.getFileName(), sourceCode);
numberOfTokensPerFile.put(sourceCode.getFileName(), tokens.size() - lastTokenSize - 1 /*EOF*/);
lastTokenSize = tokens.size();
}
private void addAndSkipLexicalErrors(SourceCode sourceCode) throws IOException {
final TokenEntry.State savedState = new TokenEntry.State();
try {
addAndThrowLexicalError(sourceCode);
} catch (TokenMgrError e) {
System.err.println("Skipping " + sourceCode.getFileName() + ". Reason: " + e.getMessage());
savedState.restore(tokens);
}
}
/**
* List names/paths of each source to be processed.
*
* @return names of sources to be processed
*/
public List<String> getSourcePaths() {
return new ArrayList<>(source.keySet());
}
/**
* Get each Source to be processed.
*
* @return all Sources to be processed
*/
public List<SourceCode> getSources() {
return new ArrayList<>(source.values());
}
/**
* Entry to invoke CPD as command line tool. Note that this will
* invoke {@link System#exit(int)}.
*
* @param args command line arguments
*
* @deprecated Use module pmd-cli -- to be removed before 7.0.0 is out.
*/
@Deprecated
public static void main(String[] args) {
throw new UnsupportedOperationException("Use the pmd-cli module.");
}
public CPDReport toReport() {
return new CPDReport(matchAlgorithm.getMatches(), numberOfTokensPerFile);
}
}
| 9,738 | 33.413428 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/CPDListener.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.File;
public interface CPDListener {
int INIT = 0;
int HASH = 1;
int MATCH = 2;
int GROUPING = 3;
int DONE = 4;
void addedFile(int fileCount, File file);
void phaseUpdate(int phase);
}
| 355 | 15.952381 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.document.FileLocation;
public class TokenEntry implements Comparable<TokenEntry> {
public static final TokenEntry EOF = new TokenEntry();
private String tokenSrcID;
private final int beginLine;
private final int beginColumn;
private final int endColumn;
private int index;
private int identifier;
private int hashCode;
private static final ThreadLocal<Map<String, Integer>> TOKENS = new ThreadLocal<Map<String, Integer>>() {
@Override
protected Map<String, Integer> initialValue() {
return new HashMap<>();
}
};
private static final ThreadLocal<AtomicInteger> TOKEN_COUNT = new ThreadLocal<AtomicInteger>() {
@Override
protected AtomicInteger initialValue() {
return new AtomicInteger(0);
}
};
private TokenEntry() {
this.identifier = 0;
this.tokenSrcID = "EOFMarker";
this.beginLine = -1;
this.beginColumn = -1;
this.endColumn = -1;
}
/**
* Creates a new token entry with the given informations.
* @param image
* @param tokenSrcID
* @param beginLine the linenumber, 1-based.
*
* @deprecated Use {@link #TokenEntry(String, String, int, int, int)}, don't be lazy
*/
@Deprecated
public TokenEntry(String image, String tokenSrcID, int beginLine) {
this(image, tokenSrcID, beginLine, -1, -1);
}
/**
* Creates a new token entry with the given informations.
* @param image
* @param tokenSrcID
* @param beginLine the linenumber, 1-based.
* @param beginColumn the column number, 1-based
* @param endColumn the column number, 1-based
*/
public TokenEntry(String image, String tokenSrcID, int beginLine, int beginColumn, int endColumn) {
assert isOk(beginLine) && isOk(beginColumn) && isOk(endColumn) : "Coordinates are 1-based";
setImage(image);
this.tokenSrcID = tokenSrcID;
this.beginLine = beginLine;
this.beginColumn = beginColumn;
this.endColumn = endColumn;
this.index = TOKEN_COUNT.get().getAndIncrement();
}
public TokenEntry(String image, FileLocation location) {
this(image, location.getFileId().getOriginalPath(), location.getStartLine(), location.getStartColumn(), location.getEndColumn());
}
private boolean isOk(int coord) {
return coord >= 1 || coord == -1;
}
public static TokenEntry getEOF() {
TOKEN_COUNT.get().getAndIncrement();
return EOF;
}
public static void clearImages() {
TOKENS.get().clear();
TOKENS.remove();
TOKEN_COUNT.remove();
}
/**
* Helper class to preserve and restore the current state of the token
* entries.
*
* @deprecated This is internal API.
*/
@InternalApi
@Deprecated
public static class State {
private final int tokenCount;
private final int tokensMapSize;
public State() {
this.tokenCount = TokenEntry.TOKEN_COUNT.get().intValue();
this.tokensMapSize = TokenEntry.TOKENS.get().size();
}
public void restore(Tokens tokens) {
final List<TokenEntry> entries = tokens.getTokens();
TokenEntry.TOKEN_COUNT.get().set(tokenCount);
final Iterator<Map.Entry<String, Integer>> it = TOKENS.get().entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue() > tokensMapSize) {
it.remove();
}
}
entries.subList(tokenCount, entries.size()).clear();
}
}
public String getTokenSrcID() {
return tokenSrcID;
}
public int getBeginLine() {
return beginLine;
}
/**
* The column number where this token begins.
* returns -1 if not available
* @return the begin column number
*/
public int getBeginColumn() {
return beginColumn; // TODO Java 1.8 make optional
}
/**
* The column number where this token ends.
* returns -1 if not available
* @return the end column number
*/
public int getEndColumn() {
return endColumn; // TODO Java 1.8 make optional
}
public int getIdentifier() {
return this.identifier;
}
public int getIndex() {
return this.index;
}
@Override
public int hashCode() {
return hashCode;
}
public void setHashCode(int hashCode) {
this.hashCode = hashCode;
}
@SuppressWarnings("PMD.CompareObjectsWithEquals")
@Override
public boolean equals(Object o) {
// make sure to recognize EOF regardless of hashCode (hashCode is irrelevant for EOF)
if (this == EOF) {
return o == EOF;
}
if (o == EOF) {
return this == EOF;
}
// any token except EOF
if (!(o instanceof TokenEntry)) {
return false;
}
TokenEntry other = (TokenEntry) o;
return other.hashCode == hashCode;
}
@Override
public int compareTo(TokenEntry other) {
return getIndex() - other.getIndex();
}
@Override
public String toString() {
if (EOF.equals(this)) {
return "EOF";
}
for (Map.Entry<String, Integer> e : TOKENS.get().entrySet()) {
if (e.getValue().intValue() == identifier) {
return e.getKey();
}
}
return "--unknown--";
}
final void setImage(String image) {
Integer i = TOKENS.get().get(image);
if (i == null) {
i = TOKENS.get().size() + 1;
TOKENS.get().put(image, i);
}
this.identifier = i.intValue();
}
}
| 6,148 | 27.336406 | 137 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/ReportException.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* @author Philippe T'Seyen
*/
public class ReportException extends Exception {
private static final long serialVersionUID = 6043174086675858209L;
public ReportException(Throwable cause) {
super(cause);
}
}
| 356 | 20 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/token/AntlrTokenFilter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.token;
import net.sourceforge.pmd.cpd.token.internal.BaseTokenFilter;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrToken;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrTokenManager;
/**
* A generic filter for Antlr-based token managers that allows to use comments
* to enable / disable analysis of parts of the stream
*/
public class AntlrTokenFilter extends BaseTokenFilter<AntlrToken> {
/**
* Creates a new AntlrTokenFilter
* @param tokenManager The token manager from which to retrieve tokens to be filtered
*/
public AntlrTokenFilter(final AntlrTokenManager tokenManager) {
super(tokenManager);
}
}
| 781 | 29.076923 | 89 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/token/TokenFilter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.token;
import net.sourceforge.pmd.lang.ast.GenericToken;
/**
* Defines filter to be applied to the token stream during CPD analysis
*/
public interface TokenFilter<T extends GenericToken<T>> {
/**
* Retrieves the next token to pass the filter
* @return The next token to pass the filter, or null if the end of the stream was reached
*/
T getNextToken();
}
| 505 | 24.3 | 94 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/token/JavaCCTokenFilter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.token;
import net.sourceforge.pmd.cpd.token.internal.BaseTokenFilter;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
/**
* A generic filter for JavaCC-based token managers that allows to use comments
* to enable / disable analysis of parts of the stream
*/
public class JavaCCTokenFilter extends BaseTokenFilter<JavaccToken> {
/**
* Creates a new JavaCCTokenFilter
* @param tokenManager The token manager from which to retrieve tokens to be filtered
*/
public JavaCCTokenFilter(final TokenManager<JavaccToken> tokenManager) {
super(tokenManager);
}
}
| 774 | 28.807692 | 89 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilter.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.token.internal;
import static net.sourceforge.pmd.util.IteratorUtil.AbstractIterator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedList;
import net.sourceforge.pmd.cpd.token.TokenFilter;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.GenericToken;
/**
* A generic filter for PMD token managers that allows to use comments
* to enable / disable analysis of parts of the stream
*/
public abstract class BaseTokenFilter<T extends GenericToken<T>> implements TokenFilter<T> {
private final TokenManager<T> tokenManager;
private final LinkedList<T> unprocessedTokens; // NOPMD - used both as Queue and List
private final Iterable<T> remainingTokens;
private boolean discardingSuppressing;
private T currentToken;
/**
* Creates a new BaseTokenFilter
* @param tokenManager The token manager from which to retrieve tokens to be filtered
*/
public BaseTokenFilter(final TokenManager<T> tokenManager) {
this.tokenManager = tokenManager;
this.unprocessedTokens = new LinkedList<>();
this.remainingTokens = new RemainingTokens();
}
@Override
public final T getNextToken() {
currentToken = null;
if (!unprocessedTokens.isEmpty()) {
currentToken = unprocessedTokens.poll();
} else {
currentToken = tokenManager.getNextToken();
}
while (!shouldStopProcessing(currentToken)) {
analyzeToken(currentToken);
analyzeTokens(currentToken, remainingTokens);
processCPDSuppression(currentToken);
if (!isDiscarding()) {
return currentToken;
}
if (!unprocessedTokens.isEmpty()) {
currentToken = unprocessedTokens.poll();
} else {
currentToken = tokenManager.getNextToken();
}
}
return null;
}
private boolean isDiscarding() {
return discardingSuppressing || isLanguageSpecificDiscarding();
}
private void processCPDSuppression(final T currentToken) {
// Check if a comment is altering the suppression state
T comment = currentToken.getPreviousComment();
while (comment != null) {
if (comment.getImage().contains("CPD-OFF")) {
discardingSuppressing = true;
break;
}
if (comment.getImage().contains("CPD-ON")) {
discardingSuppressing = false;
break;
}
comment = comment.getPreviousComment();
}
}
/**
* Extension point for subclasses to analyze all tokens (before filtering)
* and update internal status to decide on custom discard rules.
*
* @param currentToken The token to be analyzed
* @see #isLanguageSpecificDiscarding()
*/
protected void analyzeToken(final T currentToken) {
// noop
}
/**
* Extension point for subclasses to analyze all tokens (before filtering)
* and update internal status to decide on custom discard rules.
*
* @param currentToken The token to be analyzed
* @param remainingTokens All upcoming tokens
* @see #isLanguageSpecificDiscarding()
*/
protected void analyzeTokens(final T currentToken, final Iterable<T> remainingTokens) {
// noop
}
/**
* Extension point for subclasses to indicate tokens are to be filtered.
*
* @return True if tokens should be filtered, false otherwise
*/
protected boolean isLanguageSpecificDiscarding() {
return false;
}
/**
* Extension point for subclasses to indicate when to stop filtering tokens.
*
* @param currentToken The token to be analyzed
*
* @return True if the token filter has finished consuming all tokens, false otherwise
*/
protected boolean shouldStopProcessing(T currentToken) {
return currentToken.isEof();
}
private final class RemainingTokens implements Iterable<T> {
@Override
public Iterator<T> iterator() {
return new RemainingTokensIterator(currentToken);
}
private class RemainingTokensIterator extends AbstractIterator<T> implements Iterator<T> {
int index = 0; // index of next element
T startToken;
RemainingTokensIterator(final T startToken) {
this.startToken = startToken;
}
@Override
protected void computeNext() {
assert index >= 0;
if (startToken != currentToken) { // NOPMD - intentional check for reference equality
throw new ConcurrentModificationException("Using iterator after next token has been requested.");
}
if (index < unprocessedTokens.size()) {
setNext(unprocessedTokens.get(index++));
} else {
final T nextToken = tokenManager.getNextToken();
if (shouldStopProcessing(nextToken)) {
done();
return;
}
index++;
unprocessedTokens.add(nextToken);
setNext(nextToken);
}
}
}
}
}
| 5,533 | 31.745562 | 117 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/renderer/CPDReportRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.renderer;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import net.sourceforge.pmd.cpd.CPDReport;
public interface CPDReportRenderer {
void render(CPDReport report, Writer writer) throws IOException;
/**
* Call the other render method on a StringWriter. IO exceptions
* are rethrown as runtime exceptions.
*/
default String renderToString(CPDReport report) {
StringWriter sw = new StringWriter();
try {
this.render(report, sw);
} catch (IOException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}
| 769 | 23.0625 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/impl/AntlrTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.impl;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.TokenEntry;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.Tokens;
import net.sourceforge.pmd.cpd.token.AntlrTokenFilter;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrToken;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrTokenManager;
import net.sourceforge.pmd.lang.document.CpdCompat;
import net.sourceforge.pmd.lang.document.TextDocument;
/**
* Generic implementation of a {@link Tokenizer} useful to any Antlr grammar.
*/
public abstract class AntlrTokenizer implements Tokenizer {
protected abstract Lexer getLexerForSource(CharStream charStream);
@Override
public void tokenize(final SourceCode sourceCode, final Tokens tokenEntries) {
try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) {
CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getFileId().getOriginalPath());
final AntlrTokenManager tokenManager = new AntlrTokenManager(getLexerForSource(charStream), textDoc);
final AntlrTokenFilter tokenFilter = getTokenFilter(tokenManager);
AntlrToken currentToken = tokenFilter.getNextToken();
while (currentToken != null) {
processToken(tokenEntries, currentToken);
currentToken = tokenFilter.getNextToken();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
tokenEntries.add(TokenEntry.getEOF());
}
}
protected AntlrTokenFilter getTokenFilter(final AntlrTokenManager tokenManager) {
return new AntlrTokenFilter(tokenManager);
}
private void processToken(final Tokens tokenEntries, final AntlrToken token) {
final TokenEntry tokenEntry = new TokenEntry(token.getImage(), token.getReportLocation());
tokenEntries.add(tokenEntry);
}
}
| 2,282 | 35.822581 | 128 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/cpd/impl/JavaCCTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd.impl;
import java.io.IOException;
import net.sourceforge.pmd.cpd.SourceCode;
import net.sourceforge.pmd.cpd.TokenEntry;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.Tokens;
import net.sourceforge.pmd.cpd.token.JavaCCTokenFilter;
import net.sourceforge.pmd.cpd.token.TokenFilter;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.FileAnalysisException;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.document.CpdCompat;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextFile;
public abstract class JavaCCTokenizer implements Tokenizer {
@SuppressWarnings("PMD.CloseResource")
protected TokenManager<JavaccToken> getLexerForSource(TextDocument sourceCode) throws IOException {
return makeLexerImpl(CharStream.create(sourceCode, tokenBehavior()));
}
protected TokenDocumentBehavior tokenBehavior() {
return TokenDocumentBehavior.DEFAULT;
}
protected abstract TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode);
protected TokenFilter<JavaccToken> getTokenFilter(TokenManager<JavaccToken> tokenManager) {
return new JavaCCTokenFilter(tokenManager);
}
protected TokenEntry processToken(Tokens tokenEntries, JavaccToken currentToken) {
return new TokenEntry(getImage(currentToken), currentToken.getReportLocation());
}
protected String getImage(JavaccToken token) {
return token.getImage();
}
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) throws IOException {
TextFile textFile = CpdCompat.cpdCompat(sourceCode);
try (TextDocument textDoc = TextDocument.create(textFile)) {
TokenManager<JavaccToken> tokenManager = getLexerForSource(textDoc);
final TokenFilter<JavaccToken> tokenFilter = getTokenFilter(tokenManager);
JavaccToken currentToken = tokenFilter.getNextToken();
while (currentToken != null) {
tokenEntries.add(processToken(tokenEntries, currentToken));
currentToken = tokenFilter.getNextToken();
}
} catch (FileAnalysisException e) {
throw e.setFileId(textFile.getFileId());
} finally {
tokenEntries.add(TokenEntry.getEOF());
}
}
}
| 2,671 | 38.880597 | 103 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleFactory.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.rules;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.MAXIMUM_LANGUAGE_VERSION;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.MINIMUM_LANGUAGE_VERSION;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.NAME;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.PROPERTY_TYPE;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.PROPERTY_VALUE;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.ERR__INVALID_LANG_VERSION;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.ERR__INVALID_LANG_VERSION_NO_NAMED_VERSION;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.ERR__PROPERTY_DOES_NOT_EXIST;
import static net.sourceforge.pmd.util.internal.xml.XmlErrorMessages.IGNORED__DUPLICATE_PROPERTY_SETTER;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.RuleSetReference;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyDescriptorField;
import net.sourceforge.pmd.properties.PropertyTypeId;
import net.sourceforge.pmd.properties.ValueParser;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorExternalBuilder;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.StringUtil;
import net.sourceforge.pmd.util.internal.xml.PmdXmlReporter;
import net.sourceforge.pmd.util.internal.xml.SchemaConstant;
import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
import net.sourceforge.pmd.util.internal.xml.XmlErrorMessages;
import net.sourceforge.pmd.util.internal.xml.XmlUtil;
import com.github.oowekyala.ooxml.DomUtils;
import com.github.oowekyala.ooxml.messages.XmlException;
/**
* Builds rules from rule XML nodes.
*
* @author Clément Fournier
* @since 6.0.0
*/
@InternalApi
@Deprecated
public class RuleFactory {
private final ResourceLoader resourceLoader;
private final LanguageRegistry languageRegistry;
/**
* @param resourceLoader The resource loader to load the rule from jar
*/
public RuleFactory(ResourceLoader resourceLoader,
LanguageRegistry languageRegistry) {
this.resourceLoader = resourceLoader;
this.languageRegistry = languageRegistry;
}
/**
* Decorates a referenced rule with the metadata that are overridden in the given rule element.
*
* <p>Declaring a property in the overriding element throws an exception (the property must exist in the referenced
* rule).
*
* @param referencedRule Referenced rule
* @param ruleSetReference the ruleset, where the referenced rule is defined
* @param ruleElement Element overriding some metadata about the rule
* @param err Error reporter
*
* @return A rule reference to the referenced rule
*/
public RuleReference decorateRule(Rule referencedRule, RuleSetReference ruleSetReference, Element ruleElement, PmdXmlReporter err) {
RuleReference ruleReference = new RuleReference(referencedRule, ruleSetReference);
SchemaConstants.DEPRECATED.getAttributeOpt(ruleElement).map(Boolean::parseBoolean).ifPresent(ruleReference::setDeprecated);
SchemaConstants.NAME.getAttributeOpt(ruleElement).ifPresent(ruleReference::setName);
SchemaConstants.MESSAGE.getAttributeOpt(ruleElement).ifPresent(ruleReference::setMessage);
SchemaConstants.EXTERNAL_INFO_URL.getAttributeOpt(ruleElement).ifPresent(ruleReference::setExternalInfoUrl);
for (Element node : DomUtils.children(ruleElement)) {
if (SchemaConstants.DESCRIPTION.matchesElt(node)) {
ruleReference.setDescription(XmlUtil.parseTextNode(node));
} else if (SchemaConstants.EXAMPLE.matchesElt(node)) {
ruleReference.addExample(XmlUtil.parseTextNode(node));
} else if (SchemaConstants.PRIORITY.matchesElt(node)) {
RulePriority priority = parsePriority(err, node);
if (priority == null) {
priority = RulePriority.MEDIUM;
}
ruleReference.setPriority(priority);
} else if (SchemaConstants.PROPERTIES.matchesElt(node)) {
setPropertyValues(ruleReference, node, err);
} else {
err.at(node).error(
XmlErrorMessages.ERR__UNEXPECTED_ELEMENT_IN,
node.getTagName(),
"rule " + ruleReference.getName()
);
}
}
return ruleReference;
}
/**
* Parses a rule element and returns a new rule instance.
*
* <p>Notes: The ruleset name is not set here. Exceptions raised from this method indicate invalid XML structure,
* with regards to the expected schema, while RuleBuilder validates the semantics.
*
* @param ruleElement The rule element to parse
*
* @return A new instance of the rule described by this element
*
* @throws IllegalArgumentException if the element doesn't describe a valid rule.
*/
public Rule buildRule(Element ruleElement, PmdXmlReporter err) {
Rule rule;
try {
String clazz = SchemaConstants.CLASS.getNonBlankAttribute(ruleElement, err);
rule = resourceLoader.loadRuleFromClassPath(clazz);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
Attr node = SchemaConstants.CLASS.getAttributeNode(ruleElement);
throw err.at(node).error(e);
}
rule.setName(NAME.getNonBlankAttribute(ruleElement, err));
if (rule.getLanguage() == null) {
setLanguage(ruleElement, err, rule);
}
Language language = rule.getLanguage();
assert language != null;
rule.setMinimumLanguageVersion(getLanguageVersion(ruleElement, err, language, MINIMUM_LANGUAGE_VERSION));
rule.setMaximumLanguageVersion(getLanguageVersion(ruleElement, err, language, MAXIMUM_LANGUAGE_VERSION));
checkVersionsAreOrdered(ruleElement, err, rule);
SchemaConstants.SINCE.getAttributeOpt(ruleElement).ifPresent(rule::setSince);
SchemaConstants.MESSAGE.getAttributeOpt(ruleElement).ifPresent(rule::setMessage);
SchemaConstants.EXTERNAL_INFO_URL.getAttributeOpt(ruleElement).ifPresent(rule::setExternalInfoUrl);
rule.setDeprecated(SchemaConstants.DEPRECATED.getAsBooleanAttr(ruleElement, false));
for (Element node : DomUtils.children(ruleElement)) {
if (SchemaConstants.DESCRIPTION.matchesElt(node)) {
rule.setDescription(XmlUtil.parseTextNode(node));
} else if (SchemaConstants.EXAMPLE.matchesElt(node)) {
rule.addExample(XmlUtil.parseTextNode(node));
} else if (SchemaConstants.PRIORITY.matchesElt(node)) {
RulePriority rp = parsePriority(err, node);
if (rp == null) {
rp = RulePriority.MEDIUM;
}
rule.setPriority(rp);
} else if (SchemaConstants.PROPERTIES.matchesElt(node)) {
parsePropertiesForDefinitions(rule, node, err);
setPropertyValues(rule, node, err);
} else {
throw err.at(node).error(
XmlErrorMessages.ERR__UNEXPECTED_ELEMENT_IN,
"rule " + NAME.getAttributeOrNull(ruleElement));
}
}
return rule;
}
private void checkVersionsAreOrdered(Element ruleElement, PmdXmlReporter err, Rule rule) {
if (rule.getMinimumLanguageVersion() != null && rule.getMaximumLanguageVersion() != null
&& rule.getMinimumLanguageVersion().compareTo(rule.getMaximumLanguageVersion()) > 0) {
throw err.at(MINIMUM_LANGUAGE_VERSION.getAttributeNode(ruleElement))
.error(
XmlErrorMessages.ERR__INVALID_VERSION_RANGE,
rule.getMinimumLanguageVersion(),
rule.getMaximumLanguageVersion()
);
}
}
/**
* Parse a priority. If invalid, report it and return null.
*/
public static @Nullable RulePriority parsePriority(PmdXmlReporter err, Element node) {
String text = XmlUtil.parseTextNode(node);
RulePriority rp = RulePriority.valueOfNullable(text);
if (rp == null) {
err.at(node).error(XmlErrorMessages.ERR__INVALID_PRIORITY_VALUE, text);
return null;
}
return rp;
}
private LanguageVersion getLanguageVersion(Element ruleElement, PmdXmlReporter err, Language language, SchemaConstant attrName) {
if (attrName.hasAttribute(ruleElement)) {
String attrValue = attrName.getAttributeOrThrow(ruleElement, err);
LanguageVersion version = language.getVersion(attrValue);
if (version == null) {
String supportedVersions = language.getVersions().stream()
.map(LanguageVersion::getVersion)
.filter(it -> !it.isEmpty())
.map(StringUtil::inSingleQuotes)
.collect(Collectors.joining(", "));
String message = supportedVersions.isEmpty()
? ERR__INVALID_LANG_VERSION_NO_NAMED_VERSION
: ERR__INVALID_LANG_VERSION;
throw err.at(attrName.getAttributeNode(ruleElement))
.error(
message,
attrValue,
language.getTerseName(),
supportedVersions
);
}
return version;
}
return null;
}
private void setLanguage(Element ruleElement, PmdXmlReporter err, Rule rule) {
String langId = SchemaConstants.LANGUAGE.getNonBlankAttribute(ruleElement, err);
Language lang = languageRegistry.getLanguageById(langId);
if (lang == null) {
Attr node = SchemaConstants.LANGUAGE.getAttributeNode(ruleElement);
throw err.at(node)
.error("Invalid language ''{0}'', possible values are {1}", langId, supportedLanguages());
}
rule.setLanguage(lang);
}
private @NonNull String supportedLanguages() {
return languageRegistry.commaSeparatedList(l -> StringUtil.inSingleQuotes(l.getId()));
}
/**
* Parses the properties node and adds property definitions to the builder. Doesn't care for value overriding, that
* will be handled after the rule instantiation.
*
* @param rule Rule builder
* @param propertiesNode Node to parse
* @param err Error reporter
*/
private void parsePropertiesForDefinitions(Rule rule, Element propertiesNode, @NonNull PmdXmlReporter err) {
for (Element child : SchemaConstants.PROPERTY_ELT.getElementChildrenNamedReportOthers(propertiesNode, err)) {
if (isPropertyDefinition(child)) {
rule.definePropertyDescriptor(parsePropertyDefinition(child, err));
}
}
}
/**
* Overrides the rule's properties with the values defined in the element.
*
* @param rule The rule
* @param propertiesElt The {@literal <properties>} element
*/
private void setPropertyValues(Rule rule, Element propertiesElt, PmdXmlReporter err) {
Set<String> overridden = new HashSet<>();
XmlException exception = null;
for (Element element : SchemaConstants.PROPERTY_ELT.getElementChildrenNamedReportOthers(propertiesElt, err)) {
String name = SchemaConstants.NAME.getAttributeOrThrow(element, err);
if (!overridden.add(name)) {
err.at(element).warn(IGNORED__DUPLICATE_PROPERTY_SETTER, name);
continue;
}
PropertyDescriptor<?> desc = rule.getPropertyDescriptor(name);
if (desc == null) {
// todo just warn and ignore
throw err.at(element).error(ERR__PROPERTY_DOES_NOT_EXIST, name, rule.getName());
}
try {
setRulePropertyCapture(rule, desc, element, err);
} catch (XmlException e) {
if (exception == null) {
exception = e;
} else {
exception.addSuppressed(e);
}
}
}
if (exception != null) {
throw exception;
}
}
private <T> void setRulePropertyCapture(Rule rule, PropertyDescriptor<T> descriptor, Element propertyElt, PmdXmlReporter err) {
T value = parsePropertyValue(propertyElt, err, descriptor::valueFrom);
rule.setProperty(descriptor, value);
}
/**
* Finds out if the property element defines a property.
*
* @param node Property element
*
* @return True if this element defines a new property, false if this is just stating a value
*/
private static boolean isPropertyDefinition(Element node) {
return SchemaConstants.PROPERTY_TYPE.hasAttribute(node);
}
/**
* Parses a property definition node and returns the defined property descriptor.
*
* @param propertyElement Property node to parse
* @param err Error reporter
*
* @return The property descriptor
*/
private static PropertyDescriptor<?> parsePropertyDefinition(Element propertyElement, PmdXmlReporter err) {
String typeId = SchemaConstants.PROPERTY_TYPE.getAttributeOrThrow(propertyElement, err);
PropertyDescriptorExternalBuilder<?> pdFactory = PropertyTypeId.factoryFor(typeId);
if (pdFactory == null) {
throw err.at(PROPERTY_TYPE.getAttributeNode(propertyElement))
.error(
XmlErrorMessages.ERR__UNSUPPORTED_PROPERTY_TYPE,
typeId
);
}
return propertyDefCapture(propertyElement, err, pdFactory);
}
private static <T> PropertyDescriptor<T> propertyDefCapture(Element propertyElement,
PmdXmlReporter err,
PropertyDescriptorExternalBuilder<T> factory) {
// TODO support constraints like numeric range
String name = SchemaConstants.NAME.getNonBlankAttributeOrThrow(propertyElement, err);
String description = SchemaConstants.DESCRIPTION.getNonBlankAttributeOrThrow(propertyElement, err);
Map<PropertyDescriptorField, String> values = new HashMap<>();
values.put(PropertyDescriptorField.NAME, name);
values.put(PropertyDescriptorField.DESCRIPTION, description);
String defaultValue = parsePropertyValue(propertyElement, err, s -> s);
values.put(PropertyDescriptorField.DEFAULT_VALUE, defaultValue);
// populate remaining fields
for (Node attrNode : DomUtils.asList(propertyElement.getAttributes())) {
Attr attr = (Attr) attrNode;
PropertyDescriptorField field = PropertyDescriptorField.getConstant(attr.getName());
if (field == PropertyDescriptorField.NAME
|| field == PropertyDescriptorField.DEFAULT_VALUE
|| field == PropertyDescriptorField.DESCRIPTION) {
continue;
}
if (field == null) {
err.at(attr).warn(XmlErrorMessages.IGNORED__UNEXPECTED_ATTRIBUTE_IN, propertyElement.getLocalName());
continue;
}
values.put(field, attr.getValue());
}
try {
return factory.build(values);
} catch (IllegalArgumentException e) {
// builder threw, rethrow with XML location
throw err.at(propertyElement).error(e);
}
}
private static <T> T parsePropertyValue(Element propertyElt, PmdXmlReporter err, ValueParser<T> parser) {
@Nullable String defaultAttr = PROPERTY_VALUE.getAttributeOrNull(propertyElt);
if (defaultAttr != null) {
Attr attrNode = PROPERTY_VALUE.getAttributeNode(propertyElt);
try {
return parser.valueOf(defaultAttr);
} catch (IllegalArgumentException e) {
throw err.at(attrNode).error(e);
}
} else {
Element child = PROPERTY_VALUE.getSingleChildIn(propertyElt, err);
String text = XmlUtil.parseTextNode(child);
try {
return parser.valueOf(text);
} catch (IllegalArgumentException e) {
throw err.at(child).error(e);
}
}
}
}
| 17,774 | 41.120853 | 136 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TextTimingReportRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.MessageFormat;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.benchmark.TimeTracker.TimedResult;
/**
* A text based renderer for {@link TimingReport}.
* @author Juan Martín Sotuyo Dodero
*/
public class TextTimingReportRenderer implements TimingReportRenderer {
private static final String TIME_FORMAT = "{0,number,0.0000}";
private static final String CUSTOM_COUNTER_FORMAT = "{0,number,###,###,###}";
private static final int LABEL_COLUMN_WIDTH = 50;
private static final int TIME_COLUMN_WIDTH = 12;
private static final int SELF_TIME_COLUMN_WIDTH = 17;
private static final int CALL_COLUMN_WIDTH = 9;
private static final int COUNTER_COLUMN_WIDTH = 12;
private static final int COLUMNS = LABEL_COLUMN_WIDTH + TIME_COLUMN_WIDTH
+ SELF_TIME_COLUMN_WIDTH + CALL_COLUMN_WIDTH + COUNTER_COLUMN_WIDTH;
@Override
public void render(final TimingReport report, final Writer writer0) throws IOException {
PrintWriter writer = new PrintWriter(writer0);
for (final TimedOperationCategory category : TimedOperationCategory.values()) {
final Map<String, TimedResult> labeledMeasurements = report.getLabeledMeasurements(category);
if (!labeledMeasurements.isEmpty()) {
renderCategoryMeasurements(category, labeledMeasurements, writer);
}
}
renderHeader("Summary", writer);
for (final TimedOperationCategory category : TimedOperationCategory.values()) {
final TimedResult timedResult = report.getUnlabeledMeasurements(category);
if (timedResult != null) {
renderMeasurement(category.displayName(), timedResult, writer);
}
}
writer.println();
renderHeader("Total", writer);
writer.write(StringUtils.rightPad("Wall Clock Time", LABEL_COLUMN_WIDTH));
final String wallClockTime = MessageFormat.format(TIME_FORMAT, report.getWallClockMillis() / 1000.0);
writer.write(StringUtils.leftPad(wallClockTime, TIME_COLUMN_WIDTH));
writer.println();
writer.flush();
}
private void renderMeasurement(final String label, final TimedResult timedResult,
final PrintWriter writer) throws IOException {
writer.write(StringUtils.rightPad(label, LABEL_COLUMN_WIDTH));
final String time = MessageFormat.format(TIME_FORMAT, timedResult.totalTimeNanos.get() / 1000000000.0);
writer.write(StringUtils.leftPad(time, TIME_COLUMN_WIDTH));
final String selfTime = MessageFormat.format(TIME_FORMAT, timedResult.selfTimeNanos.get() / 1000000000.0);
writer.write(StringUtils.leftPad(selfTime, SELF_TIME_COLUMN_WIDTH));
if (timedResult.callCount.get() > 0) {
final String callCount = MessageFormat.format(CUSTOM_COUNTER_FORMAT, timedResult.callCount.get());
writer.write(StringUtils.leftPad(callCount, CALL_COLUMN_WIDTH));
if (timedResult.extraDataCounter.get() > 0) {
final String counter = MessageFormat.format(CUSTOM_COUNTER_FORMAT, timedResult.extraDataCounter.get());
writer.write(StringUtils.leftPad(counter, COUNTER_COLUMN_WIDTH));
}
}
writer.println();
}
private void renderCategoryMeasurements(final TimedOperationCategory category,
final Map<String, TimedResult> labeledMeasurements, final PrintWriter writer) throws IOException {
renderHeader(category.displayName(), writer);
final TimedResult grandTotal = new TimedResult();
final Set<Entry<String, TimedResult>> sortedKeySet = new TreeSet<>(Comparator.comparingLong(o -> o.getValue().selfTimeNanos.get()));
sortedKeySet.addAll(labeledMeasurements.entrySet());
for (final Map.Entry<String, TimedResult> entry : sortedKeySet) {
renderMeasurement(entry.getKey(), entry.getValue(), writer);
grandTotal.mergeTimes(entry.getValue());
}
writer.println();
renderMeasurement("Total " + category.displayName(), grandTotal, writer);
writer.println();
}
private void renderHeader(final String displayName, final PrintWriter writer) throws IOException {
final StringBuilder sb = new StringBuilder(COLUMNS)
.append(displayName);
// Make sure we have an even-length string
if (displayName.length() % 2 == 1) {
sb.append(' ');
}
// Surround with <<< and >>>
sb.insert(0, "<<< ").append(" >>>");
// Create the ruler
while (sb.length() < COLUMNS) {
sb.insert(0, '-').append('-');
}
writer.write(sb.toString());
writer.println();
// Write table titles
writer.write(StringUtils.rightPad("Label", LABEL_COLUMN_WIDTH));
writer.write(StringUtils.leftPad("Time (secs)", TIME_COLUMN_WIDTH));
writer.write(StringUtils.leftPad("Self Time (secs)", SELF_TIME_COLUMN_WIDTH));
writer.write(StringUtils.leftPad("# Calls", CALL_COLUMN_WIDTH));
writer.write(StringUtils.leftPad("Counter", COUNTER_COLUMN_WIDTH));
writer.println();
writer.println();
}
}
| 5,588 | 38.921429 | 140 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TimedOperationCategory.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
/**
* A category for a {@link TimedOperation}, rendered either as a section
* if several operations are registered on the same category but with
* distinct labels, or put into the "remaining categories" section.
*
* @author Juan Martín Sotuyo Dodero
*/
public enum TimedOperationCategory {
/** Rule execution proper. */
RULE,
COLLECT_FILES,
LOAD_RULES,
PARSER,
/** Subdivided into one label for each stage. */
LANGUAGE_SPECIFIC_PROCESSING,
RULE_AST_INDEXATION,
REPORTING,
FILE_PROCESSING,
ANALYSIS_CACHE,
UNACCOUNTED;
public String displayName() {
final String[] parts = name().toLowerCase(Locale.getDefault()).split("_");
final StringBuilder sb = new StringBuilder();
for (final String part : parts) {
sb.append(StringUtils.capitalize(part)).append(' ');
}
sb.setLength(sb.length() - 1); // remove the final space
return sb.toString();
}
}
| 1,165 | 26.761905 | 82 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TimingReport.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.benchmark.TimeTracker.TimedOperationKey;
import net.sourceforge.pmd.benchmark.TimeTracker.TimedResult;
/**
* A report on timing data obtained through the execution of PMD
* @author Juan Martín Sotuyo Dodero
*/
public class TimingReport {
private final long wallClockMillis;
private final Map<TimedOperationKey, TimedResult> results;
/* package */ TimingReport(final long wallClockMillis, final Map<TimedOperationKey, TimedResult> accumulatedResults) {
this.wallClockMillis = wallClockMillis;
results = accumulatedResults;
}
public Map<String, TimedResult> getLabeledMeasurements(final TimedOperationCategory category) {
final Map<String, TimedResult> ret = new HashMap<>();
for (final Map.Entry<TimedOperationKey, TimedResult> entry : results.entrySet()) {
final TimedOperationKey timedOperation = entry.getKey();
if (timedOperation.category == category && timedOperation.label != null) {
ret.put(timedOperation.label, entry.getValue());
}
}
return ret;
}
public TimedResult getUnlabeledMeasurements(final TimedOperationCategory category) {
for (final Map.Entry<TimedOperationKey, TimedResult> entry : results.entrySet()) {
final TimedOperationKey timedOperation = entry.getKey();
if (timedOperation.category == category && timedOperation.label == null) {
return entry.getValue();
}
}
return null;
}
public long getWallClockMillis() {
return wallClockMillis;
}
}
| 1,804 | 31.818182 | 122 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TimingReportRenderer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
import java.io.IOException;
import java.io.Writer;
/**
* Defines a renderer for {@link TimingReport}.
* @author Juan Martín Sotuyo Dodero
*/
public interface TimingReportRenderer {
/**
* Renders the given report into the given writer.
* @param report The report data to render
* @param writer The writer on which to render
* @throws IOException if the write operation fails
*/
void render(TimingReport report, Writer writer) throws IOException;
}
| 614 | 24.625 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TimedOperation.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
/**
* Describes a timed operation. It's {@link AutoCloseable}, for ease of use.
*/
public interface TimedOperation extends AutoCloseable {
/**
* Stops tracking if not already stopped.
*/
@Override
void close();
/**
* Stops tracking if not already stopped.
* @param extraDataCounter An optional additional data counter to track along the measurements.
* Users are free to track any extra value they want (ie: number of analyzed nodes,
* iterations in a loop, etc.)
*/
void close(int extraDataCounter);
}
| 739 | 27.461538 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/TimeTracker.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.benchmark;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
/**
* A time tracker class to measure time spent on different sections of PMD analysis.
* The class is thread-aware, allowing to differentiate CPU and wall clock time.
*
* @author Juan Martín Sotuyo Dodero
*/
public final class TimeTracker {
private static boolean trackTime = false;
private static long wallClockStartMillis = -1;
private static final ThreadLocal<Queue<TimerEntry>> TIMER_ENTRIES;
private static final ConcurrentMap<TimedOperationKey, TimedResult> ACCUMULATED_RESULTS = new ConcurrentHashMap<>();
private static final TimedOperation NOOP_TIMED_OPERATION = new TimedOperation() {
@Override
public void close() {
// noop
}
@Override
public void close(final int count) {
// noop
}
};
static {
TIMER_ENTRIES = ThreadLocal.withInitial(() -> Collections.asLifoQueue(new LinkedList<>()));
}
private TimeTracker() {
throw new AssertionError("Can't instantiate utility class");
}
/**
* Starts global tracking. Allows tracking operations to take place and starts the wall clock.
* Must be called once PMD starts if tracking is desired, no tracking will be performed otherwise.
*/
public static void startGlobalTracking() {
wallClockStartMillis = System.currentTimeMillis();
trackTime = true;
ACCUMULATED_RESULTS.clear(); // just in case
initThread(); // init main thread
}
/**
* Stops global tracking. Stops the wall clock. All further operations will be treated as NOOP.
* @return The timed data obtained through the run.
*/
public static TimingReport stopGlobalTracking() {
if (!trackTime) {
return null;
}
finishThread(); // finish the main thread
trackTime = false;
// Fix UNACCOUNTED metric (total time is meaningless as is call count)
final TimedResult unaccountedResult = ACCUMULATED_RESULTS.get(
new TimedOperationKey(TimedOperationCategory.UNACCOUNTED, null));
unaccountedResult.totalTimeNanos.set(unaccountedResult.selfTimeNanos.get());
unaccountedResult.callCount.set(0);
return new TimingReport(System.currentTimeMillis() - wallClockStartMillis, ACCUMULATED_RESULTS);
}
/**
* Initialize a thread, starting to track it's own time.
*/
public static void initThread() {
if (!trackTime) {
return;
}
startOperation(TimedOperationCategory.UNACCOUNTED);
}
/**
* Finishes tracking a thread.
*/
public static void finishThread() {
if (!trackTime) {
return;
}
finishOperation(0);
// clean up thread-locals in multithread analysis
if (TIMER_ENTRIES.get().isEmpty()) {
TIMER_ENTRIES.remove();
}
}
/**
* Starts tracking an operation.
* @param category The category under which to track the operation.
* @return The current timed operation being tracked.
*/
public static TimedOperation startOperation(final TimedOperationCategory category) {
return startOperation(category, null);
}
/**
* Starts tracking an operation.
* @param category The category under which to track the operation.
* @param label A label to be added to the category. Allows to differentiate measures within a single category.
* @return The current timed operation being tracked.
*/
public static TimedOperation startOperation(final TimedOperationCategory category, final String label) {
if (!trackTime) {
return NOOP_TIMED_OPERATION;
}
TIMER_ENTRIES.get().add(new TimerEntry(category, label));
return new TimedOperationImpl();
}
/**
* Finishes tracking an operation.
* @param extraDataCounter An optional additional data counter to track along the measurements.
* Users are free to track any extra value they want (ie: number of analyzed nodes,
* iterations in a loop, etc.)
*/
/* default */ static void finishOperation(final long extraDataCounter) {
if (!trackTime) {
return;
}
final Queue<TimerEntry> queue = TIMER_ENTRIES.get();
final TimerEntry timerEntry = queue.remove();
// Compute if absent
TimedResult result = ACCUMULATED_RESULTS.get(timerEntry.operation);
if (result == null) {
ACCUMULATED_RESULTS.putIfAbsent(timerEntry.operation, new TimedResult());
result = ACCUMULATED_RESULTS.get(timerEntry.operation);
}
// Update counters and let next element on the stack ignore the time we spent
final long delta = result.accumulate(timerEntry, extraDataCounter);
if (!queue.isEmpty()) {
queue.peek().inNestedOperationsNanos += delta;
}
}
public static void bench(String label, Runnable runnable) {
try (TimedOperation ignored = startOperation(TimedOperationCategory.LANGUAGE_SPECIFIC_PROCESSING, label)) {
runnable.run();
}
}
public static <T> T bench(String label, Supplier<T> runnable) {
try (TimedOperation ignored = startOperation(TimedOperationCategory.LANGUAGE_SPECIFIC_PROCESSING, label)) {
return runnable.get();
}
}
/**
* An entry in the open timers queue. Defines an operation that has started and hasn't finished yet.
*/
private static class TimerEntry {
/* package */ final TimedOperationKey operation;
/* package */ final long start;
/* package */ long inNestedOperationsNanos = 0;
/* package */ TimerEntry(final TimedOperationCategory category, final String label) {
this.operation = new TimedOperationKey(category, label);
this.start = System.nanoTime();
}
@Override
public String toString() {
return "TimerEntry for " + operation;
}
}
/**
* Aggregate results measured so far for a given category + label.
*/
/* package */ static class TimedResult {
/* package */ AtomicLong totalTimeNanos = new AtomicLong();
/* package */ AtomicLong selfTimeNanos = new AtomicLong();
/* package */ AtomicInteger callCount = new AtomicInteger();
/* package */ AtomicLong extraDataCounter = new AtomicLong();
/**
* Adds a new {@link TimerEntry} to the results.
* @param timerEntry The entry to be added
* @param extraData Any extra data counter to be added
* @return The delta time transcurred since the {@link TimerEntry} began in nanos.
*/
/* package */ long accumulate(final TimerEntry timerEntry, final long extraData) {
final long delta = System.nanoTime() - timerEntry.start;
totalTimeNanos.getAndAdd(delta);
selfTimeNanos.getAndAdd(delta - timerEntry.inNestedOperationsNanos);
callCount.getAndIncrement();
extraDataCounter.getAndAdd(extraData);
return delta;
}
/**
* Merges the times (and only the times) from another {@link TimedResult} into self.
* @param timedResult The {@link TimedResult} to merge
*/
/* package */ void mergeTimes(final TimedResult timedResult) {
totalTimeNanos.getAndAdd(timedResult.totalTimeNanos.get());
selfTimeNanos.getAndAdd(timedResult.selfTimeNanos.get());
}
}
/**
* A unique identifier for a timed operation
*/
/* package */ static class TimedOperationKey {
/* package */ final TimedOperationCategory category;
/* package */ final String label;
/* package */ TimedOperationKey(final TimedOperationCategory category, final String label) {
this.category = category;
this.label = label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TimedOperationKey other = (TimedOperationKey) obj;
return category == other.category && Objects.equals(label, other.label);
}
@Override
public String toString() {
return "TimedOperationKey [category=" + category + ", label=" + label + "]";
}
}
/**
* A standard timed operation implementation.
*/
private static final class TimedOperationImpl implements TimedOperation {
private boolean closed = false;
@Override
public void close() {
close(0);
}
@Override
public void close(int extraDataCounter) {
if (closed) {
return;
}
closed = true;
TimeTracker.finishOperation(extraDataCounter);
}
}
}
| 9,902 | 32.914384 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/DoubleMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.properties.builders.MultiNumericPropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Multi-valued double property.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
*
* @deprecated Use a {@code PropertyDescriptor<List<Double>>} instead. A builder is available from {@link PropertyFactory#doubleListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class DoubleMultiProperty extends AbstractMultiNumericProperty<Double> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues Array of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated use {@link PropertyFactory#doubleListProperty(String)}
*/
@Deprecated
public DoubleMultiProperty(String theName, String theDescription, Double min, Double max,
Double[] defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, Arrays.asList(defaultValues), theUIOrder, false);
}
/** Master constructor. */
private DoubleMultiProperty(String theName, String theDescription, Double min, Double max,
List<Double> defaultValues, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, defaultValues, theUIOrder, isDefinedExternally);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated use {@link PropertyFactory#doubleListProperty(String)}
*/
@Deprecated
public DoubleMultiProperty(String theName, String theDescription, Double min, Double max,
List<Double> defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, defaultValues, theUIOrder, false);
}
@Override
public Class<Double> type() {
return Double.class;
}
@Override
protected Double createFrom(String value) {
return Double.valueOf(value);
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Double, DoubleMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Double, DoubleMultiPBuilder>(Double.class, ValueParserConstants.DOUBLE_PARSER) {
@Override
protected DoubleMultiPBuilder newBuilder(String name) {
return new DoubleMultiPBuilder(name);
}
};
}
/** @deprecated use {@link PropertyFactory#doubleListProperty(String)} */
@Deprecated
public static DoubleMultiPBuilder named(String name) {
return new DoubleMultiPBuilder(name);
}
/** @deprecated use {@link PropertyFactory#doubleListProperty(String)} */
@Deprecated
public static final class DoubleMultiPBuilder extends MultiNumericPropertyBuilder<Double, DoubleMultiPBuilder> {
private DoubleMultiPBuilder(String name) {
super(name);
}
@Override
public DoubleMultiProperty build() {
return new DoubleMultiProperty(name, description, lowerLimit, upperLimit, defaultValues, uiOrder, isDefinedInXML);
}
}
}
| 4,119 | 34.517241 | 161 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/LongMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.properties.builders.MultiNumericPropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Multi-valued long property.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
*
* @deprecated Use a {@code PropertyDescriptor<List<Long>>} instead. A builder is available from {@link PropertyFactory#longIntListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class LongMultiProperty extends AbstractMultiNumericProperty<Long> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues Array of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#longIntListProperty(String)}
*/
@Deprecated
public LongMultiProperty(String theName, String theDescription, Long min, Long max,
Long[] defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, Arrays.asList(defaultValues), theUIOrder, false);
}
/** Master constructor. */
private LongMultiProperty(String theName, String theDescription, Long min, Long max,
List<Long> defaultValues, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, defaultValues, theUIOrder, isDefinedExternally);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#longIntListProperty(String)}
*/
@Deprecated
public LongMultiProperty(String theName, String theDescription, Long min, Long max,
List<Long> defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, defaultValues, theUIOrder, false);
}
@Override
public Class<Long> type() {
return Long.class;
}
@Override
protected Long createFrom(String value) {
return Long.valueOf(value);
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Long, LongMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Long, LongMultiPBuilder>(Long.class, ValueParserConstants.LONG_PARSER) {
@Override
protected LongMultiPBuilder newBuilder(String name) {
return new LongMultiPBuilder(name);
}
};
}
/** @deprecated Use {@link PropertyFactory#longIntListProperty(String)} */
@Deprecated
public static LongMultiPBuilder named(String name) {
return new LongMultiPBuilder(name);
}
/** @deprecated Use {@link PropertyFactory#longIntListProperty(String)} */
@Deprecated
public static final class LongMultiPBuilder
extends MultiNumericPropertyBuilder<Long, LongMultiPBuilder> {
protected LongMultiPBuilder(String name) {
super(name);
}
@Override
public LongMultiProperty build() {
return new LongMultiProperty(name, description, lowerLimit, upperLimit,
defaultValues, uiOrder, isDefinedInXML);
}
}
}
| 4,076 | 32.418033 | 153 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyTypeId.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorExternalBuilder;
/**
* Enumerates the properties that can be built from the XML. Defining a property in
* the XML requires the {@code type} attribute, which acts as a mnemonic for the type
* of the property that should be built. The mapping between the values of this attribute
* and the concrete property that is built is encoded in the constants of this enum.
*
* <h1>Properties API changes</h1>This class' API is mainly provided to build GUIs for XPath rules
* like the rule designer, so that they have info about the available properties from XML. As such,
* the number of clients are probably low. Nevertheless, a bunch of members have been deprecated to
* warn about probable upcoming API changes with 7.0.0, but the amount of change may be greater.
* See {@link PropertyDescriptor} for more info about property framework changes with 7.0.0.
*
* @author Clément Fournier
* @see PropertyDescriptorExternalBuilder
* @since 6.0.0
*/
public enum PropertyTypeId {
// These are exclusively used for XPath rules. It would make more sense to model the supported
// property types around XML Schema Datatypes (XSD) 1.0 or 1.1 instead of Java datatypes (save for
// e.g. the Class type), including the mnemonics (eg. xs:integer instead of Integer)
BOOLEAN("Boolean", BooleanProperty.extractor(), ValueParserConstants.BOOLEAN_PARSER),
/** @deprecated see {@link BooleanMultiProperty} */
@Deprecated
BOOLEAN_LIST("List[Boolean]", BooleanMultiProperty.extractor(), ValueParserConstants.BOOLEAN_PARSER),
STRING("String", StringProperty.extractor(), ValueParserConstants.STRING_PARSER),
STRING_LIST("List[String]", StringMultiProperty.extractor(), ValueParserConstants.STRING_PARSER),
CHARACTER("Character", CharacterProperty.extractor(), ValueParserConstants.CHARACTER_PARSER),
CHARACTER_LIST("List[Character]", CharacterMultiProperty.extractor(), ValueParserConstants.CHARACTER_PARSER),
REGEX("Regex", RegexProperty.extractor(), ValueParserConstants.REGEX_PARSER),
INTEGER("Integer", IntegerProperty.extractor(), ValueParserConstants.INTEGER_PARSER),
INTEGER_LIST("List[Integer]", IntegerMultiProperty.extractor(), ValueParserConstants.INTEGER_PARSER),
LONG("Long", LongProperty.extractor(), ValueParserConstants.LONG_PARSER),
LONG_LIST("List[Long]", LongMultiProperty.extractor(), ValueParserConstants.LONG_PARSER),
@Deprecated
FLOAT("Float", FloatProperty.extractor(), ValueParserConstants.FLOAT_PARSER),
@Deprecated
FLOAT_LIST("List[Float]", FloatMultiProperty.extractor(), ValueParserConstants.FLOAT_PARSER),
DOUBLE("Double", DoubleProperty.extractor(), ValueParserConstants.DOUBLE_PARSER),
DOUBLE_LIST("List[Double]", DoubleMultiProperty.extractor(), ValueParserConstants.DOUBLE_PARSER);
private static final Map<String, PropertyTypeId> CONSTANTS_BY_MNEMONIC;
private final String stringId;
private final PropertyDescriptorExternalBuilder<?> factory;
private final ValueParser<?> valueParser;
static {
Map<String, PropertyTypeId> temp = new HashMap<>();
for (PropertyTypeId id : values()) {
temp.put(id.stringId, id);
}
CONSTANTS_BY_MNEMONIC = Collections.unmodifiableMap(temp);
}
PropertyTypeId(String id, PropertyDescriptorExternalBuilder<?> factory, ValueParser<?> valueParser) {
this.stringId = id;
this.factory = factory;
this.valueParser = valueParser;
}
/**
* Gets the value of the type attribute represented by this constant.
*
* @return The string id
*/
public String getStringId() {
return stringId;
}
/**
* Gets the factory associated to the type id, that can build the
* property from strings extracted from the XML.
*
* @return The factory
*/
@Deprecated
public PropertyDescriptorExternalBuilder<?> getFactory() {
return factory;
}
/**
* Returns true if the property corresponding to this factory is numeric,
* which means it can be safely cast to a {@link NumericPropertyDescriptor}.
*
* @return whether the property is numeric
*/
@Deprecated
public boolean isPropertyNumeric() {
return factory instanceof PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric
|| factory instanceof PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric;
}
/**
* Returns true if the property corresponding to this factory takes
* lists of values as its value.
*
* @return whether the property is multivalue
*
* @deprecated see {@link PropertyDescriptor#isMultiValue()}
*/
@Deprecated
public boolean isPropertyMultivalue() {
return factory.isMultiValue();
}
/**
* Returns the value type of the property corresponding to this factory.
* This is the component type of the list if the property is multivalued.
*
* @return The value type of the property
*
* @deprecated see {@link PropertyDescriptor#type()}
*/
@Deprecated
public Class<?> propertyValueType() {
return factory.valueType();
}
/**
* Gets the object used to parse the values of this property from a string.
* If the property is multivalued, the parser only parses individual components
* of the list. A list parser can be obtained with {@link ValueParserConstants#multi(ValueParser, char)}.
*
* @return The value parser
*
* @deprecated see {@link PropertyDescriptor#valueFrom(String)}
*/
@Deprecated
public ValueParser<?> getValueParser() {
return valueParser;
}
/**
* Returns the full mappings from type ids to enum constants.
*
* @return The full mapping.
*/
public static Map<String, PropertyTypeId> typeIdsToConstants() {
return CONSTANTS_BY_MNEMONIC;
}
/**
* Gets the factory for the descriptor identified by the string id.
*
* @param stringId The identifier of the type
*
* @return The factory used to build new instances of a descriptor
*
* @deprecated See {@link PropertyDescriptorExternalBuilder}
*/
@Deprecated
public static PropertyDescriptorExternalBuilder<?> factoryFor(String stringId) {
PropertyTypeId cons = CONSTANTS_BY_MNEMONIC.get(stringId);
return cons == null ? null : cons.factory;
}
/**
* Gets the enum constant corresponding to the given mnemonic.
*
* @param stringId A mnemonic for the property type
*
* @return A PropertyTypeId
*/
public static PropertyTypeId lookupMnemonic(String stringId) {
return CONSTANTS_BY_MNEMONIC.get(stringId);
}
/**
* Gets the string representation of this type, as it should be given
* when defining a descriptor in the xml.
*
* @param valueType The type to look for
* @param multiValue Whether the descriptor is multivalued or not
*
* @return The string id
*
* @deprecated The signature will probably be altered in 7.0.0 but a similar functionality will be available
*/
@Deprecated
public static String typeIdFor(Class<?> valueType, boolean multiValue) {
for (Map.Entry<String, PropertyTypeId> entry : CONSTANTS_BY_MNEMONIC.entrySet()) {
if (entry.getValue().propertyValueType() == valueType
&& entry.getValue().isPropertyMultivalue() == multiValue) {
return entry.getKey();
}
}
return null;
}
}
| 7,964 | 35.369863 | 113 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/DoubleProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.DOUBLE_PARSER;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleNumericPropertyBuilder;
/**
* Defines a property type that support single double-type property values within an upper and lower boundary.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
*
* @deprecated Use a {@code PropertyDescriptor<Double>} instead. A builder is available from {@link PropertyFactory#doubleProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class DoubleProperty extends AbstractNumericProperty<Double> {
/**
* Constructor for DoubleProperty that limits itself to a single value within the specified limits. Converts string
* arguments into the Double values.
*
* @param theName Name
* @param theDescription Description
* @param minStr Minimum value of the property
* @param maxStr Maximum value of the property
* @param defaultStr Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#doubleProperty(String)}.
*/
@Deprecated
public DoubleProperty(String theName, String theDescription, String minStr, String maxStr, String defaultStr,
float theUIOrder) {
this(theName, theDescription, doubleFrom(minStr), doubleFrom(maxStr), doubleFrom(defaultStr), theUIOrder, false);
}
/** Master constructor. */
private DoubleProperty(String theName, String theDescription, Double min, Double max, Double theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, theDefault, theUIOrder, isDefinedExternally);
}
/**
* Constructor that limits itself to a single value within the specified limits.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param theDefault Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#doubleProperty(String)}.
*/
@Deprecated
public DoubleProperty(String theName, String theDescription, Double min, Double max, Double theDefault,
float theUIOrder) {
this(theName, theDescription, min, max, theDefault, theUIOrder, false);
}
@Override
public Class<Double> type() {
return Double.class;
}
@Override
protected Double createFrom(String value) {
return doubleFrom(value);
}
/**
* Parses a String into a Double.
*
* @param numberString String to parse
*
* @return Parsed Double
*/
private static Double doubleFrom(String numberString) {
return DOUBLE_PARSER.valueOf(numberString);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Double, DoublePBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Double, DoublePBuilder>(Double.class, ValueParserConstants.DOUBLE_PARSER) {
@Override
protected DoublePBuilder newBuilder(String name) {
return new DoublePBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#doubleProperty(String)}.
*/
@Deprecated
public static DoublePBuilder named(String name) {
return new DoublePBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#doubleProperty(String)}.
*/
@Deprecated
public static final class DoublePBuilder extends SingleNumericPropertyBuilder<Double, DoublePBuilder> {
private DoublePBuilder(String name) {
super(name);
}
@Override
public DoubleProperty build() {
return new DoubleProperty(name, description, lowerLimit, upperLimit, defaultValue, uiOrder, isDefinedInXML);
}
}
}
| 4,546 | 32.932836 | 157 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParserConstants.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* This class will be completely scrapped with 7.0.0. It only hid away the syntactic
* overhead caused by the lack of lambdas in Java 7.
*
* @author Clément Fournier
* @since 6.0.0
* @deprecated Was internal API
*/
@Deprecated
@InternalApi
public final class ValueParserConstants {
/** Extracts characters. */
static final ValueParser<Character> CHARACTER_PARSER = new ValueParser<Character>() {
@Override
public Character valueOf(String value) {
if (value == null || value.length() != 1) {
throw new IllegalArgumentException("missing/ambiguous character value");
}
return value.charAt(0);
}
};
/** Extracts strings. That's a dummy used to return a list in StringMultiProperty. */
static final ValueParser<String> STRING_PARSER = new ValueParser<String>() {
@Override
public String valueOf(String value) {
return StringUtils.trim(value);
}
};
/** Extracts integers. */
static final ValueParser<Integer> INTEGER_PARSER = new ValueParser<Integer>() {
@Override
public Integer valueOf(String value) {
return Integer.valueOf(StringUtils.trim(value));
}
};
/** Extracts booleans. */
static final ValueParser<Boolean> BOOLEAN_PARSER = new ValueParser<Boolean>() {
@Override
public Boolean valueOf(String value) {
return Boolean.valueOf(StringUtils.trim(value));
}
};
/** Extracts floats. */
static final ValueParser<Float> FLOAT_PARSER = new ValueParser<Float>() {
@Override
public Float valueOf(String value) {
return Float.valueOf(value);
}
};
/** Extracts longs. */
static final ValueParser<Long> LONG_PARSER = new ValueParser<Long>() {
@Override
public Long valueOf(String value) {
return Long.valueOf(StringUtils.trim(value));
}
};
/** Extracts doubles. */
static final ValueParser<Double> DOUBLE_PARSER = new ValueParser<Double>() {
@Override
public Double valueOf(String value) {
return Double.valueOf(value);
}
};
/** Extracts files */
static final ValueParser<File> FILE_PARSER = new ValueParser<File>() {
@Override
public File valueOf(String value) throws IllegalArgumentException {
return new File(StringUtils.trim(value));
}
};
/** Compiles a regex. */
static final ValueParser<Pattern> REGEX_PARSER = new ValueParser<Pattern>() {
@Override
public Pattern valueOf(String value) throws IllegalArgumentException {
return Pattern.compile(value);
}
};
private ValueParserConstants() {
}
static <T> ValueParser<T> enumerationParser(final Map<String, T> mappings) {
if (mappings.containsValue(null)) {
throw new IllegalArgumentException("Map may not contain entries with null values");
}
return new ValueParser<T>() {
@Override
public T valueOf(String value) throws IllegalArgumentException {
String trimmedValue = StringUtils.trim(value);
if (!mappings.containsKey(trimmedValue)) {
throw new IllegalArgumentException("Value " + value + " was not in the set " + mappings.keySet());
}
return mappings.get(trimmedValue);
}
};
}
/**
* Returns a value parser parsing lists of values of type U.
*
* @param parser Parser used to parse a single value
* @param delimiter Char delimiting values
* @param <U> Element type of the target list
*
* @return A list of values
*/
public static <U> ValueParser<List<U>> multi(final ValueParser<U> parser, final char delimiter) {
return new ValueParser<List<U>>() {
@Override
public List<U> valueOf(String value) throws IllegalArgumentException {
return parsePrimitives(value, delimiter, parser);
}
};
}
/**
* Parses a string into a list of values of type {@literal <U>}.
*
* @param toParse The string to parse
* @param delimiter The delimiter to use
* @param extractor The function mapping a string to an instance of {@code <U>}
* @param <U> The type of the values to parse
*
* @return A list of values
*/
// FUTURE 1.8 : use java.util.function.Function<String, U> in place of ValueParser<U>,
// replace ValueParser constants with static functions
static <U> List<U> parsePrimitives(String toParse, char delimiter, ValueParser<U> extractor) {
String[] values = StringUtils.split(toParse, delimiter);
List<U> result = new ArrayList<>();
for (String s : values) {
result.add(extractor.valueOf(s));
}
return result;
}
private static final char ESCAPE_CHAR = '\\';
/**
* Parse a list delimited with the given delimiter, converting individual
* values to type {@code <U>} with the given extractor. Any character is
* escaped with a backslash. This is useful to escape the delimiter, and
* to escape the backslash. For example:
* <pre>{@code
*
* "a,c" -> [ "a", "c" ]
* "a\,c" -> [ "a,c" ]
* "a\c" -> [ "ac" ]
* "a\\c" -> [ "a\c" ]
* "a\" -> [ "a\" ] (a backslash at the end of the string is just a backslash)
*
* }</pre>
*/
static <U> List<U> parseListWithEscapes(String str, char delimiter, ValueParser<U> extractor) {
if (str.isEmpty()) {
return Collections.emptyList();
}
List<U> result = new ArrayList<>();
StringBuilder currentToken = new StringBuilder();
boolean inEscapeMode = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (inEscapeMode) {
inEscapeMode = false;
currentToken.append(c);
} else if (c == delimiter) {
result.add(extractor.valueOf(currentToken.toString()));
currentToken = new StringBuilder();
} else if (c == ESCAPE_CHAR && i < str.length() - 1) {
// this is ordered this way so that if the delimiter is
// itself a backslash, no escapes are processed.
inEscapeMode = true;
} else {
currentToken.append(c);
}
}
if (currentToken.length() > 0) {
result.add(extractor.valueOf(currentToken.toString()));
}
return result;
}
}
| 7,118 | 31.958333 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/FloatProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.FLOAT_PARSER;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleNumericPropertyBuilder;
/**
* Defines a property type that supports single float property values within an upper and lower boundary.
*
*
* @deprecated Use {@link PropertyFactory#doubleProperty(String)} instead. This class will be removed with 7.0.0.
* @author Brian Remedios
*/
@Deprecated
public final class FloatProperty extends AbstractNumericProperty<Float> {
/**
* Constructor for FloatProperty that limits itself to a single value within the specified limits. Converts string
* arguments into the Float values.
*
* @param theName Name
* @param theDescription Description
* @param minStr Minimum value of the property
* @param maxStr Maximum value of the property
* @param defaultStr Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#doubleProperty(String)} instead.
*/
@Deprecated
public FloatProperty(String theName, String theDescription, String minStr, String maxStr, String defaultStr,
float theUIOrder) {
this(theName, theDescription, FLOAT_PARSER.valueOf(minStr),
FLOAT_PARSER.valueOf(maxStr), FLOAT_PARSER.valueOf(defaultStr), theUIOrder, false);
}
/** Master constructor. */
private FloatProperty(String theName, String theDescription, Float min, Float max, Float theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, theDefault, theUIOrder, isDefinedExternally);
}
/**
* Constructor that limits itself to a single value within the specified limits.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param theDefault Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#doubleProperty(String)} instead.
*/
@Deprecated
public FloatProperty(String theName, String theDescription, Float min, Float max, Float theDefault,
float theUIOrder) {
this(theName, theDescription, min, max, theDefault, theUIOrder, false);
}
@Override
public Class<Float> type() {
return Float.class;
}
@Override
protected Float createFrom(String value) {
return FLOAT_PARSER.valueOf(value);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Float, FloatPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Float, FloatPBuilder>(Float.class, ValueParserConstants.FLOAT_PARSER) {
@Override
protected FloatPBuilder newBuilder(String name) {
return new FloatPBuilder(name);
}
};
}
/** @deprecated Use {@link PropertyFactory#doubleProperty(String)} instead. */
@Deprecated
public static FloatPBuilder named(String name) {
return new FloatPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#doubleProperty(String)} instead.
*/
@Deprecated
public static final class FloatPBuilder extends SingleNumericPropertyBuilder<Float, FloatPBuilder> {
private FloatPBuilder(String name) {
super(name);
}
@Override
public FloatProperty build() {
return new FloatProperty(name, description, lowerLimit, upperLimit, defaultValue, uiOrder, isDefinedInXML);
}
}
}
| 4,201 | 34.310924 | 153 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/RegexProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.regex.Pattern;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper.SingleValue;
import net.sourceforge.pmd.properties.builders.SingleValuePropertyBuilder;
/**
* Property which has a regex pattern as a value. This property has no multi-valued
* variant, since it would be ambiguous whether the delimiters are part of the regex
* or not.
*
* @author Clément Fournier
* @since 6.2.0
* @deprecated Use a {@code PropertyDescriptor<Pattern>}. A builder is available from {@link PropertyFactory#regexProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class RegexProperty extends AbstractSingleValueProperty<Pattern> {
RegexProperty(String theName, String theDescription, Pattern theDefault, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally);
}
@Override
protected Pattern createFrom(String toParse) {
return Pattern.compile(toParse);
}
@Override
public Class<Pattern> type() {
return Pattern.class;
}
static SingleValue<Pattern, RegexPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue<Pattern, RegexPBuilder>(Pattern.class, ValueParserConstants.REGEX_PARSER) {
@Override
protected RegexPBuilder newBuilder(String name) {
return new RegexPBuilder(name);
}
};
}
/**
* Creates a new builder for a regex property.
*
* @param name The name of the property
*
* @return A new builder
*
* @deprecated Use {@link PropertyFactory#regexProperty(String)}
*/
@Deprecated
public static RegexPBuilder named(String name) {
return new RegexPBuilder(name);
}
/**
* Builder for a {@link RegexProperty}.
*
* @deprecated Use {@link PropertyFactory#regexProperty(String)}
*/
@Deprecated
public static final class RegexPBuilder extends SingleValuePropertyBuilder<Pattern, RegexProperty.RegexPBuilder> {
private RegexPBuilder(String name) {
super(name);
}
/**
* Specify a default pattern for the property.
* The argument must be a valid regex pattern.
*
* @param val Regex pattern
*
* @return The same builder
*/
public RegexPBuilder defaultValue(String val) {
return super.defaultValue(Pattern.compile(val));
}
@Override
public RegexProperty build() {
return new RegexProperty(this.name, this.description, this.defaultValue, this.uiOrder, isDefinedInXML);
}
}
}
| 2,979 | 28.8 | 149 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/CharacterProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.CHARACTER_PARSER;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleValuePropertyBuilder;
/**
* Defines a property type that supports single Character values.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<Character>}. A builder is available from {@link PropertyFactory#charProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class CharacterProperty extends AbstractSingleValueProperty<Character> {
/**
* Constructor for CharacterProperty.
*
* @param theName String
* @param theDescription String
* @param defaultStr String
* @param theUIOrder float
*
* @throws IllegalArgumentException
* @deprecated Use {@link PropertyFactory#charProperty(String)}
*/
@Deprecated
public CharacterProperty(String theName, String theDescription, String defaultStr, float theUIOrder) {
this(theName, theDescription, charFrom(defaultStr), theUIOrder, false);
}
/** Master constructor. */
private CharacterProperty(String theName, String theDescription, Character theDefault, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally);
}
/**
* Constructor.
*
* @param theName Name
* @param theDescription Description
* @param theDefault Default value
* @param theUIOrder UI order
* @deprecated Use {@link PropertyFactory#charProperty(String)}
*/
@Deprecated
public CharacterProperty(String theName, String theDescription, Character theDefault, float theUIOrder) {
this(theName, theDescription, theDefault, theUIOrder, false);
}
@Override
public Class<Character> type() {
return Character.class;
}
@Override
public Character createFrom(String valueString) throws IllegalArgumentException {
return charFrom(valueString);
}
/**
* Parses a String into a Character.
*
* @param charStr String to parse
*
* @return Parsed Character
* @throws IllegalArgumentException if the String doesn't have length 1
*/
public static Character charFrom(String charStr) {
return CHARACTER_PARSER.valueOf(charStr);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue<Character, CharacterPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue<Character, CharacterPBuilder>(Character.class, ValueParserConstants.CHARACTER_PARSER) {
@Override
protected CharacterPBuilder newBuilder(String name) {
return new CharacterPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#charProperty(String)}
*/
@Deprecated
public static CharacterPBuilder named(String name) {
return new CharacterPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#charProperty(String)}
*/
@Deprecated
public static final class CharacterPBuilder extends SingleValuePropertyBuilder<Character, CharacterPBuilder> {
private CharacterPBuilder(String name) {
super(name);
}
@Override
public CharacterProperty build() {
return new CharacterProperty(this.name, this.description, this.defaultValue, this.uiOrder, isDefinedInXML);
}
}
}
| 3,791 | 29.829268 | 161 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/StringMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.builders.MultiValuePropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Defines a datatype that supports multiple String values. Note that all strings must be filtered by the delimiter
* character.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<List<String>>}. A builder is available from {@link PropertyFactory#stringListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class StringMultiProperty extends AbstractMultiValueProperty<String> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues Array of defaults
* @param theUIOrder UI order
* @param delimiter The delimiter to use
*
* @throws IllegalArgumentException if a default value contains the delimiter
* @throws NullPointerException if the defaults array is null
* @deprecated Use {@link PropertyFactory#stringListProperty(String)}
*/
@Deprecated
public StringMultiProperty(String theName, String theDescription, String[] defaultValues, float theUIOrder,
char delimiter) {
this(theName, theDescription, Arrays.asList(defaultValues), theUIOrder, delimiter);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues List of defaults
* @param theUIOrder UI order
* @param delimiter The delimiter to useg
*
* @throws IllegalArgumentException if a default value contains the delimiter
* @throws NullPointerException if the defaults array is null
* @deprecated Use {@link PropertyFactory#stringListProperty(String)}
*/
@Deprecated
public StringMultiProperty(String theName, String theDescription, List<String> defaultValues, float theUIOrder,
char delimiter) {
this(theName, theDescription, defaultValues, theUIOrder, delimiter, false);
}
/** Master constructor. */
private StringMultiProperty(String theName, String theDescription, List<String> defaultValues, float theUIOrder,
char delimiter, boolean isDefinedExternally) {
super(theName, theDescription, defaultValues, theUIOrder, delimiter, isDefinedExternally);
checkDefaults(defaultValues, delimiter);
}
@Override
public Class<String> type() {
return String.class;
}
@Override
public List<String> valueFrom(String valueString) {
return Arrays.asList(StringUtils.split(valueString, multiValueDelimiter()));
}
@Override
protected String valueErrorFor(String value) {
if (value == null) {
return "Missing value";
}
if (containsDelimiter(value)) {
return "Value cannot contain the '" + multiValueDelimiter() + "' character";
}
// TODO - eval against regex checkers
return null;
}
/**
* Returns true if the multi value delimiter is present in the string.
*
* @param value String
*
* @return boolean
*/
private boolean containsDelimiter(String value) {
return value.indexOf(multiValueDelimiter()) >= 0;
}
@Override
protected String createFrom(String toParse) {
return toParse;
}
/**
* Checks if the values are valid.
*
* @param defaultValue The default value
* @param delim The delimiter
*
* @throws IllegalArgumentException if one value contains the delimiter
*/
private static void checkDefaults(List<String> defaultValue, char delim) {
if (defaultValue == null) {
return;
}
for (String aDefaultValue : defaultValue) {
if (aDefaultValue.indexOf(delim) >= 0) {
throw new IllegalArgumentException("Cannot include the delimiter in the set of defaults");
}
}
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue<String, StringMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue<String, StringMultiPBuilder>(String.class, ValueParserConstants.STRING_PARSER) {
@Override
protected StringMultiPBuilder newBuilder(String name) {
return new StringMultiPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#stringListProperty(String)}
*/
@Deprecated
public static StringMultiPBuilder named(String name) {
return new StringMultiPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#stringListProperty(String)}
*/
@Deprecated
public static final class StringMultiPBuilder extends MultiValuePropertyBuilder<String, StringMultiPBuilder> {
private StringMultiPBuilder(String name) {
super(name);
}
@Override
public StringMultiProperty build() {
return new StringMultiProperty(this.name, this.description, this.defaultValues, this.uiOrder, this.multiValueDelimiter, isDefinedInXML);
}
}
}
| 5,635 | 29.967033 | 153 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/GenericMultiValuePropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.properties.constraints.PropertyConstraint;
/**
* If we implement schema changes to properties, delimiter logic will probably be scrapped,
* and hence the divide between multi-value and single-value property descriptors. We can then
* use a single class for all property descriptors.
*
* @author Clément Fournier
* @since 6.10.0
*/
final class GenericMultiValuePropertyDescriptor<V, C extends Collection<V>> extends AbstractMultiValueProperty<V> {
private final Set<PropertyConstraint<? super C>> listValidators;
private final ValueParser<V> parser;
private final Class<V> type;
GenericMultiValuePropertyDescriptor(String name, String description, float uiOrder,
Collection<V> defaultValue,
Set<PropertyConstraint<? super C>> listValidators,
ValueParser<V> parser,
char delim,
Class<V> type) {
// this cast is safe until 7.0.0
super(name, description, (List<V>) defaultValue, uiOrder, delim, false);
this.listValidators = listValidators;
this.parser = parser;
this.type = type;
String dftValueError = errorFor(new ArrayList<>(defaultValue));
if (dftValueError != null) {
throw new IllegalArgumentException(dftValueError);
}
}
@SuppressWarnings("unchecked")
@Override
public String errorFor(List<V> values) {
for (PropertyConstraint<? super C> lv : listValidators) {
// Note: the unchecked cast is safe because pre-7.0.0,
// we only allow building property descriptors for lists.
// C is thus always List<V>, and the cast doesn't fail
// Post-7.0.0, the multi-value property classes will be removed
// and C will be the actual type parameter of the returned property
// descriptor
String error = lv.validate((C) values);
if (error != null) {
return error;
}
}
return null;
}
@Override
protected V createFrom(String toParse) {
return parser.valueOf(toParse);
}
@Override
public Class<V> type() {
return type;
}
}
| 2,592 | 30.621951 | 115 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiValueProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.Rule;
/**
* Multi-valued property.
*
* @param <V> The type of the individual values. The multiple values are wrapped into a list.
*
* @author Clément Fournier
* @version 6.0.0
*/
@Deprecated
/* default */ abstract class AbstractMultiValueProperty<V> extends AbstractProperty<List<V>>
implements MultiValuePropertyDescriptor<V> {
/** The default value. */
private final List<V> defaultValue;
private final char multiValueDelimiter;
/**
* Creates a multi valued property using the default delimiter {@link #DEFAULT_DELIMITER}.
*
* @param theName Name of the property (must not be empty)
* @param theDescription Description (must not be empty)
* @param theDefault Default value
* @param theUIOrder UI order (must be positive or zero)
*
* @throws IllegalArgumentException If name or description are empty, or UI order is negative.
*/
AbstractMultiValueProperty(String theName, String theDescription, List<V> theDefault, float theUIOrder,
boolean isDefinedExternally) {
this(theName, theDescription, theDefault, theUIOrder, DEFAULT_DELIMITER, isDefinedExternally);
}
/**
* Creates a multi valued property using a custom delimiter.
*
* @param theName Name of the property (must not be empty)
* @param theDescription Description (must not be empty)
* @param theDefault Default value
* @param theUIOrder UI order (must be positive or zero)
* @param delimiter The delimiter to separate multiple values
*
* @throws IllegalArgumentException If name or description are empty, or UI order is negative.
*/
AbstractMultiValueProperty(String theName, String theDescription, List<V> theDefault,
float theUIOrder, char delimiter, boolean isDefinedExternally) {
super(theName, theDescription, theUIOrder, isDefinedExternally);
defaultValue = Collections.unmodifiableList(theDefault);
multiValueDelimiter = delimiter;
}
@Override
public final boolean isMultiValue() {
return true;
}
/* This is the one overridden in PropertyDescriptor */
@Override
public String propertyErrorFor(Rule rule) {
List<V> realValues = rule.getProperty(this);
return realValues == null ? null : errorFor(realValues);
}
@Override
public String errorFor(List<V> values) {
String err;
for (V value2 : values) {
err = valueErrorFor(value2);
if (err != null) {
return err;
}
}
return null;
}
/**
* Checks a single value for a "missing value" error.
*
* @param value Value to check
*
* @return A descriptive String of the error or null if there was none
*/
protected String valueErrorFor(V value) {
return value != null || defaultHasNullValue() ? null : "missing value";
}
private boolean defaultHasNullValue() {
return defaultValue == null || defaultValue.contains(null);
}
/**
* Returns a string representation of the default value.
*
* @return A string representation of the default value.
*/
@Override
protected String defaultAsString() {
return asDelimitedString(defaultValue(), multiValueDelimiter());
}
private String asDelimitedString(List<V> values, char delimiter) {
if (values == null) {
return "";
}
StringBuilder sb = new StringBuilder();
for (V value : values) {
sb.append(asString(value)).append(delimiter);
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
public List<V> defaultValue() {
return defaultValue;
}
@Override
public char multiValueDelimiter() {
return multiValueDelimiter;
}
/**
* Returns a string representation of the value, even if it's null.
*
* @param value The value to describe
*
* @return A string representation of the value
*/
protected String asString(V value) {
return value == null ? "" : value.toString();
}
@Override
public final String asDelimitedString(List<V> values) {
return asDelimitedString(values, multiValueDelimiter());
}
@Override
public List<V> valueFrom(String valueString) throws IllegalArgumentException {
if (StringUtils.isBlank(valueString)) {
return Collections.emptyList();
}
return ValueParserConstants.parseListWithEscapes(valueString, multiValueDelimiter(), this::createFrom);
}
/**
* Parse a string and returns an instance of a single value (not a list).
*
* @param toParse String to parse
*
* @return An instance of a value
*/
protected abstract V createFrom(String toParse);
@Override
protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) {
super.addAttributesTo(attributes);
attributes.put(PropertyDescriptorField.DELIMITER, Character.toString(multiValueDelimiter()));
}
}
| 5,553 | 26.49505 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertySource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
import java.util.Map;
/**
* Entity that manages a list of properties. Properties are described by
* {@linkplain PropertyDescriptor property descriptors}. A property source
* maintains a mapping of property descriptors to property values. The value
* of a property can be set by {@link #setProperty(PropertyDescriptor, Object)}.
* If the property wasn't set with this method, then the property is assumed
* to take a default value, which is specified by {@linkplain PropertyDescriptor#defaultValue() the property descriptor}.
*
* <p>Bad configuration of the properties may be reported by {@link #dysfunctionReason()}.
*
* <p>Notable instances of this interface are {@linkplain net.sourceforge.pmd.Rule rules} and
* {@linkplain net.sourceforge.pmd.renderers.Renderer renderers}.
*
* @author Brian Remedios
*/
public interface PropertySource {
/**
* Defines a new property. Properties must be defined before they can be set a value.
*
* @param propertyDescriptor The property descriptor.
*
* @throws IllegalArgumentException If there is already a property defined the same name.
*/
void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) throws IllegalArgumentException;
/**
* Gets the name of this property source. This is e.g. the name
* of the rule or renderer.
*
* @return The name
*/
String getName();
/**
* Get the PropertyDescriptor for the given property name.
*
* @param name The name of the property.
*
* @return The PropertyDescriptor for the named property, <code>null</code> if there is no such property defined.
*/
PropertyDescriptor<?> getPropertyDescriptor(String name);
/**
* Get the descriptors of all defined properties.
* The properties are returned sorted by UI order.
*
* @return The PropertyDescriptors in UI order.
*/
List<PropertyDescriptor<?>> getPropertyDescriptors();
/**
* Returns a modifiable list of the property descriptors
* that don't use default values.
*
* @return The descriptors that don't use default values
*/
List<PropertyDescriptor<?>> getOverriddenPropertyDescriptors();
/**
* Get the typed value for the given property.
* Multi valued properties return immutable lists.
*
* @param <T> The underlying type of the property descriptor.
* @param propertyDescriptor The property descriptor.
*
* @return The property value.
*/
<T> T getProperty(PropertyDescriptor<T> propertyDescriptor);
/**
* Returns true if the given property has been set to a value
* somewhere in the XML.
*
* @param propertyDescriptor The descriptor
*
* @return True if the property has been set
*/
boolean isPropertyOverridden(PropertyDescriptor<?> propertyDescriptor);
/**
* Set the property value specified. This is also referred to as "overriding"
* the (default) value of a property.
*
* @param <T> The underlying type of the property descriptor.
* @param propertyDescriptor The property descriptor.
* @param value The value to set.
*/
<T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value);
/**
* Sets the value of a multi value property descriptor with a variable number of arguments.
* This is also referred to as "overriding" the (default) value of a property.
*
* @param propertyDescriptor The property descriptor for which to add a value
* @param values Values
* @param <V> The type of the values
*
* @deprecated {@link MultiValuePropertyDescriptor} is deprecated
*/
@Deprecated
<V> void setProperty(MultiValuePropertyDescriptor<V> propertyDescriptor, V... values);
/**
* Returns an unmodifiable map of descriptors to property values
* for the current receiver. The returned map has an entry for
* every defined descriptor ({@link #getPropertyDescriptors()}),
* if they were not specified explicitly, then default values are
* used.
*
* @return An unmodifiable map of descriptors to property values
*/
Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor();
/**
* Returns a modifiable map of the property descriptors
* that don't use default values, to their overridden value.
* Modifications on the returned map don't affect this property
* source.
*
* @return The descriptors that don't use default values
*/
Map<PropertyDescriptor<?>, Object> getOverriddenPropertiesByPropertyDescriptor();
/**
* Returns whether the specified property is defined on this property source,
* in which case it can be set or retrieved with {@link #getProperty(PropertyDescriptor)}
* and {@link #setProperty(PropertyDescriptor, Object)}.
*
* @param descriptor The descriptor to look for
*
* @return {@code true} if the descriptor is defined, {@code false} otherwise.
*/
boolean hasDescriptor(PropertyDescriptor<?> descriptor);
/**
* Returns a description of why the receiver may be dysfunctional.
* Usually due to missing property values or some kind of conflict
* between values. Returns null if the receiver is ok.
*
* @return String
*/
String dysfunctionReason();
}
| 5,622 | 33.078788 | 121 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/SingleValuePropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
/**
* Specializes property descriptors for single valued descriptors. For this type of property, the return value of the
* {@link #type()} method must be the class literal of the type parameter of the interface {@link PropertyDescriptor}.
*
* @param <T> The type of value this descriptor works with. Cannot be a list.
*
* @author Clément Fournier
* @since 6.0.0
*
* @deprecated The hard divide between multi- and single-value properties will be removed with 7.0.0
*/
@Deprecated
public interface SingleValuePropertyDescriptor<T> extends PropertyDescriptor<T> {
@Override
@Deprecated
Class<T> type();
}
| 755 | 29.24 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/GenericPropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Set;
import net.sourceforge.pmd.properties.constraints.PropertyConstraint;
/**
* Bound to be the single implementation for PropertyDescriptor in 7.0.0.
*
* @author Clément Fournier
* @since 6.10.0
*/
final class GenericPropertyDescriptor<T> extends AbstractSingleValueProperty<T> {
private final ValueParser<T> parser;
private final Class<T> type;
private final Set<PropertyConstraint<? super T>> constraints;
GenericPropertyDescriptor(String name,
String description,
float uiOrder,
T defaultValue,
Set<PropertyConstraint<? super T>> constraints,
ValueParser<T> parser,
boolean isDefinedExternally,
Class<T> type) {
super(name, description, defaultValue, uiOrder, isDefinedExternally);
this.constraints = constraints;
this.parser = parser;
this.type = type;
String dftValueError = errorFor(defaultValue);
if (dftValueError != null) {
throw new IllegalArgumentException(dftValueError);
}
}
@Override
public String errorFor(T value) {
for (PropertyConstraint<? super T> validator : constraints) {
String error = validator.validate(value);
if (error != null) {
return error;
}
}
return null;
}
@Override
public Class<T> type() {
return type;
}
@Override
protected T createFrom(String toParse) {
return parser.valueOf(toParse);
}
}
| 1,823 | 24.690141 | 81 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/FileProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.io.File;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SinglePackagedPropertyBuilder;
/**
* Property taking a File object as its value.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Will be removed with 7.0.0 with no scheduled replacement
*/
@Deprecated
public final class FileProperty extends AbstractSingleValueProperty<File> {
/**
* Constructor for file property.
*
* @param theName Name of the property
* @param theDescription Description
* @param theDefault Default value
* @param theUIOrder UI order
*/
public FileProperty(String theName, String theDescription, File theDefault, float theUIOrder) {
super(theName, theDescription, theDefault, theUIOrder, false);
}
/** Master constructor. */
private FileProperty(String theName, String theDescription, File theDefault, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally);
}
@Override
public Class<File> type() {
return File.class;
}
@Override
public File createFrom(String propertyString) {
return StringUtils.isBlank(propertyString) ? null : new File(propertyString);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue<File, FilePBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue<File, FilePBuilder>(File.class, ValueParserConstants.FILE_PARSER) {
@Override
protected FilePBuilder newBuilder(String name) {
return new FilePBuilder(name);
}
};
}
public static FilePBuilder named(String name) {
return new FilePBuilder(name);
}
public static final class FilePBuilder extends SinglePackagedPropertyBuilder<File, FilePBuilder> {
private FilePBuilder(String name) {
super(name);
}
@Override
public FileProperty build() {
return new FileProperty(name, description, defaultValue, uiOrder, isDefinedInXML);
}
}
}
| 2,422 | 27.174419 | 141 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractMultiNumericProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.properties.modules.NumericPropertyModule;
/**
* Base class for multi-valued numeric properties.
*
* @param <T> The type of number
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
*/
@Deprecated
/* default */ abstract class AbstractMultiNumericProperty<T extends Number> extends AbstractMultiValueProperty<T>
implements NumericPropertyDescriptor<List<T>> {
private final NumericPropertyModule<T> module;
/**
* Constructor for a multi-valued numeric property using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param lower Minimum value of the property
* @param upper Maximum value of the property
* @param theDefault List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if lower > upper, or one of them is null, or one of the defaults is not between
* the bounds
*/
AbstractMultiNumericProperty(String theName, String theDescription, T lower, T upper, List<T> theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally);
module = new NumericPropertyModule<>(lower, upper);
for (T num : theDefault) {
module.checkNumber(num);
}
}
@Override
protected String valueErrorFor(T value) {
return module.valueErrorFor(value);
}
@Override
public Number lowerLimit() {
return module.getLowerLimit();
}
@Override
public Number upperLimit() {
return module.getUpperLimit();
}
@Override
protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) {
super.addAttributesTo(attributes);
module.addAttributesTo(attributes);
}
}
| 2,155 | 26.641026 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Map;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSetWriter;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* Property value descriptor that defines the use & requirements for setting property values for use within PMD and
* any associated GUIs. While concrete descriptor instances are static and immutable they provide validation,
* serialization, and default values for any specific datatypes.
*
* <h1>Upcoming API changes to the properties framework</h1>
* see <a href="https://github.com/pmd/pmd/issues/1432">pmd/pmd#1432</a>
*
* @param <T> type of the property's value. This is a list type for multi-valued properties.
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
*/
public interface PropertyDescriptor<T> extends Comparable<PropertyDescriptor<?>> {
/**
* The name of the property without spaces as it serves as the key into the property map.
*
* @return String
*/
String name();
/**
* Describes the property and the role it plays within the rule it is specified for. Could be used in a tooltip.
*
* @return String
*/
String description();
/**
* Default value to use when the user hasn't specified one or when they wish to revert to a known-good state.
*
* @return Object
*/
T defaultValue();
/**
* Validation function that returns a diagnostic error message for a sample property value. Returns null if the
* value is acceptable.
*
* @param value The value to check.
*
* @return A diagnostic message.
*
* @deprecated PMD 7.0.0 will change the return type to {@code Optional<String>}
*/
@Deprecated
String errorFor(T value); // TODO Java 1.8 make optional
/**
* Denotes the value datatype. For multi value properties, this is not the List class but the list's component
* class.
*
* @return Class literal of the value type
*
* @deprecated This method is mainly used for documentation, but will not prove general enough
* to support PMD 7.0.0's improved property types.
*/
@Deprecated
Class<?> type();
/**
* Returns whether the property is multi-valued, i.e. an array of strings,
*
* <p>As unary property rule properties will return a value of one, you must use the get/setProperty accessors when
* working with the actual values. When working with multi-value properties then the get/setProperties accessors
* must be used.</p>
*
* @return boolean
*
* @deprecated The hard divide between multi- and single-value properties will be removed with 7.0.0
*/
@Deprecated
boolean isMultiValue();
/**
* Denotes the relative order the property field should occupy if we are using an auto-generated UI to display and
* edit property values. If the value returned has a non-zero fractional part then this is can be used to place
* adjacent fields on the same row.
*
* @return The relative order compared to other properties of the same rule
*
* @deprecated This method confuses the presentation layer and the business logic. The order of the
* property in a UI is irrelevant to the functioning of the property in PMD. With PMD 7.0.0, this
* method will be removed. UI and documentation tools will decide on their own convention.
*/
@Deprecated
float uiOrder();
/**
* @deprecated Comparing property descriptors is not useful within PMD
*/
@Deprecated
@Override
int compareTo(PropertyDescriptor<?> o);
/**
* Returns the value represented by this string.
*
* @param propertyString The string to parse
*
* @return The value represented by the string
*
* @throws IllegalArgumentException if the given string cannot be parsed
* @deprecated PMD 7.0.0 will use a more powerful scheme to represent values than
* simple strings, this method won't be general enough
*/
@Deprecated
T valueFrom(String propertyString) throws IllegalArgumentException;
/**
* Formats the object onto a string suitable for storage within the property map.
*
* @param value Object
*
* @return String
*
* @deprecated PMD 7.0.0 will use a more powerful scheme to represent values than
* simple strings, this method won't be general enough
*/
@Deprecated
String asDelimitedString(T value);
/**
* A convenience method that returns an error string if the rule holds onto a property value that has a problem.
* Returns null otherwise.
*
* @param rule Rule
*
* @return String
*
* @deprecated Used nowhere, and fails if the rule doesn't define the property descriptor
* A better solution will be added on property source
*/
@Deprecated
String propertyErrorFor(Rule rule);
/**
* If the datatype is a String then return the preferred number of rows to allocate in the text widget, returns a
* value of one for all other types. Useful for multi-line XPATH editors.
*
* @deprecated Was never implemented, and is none of the descriptor's concern. Will be removed with 7.0.0
* @return int
*/
@Deprecated
int preferredRowCount();
/**
* Returns a map representing all the property attributes of the receiver in string form.
*
* @deprecated Will be removed with 7.0.0
* @return map
*/
@Deprecated
Map<PropertyDescriptorField, String> attributeValuesById();
/**
* True if this descriptor was defined in the ruleset xml. This precision is necessary for the {@link RuleSetWriter}
* to write out the property correctly: if it was defined externally, then its definition must be written out,
* otherwise only its value.
*
* @deprecated May be removed with 7.0.0
* @return True if the descriptor was defined in xml
*/
@Deprecated
@InternalApi
boolean isDefinedExternally();
}
| 6,238 | 30.670051 | 120 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractPropertySource.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Base class for {@link PropertySource}.
*
* @author Brian Remedios
*/
public abstract class AbstractPropertySource implements PropertySource {
// setProperty should probably be hidden from Rule implementations, they have no business using that
// The apex rules that do that could be refactored to do it in the XML
// TODO RuleReference should extend this class
// This would avoid duplicating the implementation between Rule and RuleReference,
// which should use exactly the same mechanism to override properties (XML).
// BUT to do that RuleReference should not extend AbstractDelegateRule
// Indeed, AbstractDelegateRule has no business having this overriding logic built-in,
// it would break its contract. For all deeds and purposes that class should be removed.
// TODO 7.0.0 these fields should be made private final
/**
* The list of known properties that can be configured.
*
* @deprecated Will be made private final
*/
@Deprecated
protected List<PropertyDescriptor<?>> propertyDescriptors = new ArrayList<>();
/**
* The values for each property that were overridden here.
* Default property values are not contained in this map.
* In other words, if this map doesn't contain a descriptor
* which is in {@link #propertyDescriptors}, then it's assumed
* to have a default value.
*
* @deprecated Will be made private final
*/
@Deprecated
protected Map<PropertyDescriptor<?>, Object> propertyValuesByDescriptor = new HashMap<>();
/**
* Creates a copied list of the property descriptors and returns it.
*
* @return a copy of the property descriptors.
* @deprecated Just use {@link #getPropertyDescriptors()}
*/
@Deprecated
protected List<PropertyDescriptor<?>> copyPropertyDescriptors() {
return new ArrayList<>(propertyDescriptors);
}
/**
* Creates a copied map of the values of the properties and returns it.
*
* @return a copy of the values
*
* @deprecated Just use {@link #getPropertiesByPropertyDescriptor()} or {@link #getOverriddenPropertiesByPropertyDescriptor()}
*/
@Deprecated
protected Map<PropertyDescriptor<?>, Object> copyPropertyValues() {
return new HashMap<>(propertyValuesByDescriptor);
}
@Override
public void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) {
// Check to ensure the property does not already exist.
if (getPropertyDescriptor(propertyDescriptor.name()) != null) {
throw new IllegalArgumentException("There is already a PropertyDescriptor with name '"
+ propertyDescriptor.name() + "' defined on " + getPropertySourceType() + " " + getName() + ".");
}
propertyDescriptors.add(propertyDescriptor);
// Sort in UI order
Collections.sort(propertyDescriptors);
}
protected abstract String getPropertySourceType();
@Override
public PropertyDescriptor<?> getPropertyDescriptor(String name) {
for (PropertyDescriptor<?> propertyDescriptor : propertyDescriptors) {
if (name.equals(propertyDescriptor.name())) {
return propertyDescriptor;
}
}
return null;
}
@Override
public boolean hasDescriptor(PropertyDescriptor<?> descriptor) {
return propertyDescriptors.contains(descriptor);
}
@Override
public final List<PropertyDescriptor<?>> getOverriddenPropertyDescriptors() {
return new ArrayList<>(propertyValuesByDescriptor.keySet());
}
@Override
public List<PropertyDescriptor<?>> getPropertyDescriptors() {
return Collections.unmodifiableList(propertyDescriptors);
}
@Override
public <T> T getProperty(PropertyDescriptor<T> propertyDescriptor) {
checkValidPropertyDescriptor(propertyDescriptor);
T result = propertyDescriptor.defaultValue();
if (propertyValuesByDescriptor.containsKey(propertyDescriptor)) {
@SuppressWarnings("unchecked")
T value = (T) propertyValuesByDescriptor.get(propertyDescriptor);
result = value;
}
return result;
}
@Override
public boolean isPropertyOverridden(PropertyDescriptor<?> propertyDescriptor) {
return propertyValuesByDescriptor.containsKey(propertyDescriptor);
}
@Override
public <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value) {
checkValidPropertyDescriptor(propertyDescriptor);
if (value instanceof List) {
propertyValuesByDescriptor.put(propertyDescriptor, Collections.unmodifiableList((List) value));
} else {
propertyValuesByDescriptor.put(propertyDescriptor, value);
}
}
@Override
@Deprecated
public <V> void setProperty(MultiValuePropertyDescriptor<V> propertyDescriptor, V... values) {
checkValidPropertyDescriptor(propertyDescriptor);
propertyValuesByDescriptor.put(propertyDescriptor, Collections.unmodifiableList(Arrays.asList(values)));
}
/**
* Checks whether this property descriptor is defined for this property source.
*
* @param propertyDescriptor The property descriptor to check
*/
private void checkValidPropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) {
if (!hasDescriptor(propertyDescriptor)) {
throw new IllegalArgumentException("Property descriptor not defined for " + getPropertySourceType() + " " + getName() + ": " + propertyDescriptor);
}
}
@Override
public final Map<PropertyDescriptor<?>, Object> getOverriddenPropertiesByPropertyDescriptor() {
return new HashMap<>(propertyValuesByDescriptor);
}
@Override
public Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor() {
if (propertyDescriptors.isEmpty()) {
return Collections.emptyMap();
}
Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor = new HashMap<>(propertyDescriptors.size());
// Fill with existing explicitly values
propertiesByPropertyDescriptor.putAll(this.propertyValuesByDescriptor);
// Add default values for anything not yet set
for (PropertyDescriptor<?> propertyDescriptor : this.propertyDescriptors) {
if (!propertiesByPropertyDescriptor.containsKey(propertyDescriptor)) {
propertiesByPropertyDescriptor.put(propertyDescriptor, propertyDescriptor.defaultValue());
}
}
return Collections.unmodifiableMap(propertiesByPropertyDescriptor);
}
// todo Java 8 move up to interface
@Override
public String dysfunctionReason() {
for (PropertyDescriptor<?> descriptor : getOverriddenPropertyDescriptors()) {
String error = errorForPropCapture(descriptor);
if (error != null) {
return error;
}
}
return null;
}
private <T> String errorForPropCapture(PropertyDescriptor<T> descriptor) {
return descriptor.errorFor(getProperty(descriptor));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractPropertySource that = (AbstractPropertySource) o;
if (!Objects.equals(propertyDescriptors, that.propertyDescriptors)) {
return false;
}
// Convert the values to strings for comparisons. This is needed at least for RegexProperties,
// as java.util.regex.Pattern doesn't implement equals().
Map<String, String> propertiesWithValues = new HashMap<>();
propertyDescriptors.forEach(propertyDescriptor -> {
Object value = propertyValuesByDescriptor.getOrDefault(propertyDescriptor, propertyDescriptor.defaultValue());
@SuppressWarnings({"unchecked", "rawtypes"})
String valueString = ((PropertyDescriptor) propertyDescriptor).asDelimitedString(value);
propertiesWithValues.put(propertyDescriptor.name(), valueString);
});
Map<String, String> thatPropertiesWithValues = new HashMap<>();
that.propertyDescriptors.forEach(propertyDescriptor -> {
Object value = that.propertyValuesByDescriptor.getOrDefault(propertyDescriptor, propertyDescriptor.defaultValue());
@SuppressWarnings({"unchecked", "rawtypes"})
String valueString = ((PropertyDescriptor) propertyDescriptor).asDelimitedString(value);
thatPropertiesWithValues.put(propertyDescriptor.name(), valueString);
});
return Objects.equals(propertiesWithValues, thatPropertiesWithValues);
}
@Override
public int hashCode() {
return Objects.hash(propertyDescriptors, propertyValuesByDescriptor);
}
}
| 9,352 | 35.111969 | 159 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractSingleValueProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import net.sourceforge.pmd.Rule;
/**
* Single value property.
*
* @param <T> The type of the value.
*
* @author Clément Fournier
*/
@Deprecated
/* default */ abstract class AbstractSingleValueProperty<T> extends AbstractProperty<T>
implements SingleValuePropertyDescriptor<T> {
/** Default value. */
private T defaultValue;
/**
* Creates a single value property.
*
* @param theName Name of the property
* @param theDescription Description
* @param theUIOrder UI order
* @param theDefault Default value
* @param isDefinedExternally Whether the property is defined in the XML (by a XPath rule) or not
*
* @throws IllegalArgumentException If name or description are empty, or UI order is negative.
*/
protected AbstractSingleValueProperty(String theName, String theDescription, T theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theUIOrder, isDefinedExternally);
defaultValue = theDefault;
}
@Override
public final T defaultValue() {
return defaultValue;
}
@Override
public final boolean isMultiValue() {
return false;
}
@Override
public String asDelimitedString(T value) {
return asString(value);
}
/**
* Returns a string representation of the value, even if it's null.
*
* @param value The value to describe
*
* @return A string representation of the value
*/
protected String asString(T value) {
return value == null ? "" : value.toString();
}
@Override
public String propertyErrorFor(Rule rule) {
T realValue = rule.getProperty(this);
return realValue == null ? null : errorFor(realValue);
}
@Override
public String errorFor(T value) {
String typeError = typeErrorFor(value);
if (typeError != null) {
return typeError;
}
return valueErrorFor(value);
}
private String typeErrorFor(T value) {
if (value != null && !type().isAssignableFrom(value.getClass())) {
return value + " is not an instance of " + type();
}
return null;
}
/**
* Checks the value for an error.
*
* @param value Value to check
*
* @return A diagnostic error message, or null if there's no problem
*/
protected String valueErrorFor(T value) {
return value != null || defaultHasNullValue() ? null : "missing value";
}
/**
* Returns true if the default value is {@code null}.
*
* @return True if the default value is {@code null}.
*/
private boolean defaultHasNullValue() {
return defaultValue == null;
}
@Override
protected final String defaultAsString() {
return asString(defaultValue);
}
@Override
public final T valueFrom(String valueString) throws IllegalArgumentException {
return createFrom(valueString);
}
/**
* Parse a string and returns an instance of a value.
*
* @param toParse String to parse
*
* @return An instance of a value
*/
protected abstract T createFrom(String toParse); // this is there to be symmetrical to multi values
}
| 3,503 | 23.333333 | 106 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.DEFAULT_VALUE;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.DESCRIPTION;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.NAME;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
/**
* Abstract class for properties.
*
* @param <T> The type of the property's value. This is a list type for multi-valued properties
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
*/
// @Deprecated // will be replaced by another base class in the next PR
/* default */ abstract class AbstractProperty<T> implements PropertyDescriptor<T> {
private final String name;
private final String description;
private final float uiOrder;
private final boolean isDefinedExternally;
/**
* Constructor for an abstract property.
*
* @param theName Name of the property
* @param theDescription Description
* @param theUIOrder UI order
*
* @throws IllegalArgumentException If name or description are empty, or UI order is negative.
*/
protected AbstractProperty(String theName, String theDescription, float theUIOrder, boolean isDefinedExternally) {
if (theUIOrder < 0) {
throw new IllegalArgumentException("Property attribute 'UI order' cannot be null or blank");
}
name = checkNotEmpty(theName, NAME);
description = checkNotEmpty(theDescription, DESCRIPTION);
uiOrder = theUIOrder;
this.isDefinedExternally = isDefinedExternally;
}
@Override
public String description() {
return description;
}
@Override
public float uiOrder() {
return uiOrder;
}
@Override
public final int compareTo(PropertyDescriptor<?> otherProperty) {
float otherOrder = otherProperty.uiOrder();
return (int) (otherOrder - uiOrder);
}
@Override
public int preferredRowCount() {
return 1;
}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof PropertyDescriptor
&& name.equals(((PropertyDescriptor<?>) obj).name());
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "[PropertyDescriptor: name=" + name() + ','
+ " type=" + (isMultiValue() ? "List<" + type() + '>' : type()) + ','
+ " value=" + defaultValue() + ']';
}
@Override
public String name() {
return name;
}
@Override
public final Map<PropertyDescriptorField, String> attributeValuesById() {
Map<PropertyDescriptorField, String> values = new HashMap<>();
addAttributesTo(values);
return values;
}
/**
* Adds this property's attributes to the map. Subclasses can override this to add more {@link
* PropertyDescriptorField}.
*
* @param attributes The map to fill
*/
protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) {
attributes.put(NAME, name);
attributes.put(DESCRIPTION, description);
attributes.put(DEFAULT_VALUE, defaultAsString());
}
/**
* Returns a string representation of the default value.
*
* @return A string representation of the default value.
*/
protected abstract String defaultAsString();
@Override
public boolean isDefinedExternally() {
return isDefinedExternally;
}
private static String checkNotEmpty(String arg, PropertyDescriptorField argId) throws IllegalArgumentException {
if (StringUtils.isBlank(arg)) {
throw new IllegalArgumentException("Property attribute '" + argId + "' cannot be null or blank");
}
return arg;
}
}
| 4,070 | 25.782895 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/MultiValuePropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.List;
/**
* Specializes property descriptors for multi valued descriptors. For this type of property, the return value of the
* {@link #type()} method must be the class literal of the type parameter of this interface, which is the type of the
* components of the list (not the type of the list). Notice that for implementors, the type parameter of this interface
* is <i>not</i> the same as the type parameter of {@link PropertyDescriptor} they inherit!
*
* @param <V> The type of value this descriptor works with. This is the type of the list's component.
*
* @author Clément Fournier
* @since 6.0.0
*
* @deprecated The hard divide between multi- and single-value properties will be removed with 7.0.0
*/
@Deprecated
public interface MultiValuePropertyDescriptor<V> extends PropertyDescriptor<List<V>> {
/** Default delimiter for multi-valued properties other than numeric ones. */
@Deprecated
char DEFAULT_DELIMITER = '|';
/** Default delimiter for numeric multi-valued properties. */
@Deprecated
char DEFAULT_NUMERIC_DELIMITER = ',';
/**
* Return the character being used to delimit multiple property values within a single string. You must ensure that
* this character does not appear within any rule property values to avoid deserialization errors.
*
* @return char
*/
@Deprecated
char multiValueDelimiter();
@Override
@Deprecated
Class<V> type();
}
| 1,595 | 31.571429 | 120 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/EnumeratedProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Map;
import net.sourceforge.pmd.properties.builders.SingleValuePropertyBuilder;
import net.sourceforge.pmd.properties.modules.EnumeratedPropertyModule;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Property which can take only a fixed set of values of any type, then selected via String labels. The mappings method
* returns the set of mappings between the labels and their values.
*
* <p>This property currently doesn't support serialization and cannot be defined in a ruleset file.z </p>
*
* @param <E> Type of the values
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<E>} instead. A builder is available from {@link PropertyFactory#enumProperty(String, Map)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class EnumeratedProperty<E> extends AbstractSingleValueProperty<E>
implements EnumeratedPropertyDescriptor<E, E> {
private final EnumeratedPropertyModule<E> module;
/**
* Constructor using arrays to define the label-value mappings. The correct construction of the property depends on
* the correct ordering of the arrays.
*
* @param theName Name
* @param theDescription Description
* @param theLabels Labels of the choices
* @param theChoices Values that can be chosen
* @param defaultIndex The index of the default value
* @param valueType Type of the values
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#enumProperty(String, Map)}
*/
@Deprecated
public EnumeratedProperty(String theName, String theDescription, String[] theLabels, E[] theChoices,
int defaultIndex, Class<E> valueType, float theUIOrder) {
this(theName, theDescription, CollectionUtil.mapFrom(theLabels, theChoices),
theChoices[defaultIndex], valueType, theUIOrder, false);
}
/**
* Constructor using arrays to define the label-value mappings. The correct construction of the property depends on
* the correct ordering of the arrays.
*
* @param theName Name
* @param theDescription Description
* @param theLabels Labels of the choices
* @param theChoices Values that can be chosen
* @param defaultIndex Index of the default value
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#enumProperty(String, Map)}
*/
@Deprecated
public EnumeratedProperty(String theName, String theDescription, String[] theLabels, E[] theChoices,
int defaultIndex, float theUIOrder) {
this(theName, theDescription, CollectionUtil.mapFrom(theLabels, theChoices),
theChoices[defaultIndex], null, theUIOrder, false);
}
/**
* Constructor using a map to define the label-value mappings.
*
* @param theName Name
* @param theDescription Description
* @param labelsToChoices Map of labels to values
* @param defaultValue Default value
* @param valueType Type of the values
* @param theUIOrder UI order
* @deprecated Use {@link PropertyFactory#enumProperty(String, Map)}
*/
@Deprecated
public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices,
E defaultValue, Class<E> valueType, float theUIOrder) {
this(theName, theDescription, labelsToChoices, defaultValue, valueType, theUIOrder, false);
}
/** Master constructor. */
private EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices,
E defaultValue, Class<E> valueType, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, defaultValue, theUIOrder, isDefinedExternally);
module = new EnumeratedPropertyModule<>(labelsToChoices, valueType);
module.checkValue(defaultValue);
}
@Override
public Class<E> type() {
return module.getValueType();
}
@Override
public String errorFor(E value) {
return module.errorFor(value);
}
@Override
public E createFrom(String value) throws IllegalArgumentException {
return module.choiceFrom(value);
}
@Override
public String asString(E value) {
return module.getLabelsByChoice().get(value);
}
@Override
public Map<String, E> mappings() {
return module.getChoicesByLabel(); // unmodifiable
}
/**
* @deprecated Use {@link PropertyFactory#enumProperty(String, Map)}
*/
@Deprecated
public static <E> EnumPBuilder<E> named(String name) {
return new EnumPBuilder<>(name);
}
/**
* @deprecated Use {@link PropertyFactory#enumProperty(String, Map)}
*/
@Deprecated
public static final class EnumPBuilder<E> extends SingleValuePropertyBuilder<E, EnumPBuilder<E>> {
private Class<E> valueType;
private Map<String, E> mappings;
private EnumPBuilder(String name) {
super(name);
}
public EnumPBuilder<E> type(Class<E> type) {
this.valueType = type;
return this;
}
public EnumPBuilder<E> mappings(Map<String, E> map) {
this.mappings = map;
return this;
}
@Override
public EnumeratedProperty<E> build() {
return new EnumeratedProperty<>(this.name, this.description, mappings, this.defaultValue, valueType, this.uiOrder, isDefinedInXML);
}
}
}
| 5,866 | 32.335227 | 143 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder;
import net.sourceforge.pmd.properties.constraints.PropertyConstraint;
// @formatter:off
/**
* Base class for generic property builders.
* Property builders are obtained from the {@link PropertyFactory},
* and are used to build {@link PropertyDescriptor}s.
*
* <p>All properties <i>must</i> specify the following attributes to build
* properly:
* <ul>
* <li>A name: filled-in when obtaining the builder
* <li>A description: see {@link #desc(String)}
* <li>A default value: see {@link #defaultValue(Object)}
* </ul>
*
* <p>The {@link PropertyDescriptor} may be built after those required steps by
* calling {@link #build()}.
*
* <p>A property builder may throw {@link IllegalArgumentException} at any
* stage during the build process to indicate invalid input. It usually tries
* to do so as early as possible, rather than waiting for the call to {@link #build()}.
*
* <p>Note: from 7.0.0 on, all property builders will
* extend this class instead of {@link PropertyDescriptorBuilder}.
*
* @param <B> Concrete type of this builder instance
* @param <T> Type of values the property handles
*
* @author Clément Fournier
* @since 6.10.0
*/
// @formatter:on
public abstract class PropertyBuilder<B extends PropertyBuilder<B, T>, T> {
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][\\w-]*");
private final Set<PropertyConstraint<? super T>> validators = new LinkedHashSet<>();
protected boolean isDefinedExternally;
private String name;
private String description;
private T defaultValue;
PropertyBuilder(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Name must be provided");
} else if (!NAME_PATTERN.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid name '" + name + "'");
}
this.name = name;
}
void setDefinedExternally(boolean bool) {
this.isDefinedExternally = bool;
}
Set<PropertyConstraint<? super T>> getConstraints() {
return validators;
}
String getDescription() {
if (StringUtils.isBlank(description)) {
throw new IllegalArgumentException("Description must be provided");
}
return description;
}
/** Returns the value, asserting it has been set. */
T getDefaultValue() {
if (!isDefaultValueSet()) {
throw new IllegalArgumentException("A default value must be provided");
}
return defaultValue;
}
boolean isDefaultValueSet() {
return defaultValue != null;
}
/**
* Specify the description of the property. This is used for documentation.
* Please describe precisely how the property may change the behaviour of the
* rule. Providing complete information should be preferred over being concise.
*
* <p>Calling this method is required for {@link #build()} to succeed.
*
* @param desc The description
*
* @return The same builder
*
* @throws IllegalArgumentException If the description is null or whitespace
*/
@SuppressWarnings("unchecked")
public B desc(String desc) {
if (StringUtils.isBlank(desc)) {
throw new IllegalArgumentException("Description must be provided");
}
this.description = desc;
return (B) this;
}
// TODO 7.0.0 document the following:
//
// * <p>Constraints should be independent from each other, and should
// * perform no side effects. PMD doesn't specify how many times a
// * constraint predicate will be executed, or in what order.
//
// This is superfluous right now bc users may not create their own constraints
/**
* Add a constraint on the values that this property may take.
* The validity of values will be checked when parsing the XML,
* and invalid values will be reported. A rule will never be run
* if some of its properties violate some constraints.
*
* @param constraint The constraint
*
* @return The same builder
*
* @see net.sourceforge.pmd.properties.constraints.NumericConstraints
*/
@SuppressWarnings("unchecked")
public B require(PropertyConstraint<? super T> constraint) {
validators.add(constraint);
return (B) this;
}
/**
* Specify a default value. Some subclasses provide convenient
* related methods, see e.g. {@link GenericCollectionPropertyBuilder#defaultValues(Object, Object[])}.
* Using the null value is prohibited.
*
* <p>Calling this method is required for {@link #build()} to succeed.
*
* @param val Default value
*
* @return The same builder
*
* @throws IllegalArgumentException If the argument is null
*/
@SuppressWarnings("unchecked")
public B defaultValue(T val) {
if (val == null) {
throw new IllegalArgumentException("Property values may not be null.");
}
this.defaultValue = val;
return (B) this;
}
/**
* Builds the descriptor and returns it.
*
* @return The built descriptor
*
* @throws IllegalArgumentException if the description or default value were not provided, or if the default value doesn't satisfy the given constraints
*/
public abstract PropertyDescriptor<T> build();
/**
* Returns the name of the property to be built.
*/
public String getName() {
return name;
}
// Technically this may very well be merged into PropertyBuilder
// We'd have all properties (even collection properties) enjoy a ValueParser,
// which means they could be parsed in a <value> tag (collections would use delimiters) if they opt in.
// The delimiters wouldn't be configurable (we'd take our current defaults). If they could ambiguous
// then the <seq> syntax should be the only one available.
// This would allow specifying eg lists of numbers as <value>1,2,3</value>, for which the <seq> syntax would look clumsy
abstract static class BaseSinglePropertyBuilder<B extends PropertyBuilder<B, T>, T> extends PropertyBuilder<B, T> {
private final ValueParser<T> parser;
private final Class<T> type;
// Class is not final but a package-private constructor restricts inheritance
BaseSinglePropertyBuilder(String name, ValueParser<T> parser, Class<T> type) {
super(name);
this.parser = parser;
this.type = type;
}
protected ValueParser<T> getParser() {
return parser;
}
protected Class<T> getType() {
return type;
}
/**
* Returns a new builder that can be used to build a property
* handling lists of Ts. The validators already added are
* converted to list validators. The default value cannot have
* previously been set.
*
* @return A new list property builder
*
* @throws IllegalStateException if the default value has already been set
*/
/* package private */ GenericCollectionPropertyBuilder<T, List<T>> toList() {
Supplier<List<T>> listSupplier = new Supplier<List<T>>() {
@Override
public List<T> get() {
return new ArrayList<>();
}
};
return toCollection(listSupplier);
}
// TODO 7.0.0 this can be inlined
private <C extends Collection<T>> GenericCollectionPropertyBuilder<T, C> toCollection(Supplier<C> emptyCollSupplier) {
if (isDefaultValueSet()) {
throw new IllegalStateException("The default value is already set!");
}
GenericCollectionPropertyBuilder<T, C> result = new GenericCollectionPropertyBuilder<>(getName(),
getParser(),
emptyCollSupplier,
getType());
for (PropertyConstraint<? super T> validator : getConstraints()) {
result.require(validator.toCollectionConstraint());
}
return result;
}
@Override
public PropertyDescriptor<T> build() {
return new GenericPropertyDescriptor<>(
getName(),
getDescription(),
0f,
getDefaultValue(),
getConstraints(),
parser,
isDefinedExternally,
type
);
}
}
/**
* Generic builder for a single-value property.
*
* @param <T> Type of values the property handles
*
* @author Clément Fournier
* @since 6.10.0
*/
// Note: This type is used to fix the first type parameter for classes that don't need more API.
public static final class GenericPropertyBuilder<T> extends BaseSinglePropertyBuilder<GenericPropertyBuilder<T>, T> {
GenericPropertyBuilder(String name, ValueParser<T> parser, Class<T> type) {
super(name, parser, type);
}
}
/**
* Specialized builder for regex properties. Allows specifying the pattern as a
* string, with {@link #defaultValue(String)}.
*
* @author Clément Fournier
* @since 6.10.0
*/
public static final class RegexPropertyBuilder extends BaseSinglePropertyBuilder<RegexPropertyBuilder, Pattern> {
RegexPropertyBuilder(String name) {
super(name, ValueParserConstants.REGEX_PARSER, Pattern.class);
}
/**
* Specify a default value using a string pattern. The argument is
* compiled to a pattern using {@link Pattern#compile(String)}.
*
* @param pattern String pattern
*
* @return The same builder
*
* @throws java.util.regex.PatternSyntaxException If the argument is not a valid pattern
*/
public RegexPropertyBuilder defaultValue(String pattern) {
super.defaultValue(Pattern.compile(pattern));
return this;
}
/**
* Specify a default value using a string pattern. The argument is
* compiled to a pattern using {@link Pattern#compile(String, int)}.
*
* @param pattern String pattern
* @param flags Regex compilation flags, the same as for {@link Pattern#compile(String, int)}
*
* @return The same builder
*
* @throws java.util.regex.PatternSyntaxException If the argument is not a valid pattern
* @throws IllegalArgumentException If bit values other than those corresponding to the defined
* match flags are set in {@code flags}
*/
public RegexPropertyBuilder defaultValue(String pattern, int flags) {
super.defaultValue(Pattern.compile(pattern, flags));
return this;
}
}
/**
* Generic builder for a collection-valued property.
* This class adds methods related to {@link #defaultValue(Collection)}
* to make its use more flexible. See e.g. {@link #defaultValues(Object, Object[])}.
*
* <p>Note: this is designed to support arbitrary collections.
* Pre-7.0.0, the only collections available from the {@link PropertyFactory}
* are list types though.
*
* @param <V> Component type of the collection
* @param <C> Collection type for the property being built
*
* @author Clément Fournier
* @since 6.10.0
*/
public static final class GenericCollectionPropertyBuilder<V, C extends Collection<V>> extends PropertyBuilder<GenericCollectionPropertyBuilder<V, C>, C> {
private final ValueParser<V> parser;
private final Supplier<C> emptyCollSupplier;
private final Class<V> type;
private char multiValueDelimiter = MultiValuePropertyDescriptor.DEFAULT_DELIMITER;
/**
* Builds a new builder for a collection type. Package-private.
*/
GenericCollectionPropertyBuilder(String name,
ValueParser<V> parser,
Supplier<C> emptyCollSupplier,
Class<V> type) {
super(name);
this.parser = parser;
this.emptyCollSupplier = emptyCollSupplier;
this.type = type;
}
private C getDefaultValue(Collection<? extends V> list) {
C coll = emptyCollSupplier.get();
coll.addAll(list);
return coll;
}
/**
* Specify a default value.
*
* @param val List of values
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public GenericCollectionPropertyBuilder<V, C> defaultValue(Collection<? extends V> val) {
super.defaultValue(getDefaultValue(val));
return this;
}
/**
* Specify default values. To specify an empty
* default value, use {@link #emptyDefaultValue()}.
*
* @param head First value
* @param tail Rest of the values
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public GenericCollectionPropertyBuilder<V, C> defaultValues(V head, V... tail) {
List<V> tmp = new ArrayList<>(tail.length + 1);
tmp.add(head);
tmp.addAll(Arrays.asList(tail));
return super.defaultValue(getDefaultValue(tmp));
}
/**
* Specify that the default value is an empty collection.
*
* @return The same builder
*/
public GenericCollectionPropertyBuilder<V, C> emptyDefaultValue() {
return super.defaultValue(getDefaultValue(Collections.<V>emptyList()));
}
/**
* Require that the given constraint be fulfilled on each item of the
* value of this property. This is a convenient shorthand for
* {@code require(constraint.toCollectionConstraint())}.
*
* @param constraint Constraint to impose on the items of the collection value
*
* @return The same builder
*/
public GenericCollectionPropertyBuilder<V, C> requireEach(PropertyConstraint<? super V> constraint) {
return super.require(constraint.toCollectionConstraint());
}
/**
* Specify a delimiter character. By default it's {@link MultiValuePropertyDescriptor#DEFAULT_DELIMITER}, or {@link
* MultiValuePropertyDescriptor#DEFAULT_NUMERIC_DELIMITER} for numeric properties.
*
* @param delim Delimiter
*
* @return The same builder
*
* @deprecated PMD 7.0.0 will introduce a new XML syntax for multi-valued properties which will not rely on delimiters.
* This method is kept until this is implemented for compatibility reasons with the pre-7.0.0 framework, but
* it will be scrapped come 7.0.0.
*/
@Deprecated
public GenericCollectionPropertyBuilder<V, C> delim(char delim) {
this.multiValueDelimiter = delim;
return this;
}
@SuppressWarnings("unchecked")
@Override
public PropertyDescriptor<C> build() {
// Note: the unchecked cast is safe because pre-7.0.0,
// we only allow building property descriptors for lists.
// C is thus always List<V>, and the cast doesn't fail
// Post-7.0.0, the multi-value property classes will be removed
// and C will be the actual type parameter of the returned property
// descriptor
return (PropertyDescriptor<C>) new GenericMultiValuePropertyDescriptor<>(
getName(),
getDescription(),
0f,
getDefaultValue(),
getConstraints(),
parser,
multiValueDelimiter,
type
);
}
}
}
| 17,071 | 33.628803 | 159 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/ValueParser.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import net.sourceforge.pmd.annotation.InternalApi;
/**
* Parses a value from a string.
*
* @param <U> The type of the value to parse
*/
// FUTURE @FunctionalInterface
@Deprecated
@InternalApi
public interface ValueParser<U> {
/**
* Extracts a primitive from a string.
*
* @param value The string to parse
*
* @return The primitive found
* @throws IllegalArgumentException if the value couldn't be parsed
*/
U valueOf(String value) throws IllegalArgumentException;
}
| 647 | 19.903226 | 79 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/NumericPropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
/**
* Defines a descriptor type whose instance values are required to lie within specified upper and lower limits.
*
* @param <T> type of the property value
*
* @deprecated Will be removed with 7.0.0. In the future this interface won't exist,
* but numeric properties will still be around
* @author Brian Remedios
* @author Clément Fournier
*/
@Deprecated
public interface NumericPropertyDescriptor<T> extends PropertyDescriptor<T> {
/**
* Returns the maximum value that instances of the property can have.
*
* @return Number
*/
Number upperLimit();
/**
* Returns the minimum value that instances of the property can have.
*
* @return Number
*/
Number lowerLimit();
}
| 866 | 23.771429 | 111 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/IntegerProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.INTEGER_PARSER;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleNumericPropertyBuilder;
/**
* Defines a datatype that supports single Integer property values within an upper and lower boundary.
*
* @author Brian Remedios
*
* @deprecated Use a {@code PropertyDescriptor<Integer>} instead. A builder is available from {@link PropertyFactory#intProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class IntegerProperty extends AbstractNumericProperty<Integer> {
/**
* Constructor that limits itself to a single value within the specified limits.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param theDefault Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
*
* @deprecated Use {@link PropertyFactory#intProperty(String)}
*/
@Deprecated
public IntegerProperty(String theName, String theDescription, Integer min, Integer max, Integer theDefault,
float theUIOrder) {
this(theName, theDescription, min, max, theDefault, theUIOrder, false);
}
/** Master constructor. */
private IntegerProperty(String theName, String theDescription, Integer min, Integer max, Integer theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, theDefault, theUIOrder, isDefinedExternally);
}
@Override
public Class<Integer> type() {
return Integer.class;
}
@Override
protected Integer createFrom(String value) {
return INTEGER_PARSER.valueOf(value);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Integer, IntegerPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Integer, IntegerPBuilder>(Integer.class, ValueParserConstants.INTEGER_PARSER) {
@Override
protected IntegerPBuilder newBuilder(String name) {
return new IntegerPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#intProperty(String)}
*/
@Deprecated
public static IntegerPBuilder named(String name) {
return new IntegerPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#intProperty(String)}
*/
@Deprecated
public static final class IntegerPBuilder extends SingleNumericPropertyBuilder<Integer, IntegerPBuilder> {
private IntegerPBuilder(String name) {
super(name);
}
@Override
public IntegerProperty build() {
return new IntegerProperty(name, description, lowerLimit, upperLimit, defaultValue, uiOrder, isDefinedInXML);
}
}
}
| 3,319 | 31.871287 | 161 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/EnumeratedPropertyDescriptor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Map;
/**
* Interface defining an enumerated property descriptor.
*
* @param <E> The type of the values
* @param <T> The type of default values the descriptor can take (can be a List)
*
* @author Clément Fournier
* @since 6.0.0
* @deprecated Will be removed with 7.0.0. In the future this interface won't exist,
* but enumerated properties will still be around
*/
@Deprecated
public interface EnumeratedPropertyDescriptor<E, T> extends PropertyDescriptor<T> {
/**
* Returns an immutable map of the label - value mappings defined by this descriptor.
*
* @return an immutable map of the label - value mappings defined by this descriptor.
*/
Map<String, E> mappings();
}
| 856 | 25.78125 | 89 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/CharacterMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.builders.MultiValuePropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Multi-valued character property.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<List<Character>>}. A builder is available from {@link PropertyFactory#charListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class CharacterMultiProperty extends AbstractMultiValueProperty<Character> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues Array of defaults
* @param theUIOrder UI order
* @param delimiter The delimiter to use
*
* @throws IllegalArgumentException if the delimiter is in the default values
* @deprecated Use {@link PropertyFactory#charListProperty(String)}
*/
@Deprecated
public CharacterMultiProperty(String theName, String theDescription, Character[] defaultValues, float theUIOrder, char delimiter) {
this(theName, theDescription, Arrays.asList(defaultValues), theUIOrder, delimiter, false);
}
/** Master constructor. */
private CharacterMultiProperty(String theName, String theDescription, List<Character> defaultValues, float theUIOrder,
char delimiter, boolean isDefinedExternally) {
super(theName, theDescription, defaultValues, theUIOrder, delimiter, isDefinedExternally);
if (defaultValues != null) {
for (Character c : defaultValues) {
if (c == delimiter) {
throw new IllegalArgumentException("Cannot include the delimiter in the set of defaults");
}
}
}
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues List of defaults
* @param theUIOrder UI order
* @param delimiter The delimiter to use
*
* @throws IllegalArgumentException if the delimiter is in the default values
* @deprecated Use {@link PropertyFactory#charListProperty(String)}
*/
@Deprecated
public CharacterMultiProperty(String theName, String theDescription, List<Character> defaultValues, float theUIOrder, char delimiter) {
this(theName, theDescription, defaultValues, theUIOrder, delimiter, false);
}
@Override
protected Character createFrom(String toParse) {
return CharacterProperty.charFrom(toParse);
}
@Override
public Class<Character> type() {
return Character.class;
}
@Override
public List<Character> valueFrom(String valueString) throws IllegalArgumentException {
String[] values = StringUtils.split(valueString, multiValueDelimiter());
List<Character> chars = new ArrayList<>(values.length);
for (int i = 0; i < values.length; i++) {
chars.add(values[i].charAt(0));
}
return chars;
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue<Character, CharacterMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue<Character, CharacterMultiPBuilder>(Character.class, ValueParserConstants.CHARACTER_PARSER) {
@Override
protected CharacterMultiPBuilder newBuilder(String name) {
return new CharacterMultiPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#charListProperty(String)}
*/
@Deprecated
public static CharacterMultiPBuilder named(String name) {
return new CharacterMultiPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#charListProperty(String)}
*/
@Deprecated
public static final class CharacterMultiPBuilder extends MultiValuePropertyBuilder<Character, CharacterMultiPBuilder> {
private CharacterMultiPBuilder(String name) {
super(name);
}
@Override
public CharacterMultiProperty build() {
return new CharacterMultiProperty(this.name, this.description, this.defaultValues, this.uiOrder, multiValueDelimiter, isDefinedInXML);
}
}
}
| 4,669 | 32.120567 | 165 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/FloatMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.properties.builders.MultiNumericPropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Multi-valued float property.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<List<Double>>} instead. A builder is available from {@link PropertyFactory#doubleListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class FloatMultiProperty extends AbstractMultiNumericProperty<Float> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues Array of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated use {@link PropertyFactory#doubleListProperty(String)}
*/
@Deprecated
public FloatMultiProperty(String theName, String theDescription, Float min, Float max,
Float[] defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, Arrays.asList(defaultValues), theUIOrder, false);
}
/** Master constructor. */
private FloatMultiProperty(String theName, String theDescription, Float min, Float max,
List<Float> defaultValues, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, defaultValues, theUIOrder, isDefinedExternally);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated use {@link PropertyFactory#doubleListProperty(String)}
*/
@Deprecated
public FloatMultiProperty(String theName, String theDescription, Float min, Float max,
List<Float> defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, defaultValues, theUIOrder, false);
}
@Override
public Class<Float> type() {
return Float.class;
}
@Override
protected Float createFrom(String value) {
return Float.valueOf(value);
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Float, FloatMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Float, FloatMultiPBuilder>(Float.class, ValueParserConstants.FLOAT_PARSER) {
@Override
protected FloatMultiPBuilder newBuilder(String name) {
return new FloatMultiPBuilder(name);
}
};
}
/** @deprecated use {@link PropertyFactory#doubleListProperty(String)} */
@Deprecated
public static FloatMultiPBuilder named(String name) {
return new FloatMultiPBuilder(name);
}
/** @deprecated use {@link PropertyFactory#doubleListProperty(String)} */
@Deprecated
public static final class FloatMultiPBuilder extends MultiNumericPropertyBuilder<Float, FloatMultiPBuilder> {
private FloatMultiPBuilder(String name) {
super(name);
}
@Override
public FloatMultiProperty build() {
return new FloatMultiProperty(name, description, lowerLimit, upperLimit, defaultValues, uiOrder, isDefinedInXML);
}
}
}
| 4,081 | 33.59322 | 157 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/LongProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleNumericPropertyBuilder;
/**
* Single valued long property.
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
*
* @deprecated Use a {@code PropertyDescriptor<Long>} instead. A builder is available from {@link PropertyFactory#longIntProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class LongProperty extends AbstractNumericProperty<Long> {
/**
* Constructor for LongProperty that limits itself to a single value within the specified limits. Converts string
* arguments into the Long values.
*
* @param theName Name
* @param theDescription Description
* @param minStr Minimum value of the property
* @param maxStr Maximum value of the property
* @param defaultStr Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#longIntProperty(String)}
*/
@Deprecated
public LongProperty(String theName, String theDescription, String minStr, String maxStr, String defaultStr,
float theUIOrder) {
this(theName, theDescription, Long.valueOf(minStr), Long.valueOf(maxStr),
Long.valueOf(defaultStr), theUIOrder, false);
}
/** Master constructor. */
private LongProperty(String theName, String theDescription, Long min, Long max, Long theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, theDefault, theUIOrder, isDefinedExternally);
}
/**
* Constructor that limits itself to a single value within the specified limits.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param theDefault Default value
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#longIntProperty(String)}
*/
@Deprecated
public LongProperty(String theName, String theDescription, Long min, Long max, Long theDefault, float theUIOrder) {
this(theName, theDescription, min, max, theDefault, theUIOrder, false);
}
@Override
public Class<Long> type() {
return Long.class;
}
@Override
protected Long createFrom(String toParse) {
return Long.valueOf(toParse);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Long, LongPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue.Numeric<Long, LongPBuilder>(Long.class, ValueParserConstants.LONG_PARSER) {
@Override
protected LongPBuilder newBuilder(String name) {
return new LongPBuilder(name);
}
};
}
/** @deprecated Use {@link PropertyFactory#longIntProperty(String)} */
@Deprecated
public static LongPBuilder named(String name) {
return new LongPBuilder(name);
}
/** @deprecated Use {@link PropertyFactory#longIntProperty(String)} */
@Deprecated
public static final class LongPBuilder extends SingleNumericPropertyBuilder<Long, LongPBuilder> {
private LongPBuilder(String name) {
super(name);
}
@Override
public LongProperty build() {
return new LongProperty(name, description, lowerLimit, upperLimit, defaultValue, uiOrder, isDefinedInXML);
}
}
}
| 4,062 | 33.726496 | 149 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyFactory.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import net.sourceforge.pmd.properties.PropertyBuilder.GenericCollectionPropertyBuilder;
import net.sourceforge.pmd.properties.PropertyBuilder.GenericPropertyBuilder;
import net.sourceforge.pmd.properties.PropertyBuilder.RegexPropertyBuilder;
import net.sourceforge.pmd.properties.constraints.NumericConstraints;
import net.sourceforge.pmd.properties.constraints.PropertyConstraint;
import net.sourceforge.pmd.util.CollectionUtil;
//@formatter:off
/**
* Provides factory methods for common property types.
* Note: from 7.0.0 on, this will be the only way to
* build property descriptors. Concrete property classes
* and their constructors/ builders will be gradually
* deprecated before 7.0.0.
*
* <h1>Usage</h1>
*
* Properties are a way to make your rule configurable by
* letting a user fill in some config value in their
* ruleset XML.
*
* As a rule developer, to declare a property on your rule, you
* must:
* <ul>
* <li>Build a {@link PropertyDescriptor} using one of
* the factory methods of this class, and providing the
* {@linkplain PropertyBuilder builder} with the required
* info.
* <li>Define the property on your rule using {@link PropertySource#definePropertyDescriptor(PropertyDescriptor)}.
* This should be done in your rule's constructor.
* </ul>
*
* You can then retrieve the value configured by the user in your
* rule using {@link PropertySource#getProperty(PropertyDescriptor)}.
*
* <h1>Example</h1>
*
* <pre>
* class MyRule {
* // The property descriptor may be static, it can be shared across threads.
* private static final {@link PropertyDescriptor}<Integer> myIntProperty
* = PropertyFactory.{@linkplain #intProperty(String) intProperty}("myIntProperty")
* .{@linkplain PropertyBuilder#desc(String) desc}("This is my property")
* .{@linkplain PropertyBuilder#defaultValue(Object) defaultValue}(3)
* .{@linkplain PropertyBuilder#require(PropertyConstraint) require}(inRange(0, 100)) // constraints are checked before the rule is run
* .{@linkplain PropertyBuilder#build() build}();
*
* // ..
*
* public MyRule() {
* {@linkplain PropertySource#definePropertyDescriptor(PropertyDescriptor) definePropertyDescriptor}(myIntProperty);
* }
*
* // ... somewhere in the rule
*
* int myPropertyValue = {@linkplain PropertySource#getProperty(PropertyDescriptor) getProperty(myIntProperty)};
* // use it.
*
* }
* </pre>
*
*
* @author Clément Fournier
* @since 6.10.0
*/
//@formatter:on
public final class PropertyFactory {
private PropertyFactory() {
}
/**
* Returns a builder for an integer property. The property descriptor
* will by default accept any value conforming to the format specified
* by {@link Integer#parseInt(String)}, e.g. {@code 1234} or {@code -123}.
*
* <p>Note that that parser only supports decimal representations.
*
* <p>Acceptable values may be further refined by {@linkplain PropertyBuilder#require(PropertyConstraint) adding constraints}.
* The class {@link NumericConstraints} provides some useful ready-made constraints
* for that purpose.
*
* @param name Name of the property to build
*
* @return A new builder
*
* @see NumericConstraints
*/
public static GenericPropertyBuilder<Integer> intProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.INTEGER_PARSER, Integer.class);
}
/**
* Returns a builder for a property having as value a list of integers. The
* format of the individual items is the same as for {@linkplain #intProperty(String) intProperty}.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericCollectionPropertyBuilder<Integer, List<Integer>> intListProperty(String name) {
return intProperty(name).toList().delim(MultiValuePropertyDescriptor.DEFAULT_NUMERIC_DELIMITER);
}
/**
* Returns a builder for a long integer property. The property descriptor
* will by default accept any value conforming to the format specified
* by {@link Long#parseLong(String)}, e.g. {@code 1234455678854}.
*
* <p>Note that that parser only supports decimal representations, and that neither
* the character L nor l is permitted to appear at the end of the string as a type
* indicator, as would be permitted in Java source.
*
* <p>Acceptable values may be further refined by {@linkplain PropertyBuilder#require(PropertyConstraint) adding constraints}.
* The class {@link NumericConstraints} provides some useful ready-made constraints
* for that purpose.
*
* @param name Name of the property to build
*
* @return A new builder
*
* @see NumericConstraints
*/
public static GenericPropertyBuilder<Long> longIntProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.LONG_PARSER, Long.class);
}
/**
* Returns a builder for a property having as value a list of long integers. The
* format of the individual items is the same as for {@linkplain #longIntProperty(String)} longIntProperty}.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericCollectionPropertyBuilder<Long, List<Long>> longIntListProperty(String name) {
return longIntProperty(name).toList().delim(MultiValuePropertyDescriptor.DEFAULT_NUMERIC_DELIMITER);
}
/**
* Returns a builder for a double property. The property descriptor
* will by default accept any value conforming to the format specified
* by {@link Double#valueOf(String)}, e.g. {@code 0}, {@code .93}, or {@code 1e-1}.
* Acceptable values may be further refined by {@linkplain PropertyBuilder#require(PropertyConstraint) adding constraints}.
* The class {@link NumericConstraints} provides some useful ready-made constraints
* for that purpose.
*
* @param name Name of the property to build
*
* @return A new builder
*
* @see NumericConstraints
*/
public static GenericPropertyBuilder<Double> doubleProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.DOUBLE_PARSER, Double.class);
}
/**
* Returns a builder for a property having as value a list of decimal numbers. The
* format of the individual items is the same as for {@linkplain #doubleProperty(String) doubleProperty}.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericCollectionPropertyBuilder<Double, List<Double>> doubleListProperty(String name) {
return doubleProperty(name).toList().delim(MultiValuePropertyDescriptor.DEFAULT_NUMERIC_DELIMITER);
}
/**
* Returns a builder for a regex property. The value type of such
* a property is {@link java.util.regex.Pattern}. For this use case, this type of
* property should be preferred over {@linkplain #stringProperty(String) stringProperty}
* as pattern compilation, including syntax errors, are handled transparently to
* the rule.
*
* <p>This type of property is not available as a list, because the delimiters
* could be part of the regex. This restriction will be lifted with 7.0.0.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static RegexPropertyBuilder regexProperty(String name) {
return new RegexPropertyBuilder(name);
}
/**
* Returns a builder for a string property. The property descriptor
* will accept any string, and performs no expansion of escape
* sequences (e.g. {@code \n} in the XML will be represented as the
* character sequence '\' 'n' and not the line-feed character '\n').
* This behaviour could be changed with PMD 7.0.0.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericPropertyBuilder<String> stringProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.STRING_PARSER, String.class);
}
/**
* Returns a builder for a property having as value a list of strings. The
* format of the individual items is the same as for {@linkplain #stringProperty(String) stringProperty}.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericCollectionPropertyBuilder<String, List<String>> stringListProperty(String name) {
return stringProperty(name).toList();
}
/**
* Returns a builder for a character property. The property descriptor
* will accept any single character string. No unescaping is performed
* other than what the XML parser does itself. That means that Java
* escape sequences are not expanded: e.g. "\n", will be represented as the
* character sequence '\' 'n', so it's not a valid value for this type
* of property. On the other hand, XML character references are expanded,
* like {@literal &} ('&') or {@literal <} ('<').
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericPropertyBuilder<Character> charProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.CHARACTER_PARSER, Character.class);
}
/**
* Returns a builder for a property having as value a list of characters. The
* format of the individual items is the same as for {@linkplain #charProperty(String) charProperty}.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericCollectionPropertyBuilder<Character, List<Character>> charListProperty(String name) {
return charProperty(name).toList();
}
/**
* Returns a builder for a boolean property. The boolean is parsed from
* the XML using {@link Boolean#valueOf(String)}, i.e. the only truthy
* value is the string "true", and all other string values are falsy.
*
* @param name Name of the property to build
*
* @return A new builder
*/
public static GenericPropertyBuilder<Boolean> booleanProperty(String name) {
return new GenericPropertyBuilder<>(name, ValueParserConstants.BOOLEAN_PARSER, Boolean.class);
}
// We can add more useful factories with Java 8.
// * We don't really need a Map, just a Function<String, T>.
// * We could have a factory taking a Class<? extends Enum<T>>
// and a Function<T, String> to build a mapper for a whole enum.
/**
* Returns a builder for an enumerated property. Such a property can be
* defined for any type {@code <T>}, provided the possible values can be
* indexed by strings. This is enforced by passing a {@code Map<String, T>}
* at construction time, which maps labels to values. If {@link Map#get(Object)}
* returns null for a given label, then the value is rejected. Null values
* are hence prohibited.
*
* @param name Name of the property to build
* @param nameToValue Map of labels to values. The null key is ignored.
* @param <T> Value type of the property
*
* @return A new builder
*/
// Note: there is a bug, whereby the default value can be set on
// the builder, even if it wasn't registered in the constants
// This is fixed in the framework refactoring
public static <T> GenericPropertyBuilder<T> enumProperty(String name, Map<String, T> nameToValue) {
// TODO find solution to document the set of possible values
// At best, map that requirement to a constraint (eg make parser return null if not found, and
// add a non-null constraint with the right description.)
return new GenericPropertyBuilder<>(name, ValueParserConstants.enumerationParser(nameToValue), (Class<T>) Object.class);
}
/**
* Returns a builder for a property having as value a list of {@code <T>}. The
* format of the individual items is the same as for {@linkplain #enumProperty(String, Map)}.
*
* @param name Name of the property to build
* @param nameToValue Map of labels to values. The null key is ignored.
* @param <T> Value type of the property
*
* @return A new builder
*/
public static <T> GenericCollectionPropertyBuilder<T, List<T>> enumListProperty(String name, Map<String, T> nameToValue) {
return enumProperty(name, nameToValue).toList().delim(MultiValuePropertyDescriptor.DEFAULT_DELIMITER);
}
/**
* Returns a builder for a property having as value a list of {@code <T>}. The
* format of the individual items is the same as for {@linkplain #enumProperty(String, Map)}.
*
* @param name Name of the property to build
* @param enumClass Class of the values
* @param labelMaker Function that associates enum constants to their label
* @param <T> Value type of the property
*
* @return A new builder
*/
public static <T extends Enum<T>> GenericCollectionPropertyBuilder<T, List<T>> enumListProperty(String name, Class<T> enumClass, Function<? super T, String> labelMaker) {
Map<String, T> enumMap = CollectionUtil.associateBy(asList(enumClass.getEnumConstants()), labelMaker);
return enumListProperty(name, enumMap);
}
}
| 13,973 | 39.504348 | 174 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/IntegerMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.properties.builders.MultiNumericPropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Multi-valued integer property.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
*
*
* @deprecated Use a {@code PropertyDescriptor<List<Integer>>} instead. A builder is available from {@link PropertyFactory#intListProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class IntegerMultiProperty extends AbstractMultiNumericProperty<Integer> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues Array of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#intListProperty(String)}
*/
@Deprecated
public IntegerMultiProperty(String theName, String theDescription, Integer min, Integer max,
Integer[] defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, Arrays.asList(defaultValues), theUIOrder, false);
}
/** Master constructor. */
private IntegerMultiProperty(String theName, String theDescription, Integer min, Integer max,
List<Integer> defaultValues, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, min, max, defaultValues, theUIOrder, isDefinedExternally);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param min Minimum value of the property
* @param max Maximum value of the property
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if {@literal min > max} or one of the defaults is not between the bounds
* @deprecated Use {@link PropertyFactory#intListProperty(String)}
*/
@Deprecated
public IntegerMultiProperty(String theName, String theDescription, Integer min, Integer max,
List<Integer> defaultValues, float theUIOrder) {
this(theName, theDescription, min, max, defaultValues, theUIOrder, false);
}
@Override
public Class<Integer> type() {
return Integer.class;
}
@Override
protected Integer createFrom(String toParse) {
return Integer.valueOf(toParse);
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Integer, IntegerMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue.Numeric<Integer, IntegerMultiPBuilder>(Integer.class, ValueParserConstants.INTEGER_PARSER) {
@Override
protected IntegerMultiPBuilder newBuilder(String name) {
return new IntegerMultiPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#intListProperty(String)}
*/
@Deprecated
public static IntegerMultiPBuilder named(String name) {
return new IntegerMultiPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#intListProperty(String)}
*/
@Deprecated
public static final class IntegerMultiPBuilder extends MultiNumericPropertyBuilder<Integer, IntegerMultiPBuilder> {
private IntegerMultiPBuilder(String name) {
super(name);
}
@Override
public IntegerMultiProperty build() {
return new IntegerMultiProperty(name, description, lowerLimit, upperLimit, defaultValues, uiOrder, isDefinedInXML);
}
}
}
| 4,177 | 32.693548 | 165 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/StringProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleValuePropertyBuilder;
/**
* Defines a datatype that supports single String values.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<String>}. A builder is available from {@link PropertyFactory#stringProperty(String)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class StringProperty extends AbstractSingleValueProperty<String> {
/**
* Constructor.
*
* @param theName Name
* @param theDescription Description
* @param defaultValue Default value
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#stringProperty(String)}
*/
@Deprecated
public StringProperty(String theName, String theDescription, String defaultValue, float theUIOrder) {
this(theName, theDescription, defaultValue, theUIOrder, false);
}
/** Master constructor. */
private StringProperty(String theName, String theDescription, String defaultValue, float theUIOrder, boolean
isDefinedExternally) {
super(theName, theDescription, defaultValue, theUIOrder, isDefinedExternally);
}
@Override
public Class<String> type() {
return String.class;
}
@Override
public String createFrom(String valueString) {
return valueString;
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue<String, StringPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue<String, StringPBuilder>(String.class, ValueParserConstants.STRING_PARSER) {
@Override
protected StringPBuilder newBuilder(String name) {
return new StringPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#stringProperty(String)}
*/
@Deprecated
public static StringPBuilder named(String name) {
return new StringPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#stringProperty(String)}
*/
@Deprecated
public static final class StringPBuilder extends SingleValuePropertyBuilder<String, StringPBuilder> {
private StringPBuilder(String name) {
super(name);
}
@Override
public StringProperty build() {
return new StringProperty(this.name, this.description, this.defaultValue, this.uiOrder, isDefinedInXML);
}
}
}
| 2,748 | 28.880435 | 149 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/AbstractNumericProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Map;
import net.sourceforge.pmd.properties.modules.NumericPropertyModule;
/**
* Maintains a pair of boundary limit values between which all values managed by the subclasses must fit.
*
* @param <T> The type of value.
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
*/
@Deprecated
/* default */ abstract class AbstractNumericProperty<T extends Number> extends AbstractSingleValueProperty<T>
implements NumericPropertyDescriptor<T> {
private final NumericPropertyModule<T> module;
/**
* Constructor for a single-valued numeric property.
*
* @param theName Name
* @param theDescription Description
* @param lower Minimum value of the property
* @param upper Maximum value of the property
* @param theDefault List of defaults
* @param theUIOrder UI order
*
* @throws IllegalArgumentException if lower > upper, or one of them is null, or the default is not between the
* bounds
*/
protected AbstractNumericProperty(String theName, String theDescription, T lower, T upper, T theDefault,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, theDefault, theUIOrder, isDefinedExternally);
module = new NumericPropertyModule<>(lower, upper);
if (theDefault == null) {
return; // TODO: remove me when you scrap StatisticalRule (see pull #727)
}
module.checkNumber(theDefault);
}
@Override
protected String valueErrorFor(T value) {
return module.valueErrorFor(value);
}
@Override
public Number lowerLimit() {
return module.getLowerLimit();
}
@Override
public Number upperLimit() {
return module.getUpperLimit();
}
@Override
protected void addAttributesTo(Map<PropertyDescriptorField, String> attributes) {
super.addAttributesTo(attributes);
module.addAttributesTo(attributes);
}
}
| 2,243 | 27.05 | 115 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/EnumeratedMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.properties.builders.MultiValuePropertyBuilder;
import net.sourceforge.pmd.properties.modules.EnumeratedPropertyModule;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Multi-valued property which can take only a fixed set of values of any type, then selected via String labels. The
* mappings method returns the set of mappings between the labels and their values.
*
* @param <E> The type of the values
*
* @author Brian Remedios
* @author Clément Fournier
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<List<E>>} instead. A builder is available from {@link PropertyFactory#enumListProperty(String, Map)}.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class EnumeratedMultiProperty<E> extends AbstractMultiValueProperty<E>
implements EnumeratedPropertyDescriptor<E, List<E>> {
private final EnumeratedPropertyModule<E> module;
/**
* Constructor using arrays to define the label-value mappings. The correct construction of the property depends on
* the correct ordering of the arrays.
*
* @param theName Name
* @param theDescription Description
* @param theLabels Labels of the choices
* @param theChoices Values that can be chosen
* @param choiceIndices Indices of the default values
* @param valueType Type of the values
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#enumListProperty(String, Map)}
*/
@Deprecated
public EnumeratedMultiProperty(String theName, String theDescription, String[] theLabels, E[] theChoices,
int[] choiceIndices, Class<E> valueType, float theUIOrder) {
this(theName, theDescription, CollectionUtil.mapFrom(theLabels, theChoices),
selection(choiceIndices, theChoices), valueType, theUIOrder, false);
}
/**
* Constructor using arrays to define the label-value mappings. The correct construction of the property depends on
* the correct ordering of the arrays.
*
* @param theName Name
* @param theDescription Description
* @param theLabels Labels of the choices
* @param theChoices Values that can be chosen
* @param choiceIndices Indices of the default values
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#enumListProperty(String, Map)}
*/
@Deprecated
public EnumeratedMultiProperty(String theName, String theDescription, String[] theLabels, E[] theChoices,
int[] choiceIndices, float theUIOrder) {
this(theName, theDescription, CollectionUtil.mapFrom(theLabels, theChoices),
selection(choiceIndices, theChoices), null, theUIOrder, false);
}
/**
* Constructor using a map to define the label-value mappings. The default values are specified with a list.
*
* @param theName Name
* @param theDescription Description
* @param choices Map of labels to values
* @param defaultValues List of default values
* @param valueType Type of the values
* @param theUIOrder UI order
* @deprecated Use {@link PropertyFactory#enumListProperty(String, Map)}
*/
@Deprecated
public EnumeratedMultiProperty(String theName, String theDescription, Map<String, E> choices,
List<E> defaultValues, Class<E> valueType, float theUIOrder) {
this(theName, theDescription, choices, defaultValues, valueType, theUIOrder, false);
}
private EnumeratedMultiProperty(String theName, String theDescription, Map<String, E> choices,
List<E> defaultValues, Class<E> valueType, float theUIOrder,
boolean isDefinedExternally) {
super(theName, theDescription, defaultValues, theUIOrder, isDefinedExternally);
module = new EnumeratedPropertyModule<>(choices, valueType);
checkDefaults(defaultValues);
}
@Override
public Map<String, E> mappings() {
return module.getChoicesByLabel(); // unmodifiable
}
@Override
public Class<E> type() {
return module.getValueType();
}
@Override
public String errorFor(List<E> values) {
for (E value : values) {
String error = module.errorFor(value);
if (error != null) {
return error;
}
}
return null;
}
@Override
protected E createFrom(String toParse) {
return module.choiceFrom(toParse);
}
@Override
public String asString(E item) {
return module.getLabelsByChoice().get(item);
}
private void checkDefaults(List<E> defaults) {
for (E elt : defaults) {
module.checkValue(elt);
}
}
private static <E> List<E> selection(int[] choiceIndices, E[] theChoices) {
List<E> selected = new ArrayList<>();
for (int i : choiceIndices) {
if (i < 0 || i > theChoices.length) {
throw new IllegalArgumentException("Default value index is out of bounds: " + i);
}
selected.add(theChoices[i]);
}
return selected;
}
/**
* @deprecated Use {@link PropertyFactory#enumListProperty(String, Map)}
*/
@Deprecated
public static <E> EnumMultiPBuilder<E> named(String name) {
return new EnumMultiPBuilder<>(name);
}
/**
* @deprecated Use {@link PropertyFactory#enumListProperty(String, Map)}
*/
@Deprecated
public static final class EnumMultiPBuilder<E> extends MultiValuePropertyBuilder<E, EnumMultiPBuilder<E>> {
private Class<E> valueType;
private Map<String, E> mappings;
private EnumMultiPBuilder(String name) {
super(name);
}
public EnumMultiPBuilder<E> type(Class<E> type) {
this.valueType = type;
return this;
}
/**
* Sets the key-value mappings.
*
* @param map A map of label to value
*
* @return The same builder
*/
public EnumMultiPBuilder<E> mappings(Map<String, E> map) {
this.mappings = map;
return this;
}
@Override
public EnumeratedMultiProperty<E> build() {
return new EnumeratedMultiProperty<>(this.name, this.description, mappings, this.defaultValues, valueType, this.uiOrder, isDefinedInXML);
}
}
}
| 6,854 | 31.642857 | 149 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/PropertyDescriptorField.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import java.util.Objects;
/**
* Field names for parsing the properties out of the ruleset xml files. These are intended to be used as the keys to a
* map of fields to values. Most property descriptors can be built directly from such a map using their factory.
*
* @author Brian Remedios
* @see PropertyTypeId
* @deprecated Will be removed with 7.0.0
*/
@Deprecated
public enum PropertyDescriptorField {
/** The type of the property. */
TYPE("type"),
/** The name of the property. */
NAME("name"),
/** The description of the property. */
DESCRIPTION("description"),
/** The UI order. */
UI_ORDER("uiOrder"),
/** The default value. */
DEFAULT_VALUE("value"),
/** For multi-valued properties, this defines the delimiter of the single values. */
DELIMITER("delimiter"),
/** The minimum allowed value for numeric properties. */
MIN("min"),
/** The maximum allowed value for numeric properties. */
MAX("max"),
/** To limit the range of valid values, package names. */
LEGAL_PACKAGES("legalPackages"),
/** Labels for enumerated properties. */
LABELS("labels"),
/** Choices for enumerated properties. */
CHOICES("choices"),
/** Default index for enumerated properties. */
DEFAULT_INDEX("defaultIndex");
private final String attributeName;
PropertyDescriptorField(String attributeName) {
this.attributeName = attributeName;
}
/**
* Returns the String name of this attribute.
*
* @return The attribute's name
*/
public String attributeName() {
return attributeName;
}
@Override
public String toString() {
return attributeName();
}
public static PropertyDescriptorField getConstant(String name) {
for (PropertyDescriptorField f : values()) {
if (Objects.equals(f.attributeName, name)) {
return f;
}
}
return null;
}
}
| 2,105 | 25.325 | 118 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/BooleanProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.BOOLEAN_PARSER;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
import net.sourceforge.pmd.properties.builders.SingleValuePropertyBuilder;
/**
* Defines a property type that supports single Boolean values.
*
* @author Brian Remedios
* @version Refactored June 2017 (6.0.0)
* @deprecated Use a {@code PropertyDescriptor<Boolean>} instead. A builder is available from {@link PropertyFactory#booleanProperty(String)} and its overloads.
* This class will be removed in 7.0.0.
*/
@Deprecated
public final class BooleanProperty extends AbstractSingleValueProperty<Boolean> {
/**
* Constructor for BooleanProperty limited to a single value. Converts default argument string into a boolean.
*
* @param theName Name
* @param theDescription Description
* @param defaultBoolStr String representing the default value.
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#booleanProperty(String)} or its overloads.
*/
@Deprecated
public BooleanProperty(String theName, String theDescription, String defaultBoolStr, float theUIOrder) {
this(theName, theDescription, Boolean.parseBoolean(defaultBoolStr), theUIOrder, false);
}
/** Master constructor. */
private BooleanProperty(String theName, String theDescription, boolean defaultValue, float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, defaultValue, theUIOrder, isDefinedExternally);
}
/**
* Constructor.
*
* @param theName Name
* @param theDescription Description
* @param defaultValue Default value
* @param theUIOrder UI order
*
* @deprecated Use {@link PropertyFactory#booleanProperty(String)} or its overloads.
*/
@Deprecated
public BooleanProperty(String theName, String theDescription, boolean defaultValue, float theUIOrder) {
this(theName, theDescription, defaultValue, theUIOrder, false);
}
@Override
public Class<Boolean> type() {
return Boolean.class;
}
@Override
public Boolean createFrom(String propertyString) throws IllegalArgumentException {
return BOOLEAN_PARSER.valueOf(propertyString);
}
static PropertyDescriptorBuilderConversionWrapper.SingleValue<Boolean, BooleanPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.SingleValue<Boolean, BooleanPBuilder>(Boolean.class, ValueParserConstants.BOOLEAN_PARSER) {
@Override
protected BooleanPBuilder newBuilder(String name) {
return new BooleanPBuilder(name);
}
};
}
/**
* @deprecated Use {@link PropertyFactory#booleanProperty(String)} or its overloads.
*/
@Deprecated
public static BooleanPBuilder named(String name) {
return new BooleanPBuilder(name);
}
/**
* @deprecated Use {@link PropertyFactory#booleanProperty(String)} or its overloads.
*/
@Deprecated
public static final class BooleanPBuilder extends SingleValuePropertyBuilder<Boolean, BooleanPBuilder> {
private BooleanPBuilder(String name) {
super(name);
}
@Override
public BooleanProperty build() {
return new BooleanProperty(this.name, this.description, this.defaultValue, this.uiOrder, this.isDefinedInXML);
}
}
}
| 3,659 | 32.272727 | 160 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/BooleanMultiProperty.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.ValueParserConstants.BOOLEAN_PARSER;
import java.util.Arrays;
import java.util.List;
import net.sourceforge.pmd.properties.builders.MultiValuePropertyBuilder;
import net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrapper;
/**
* Defines a property type that supports multiple Boolean values.
*
* @author Brian Remedios
* @deprecated Not useful, will be removed with 7.0.0
*/
@Deprecated
public final class BooleanMultiProperty extends AbstractMultiValueProperty<Boolean> {
/**
* Constructor using an array of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @deprecated Not useful, will be removed with 7.0.0
*/
@Deprecated
public BooleanMultiProperty(String theName, String theDescription, Boolean[] defaultValues, float theUIOrder) {
this(theName, theDescription, Arrays.asList(defaultValues), theUIOrder, false);
}
/** Master constructor. */
private BooleanMultiProperty(String theName, String theDescription, List<Boolean> defaultValues,
float theUIOrder, boolean isDefinedExternally) {
super(theName, theDescription, defaultValues, theUIOrder, isDefinedExternally);
}
/**
* Constructor using a list of defaults.
*
* @param theName Name
* @param theDescription Description
* @param defaultValues List of defaults
* @param theUIOrder UI order
*
* @deprecated Not useful, will be removed with 7.0.0
*/
@Deprecated
public BooleanMultiProperty(String theName, String theDescription, List<Boolean> defaultValues, float theUIOrder) {
this(theName, theDescription, defaultValues, theUIOrder, false);
}
@Override
protected Boolean createFrom(String toParse) {
return BOOLEAN_PARSER.valueOf(toParse);
}
@Override
public Class<Boolean> type() {
return Boolean.class;
}
static PropertyDescriptorBuilderConversionWrapper.MultiValue<Boolean, BooleanMultiPBuilder> extractor() {
return new PropertyDescriptorBuilderConversionWrapper.MultiValue<Boolean, BooleanMultiPBuilder>(Boolean.class, ValueParserConstants.BOOLEAN_PARSER) {
@Override
protected BooleanMultiPBuilder newBuilder(String name) {
return new BooleanMultiPBuilder(name);
}
};
}
/**
* @deprecated Not useful, will be removed with 7.0.0
*/
@Deprecated
public static BooleanMultiPBuilder named(String name) {
return new BooleanMultiPBuilder(name);
}
/**
* @deprecated Not useful, will be removed with 7.0.0
*/
@Deprecated
public static final class BooleanMultiPBuilder extends MultiValuePropertyBuilder<Boolean, BooleanMultiPBuilder> {
private BooleanMultiPBuilder(String name) {
super(name);
}
@Override
public BooleanMultiProperty build() {
return new BooleanMultiProperty(this.name, this.description, this.defaultValues, this.uiOrder, isDefinedInXML);
}
}
}
| 3,391 | 29.017699 | 157 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/EnumeratedPropertyModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.modules;
import java.util.Collections;
import java.util.Map;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Factorises common functionality for enumerated properties.
*
* @author Clément Fournier
*/
@Deprecated
public class EnumeratedPropertyModule<E> {
private final Map<String, E> choicesByLabel;
private final Map<E, String> labelsByChoice;
private final Class<E> valueType;
public EnumeratedPropertyModule(Map<String, E> choicesByLabel, Class<E> valueType) {
this.valueType = valueType;
this.choicesByLabel = Collections.unmodifiableMap(choicesByLabel);
this.labelsByChoice = Collections.unmodifiableMap(CollectionUtil.invertedMapFrom(choicesByLabel));
}
public Class<E> getValueType() {
return valueType;
}
public Map<E, String> getLabelsByChoice() {
return labelsByChoice;
}
public Map<String, E> getChoicesByLabel() {
return choicesByLabel;
}
private String nonLegalValueMsgFor(E value) {
return value + " is not a legal value";
}
public String errorFor(E value) {
return labelsByChoice.containsKey(value) ? null : nonLegalValueMsgFor(value);
}
public E choiceFrom(String label) {
E result = choicesByLabel.get(label);
if (result != null) {
return result;
}
throw new IllegalArgumentException(label);
}
public void checkValue(E value) {
if (!choicesByLabel.containsValue(value)) {
throw new IllegalArgumentException("Invalid default value: no mapping to this value");
}
}
}
| 1,754 | 22.716216 | 106 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/modules/NumericPropertyModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.modules;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.MAX;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.MIN;
import java.util.Map;
import net.sourceforge.pmd.properties.PropertyDescriptorField;
/**
* Common utilities for implementations of numeric property descriptors.
*
* @author Clément Fournier
*/
@Deprecated
public class NumericPropertyModule<T extends Number> {
private final T lowerLimit;
private final T upperLimit;
public NumericPropertyModule(T lowerLimit, T upperLimit) {
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
checkNumber(lowerLimit);
checkNumber(upperLimit);
if (lowerLimit.doubleValue() > upperLimit.doubleValue()) {
throw new IllegalArgumentException("Lower limit cannot be greater than the upper limit");
}
}
public void checkNumber(T number) {
String error = valueErrorFor(number);
if (error != null) {
throw new IllegalArgumentException(error);
}
}
public String valueErrorFor(T value) {
if (value == null) {
return "Missing value";
}
double number = value.doubleValue();
if (number > upperLimit.doubleValue() || number < lowerLimit.doubleValue()) {
return value + " is out of range " + rangeString(lowerLimit, upperLimit);
}
return null;
}
public T getLowerLimit() {
return lowerLimit;
}
public T getUpperLimit() {
return upperLimit;
}
public void addAttributesTo(Map<PropertyDescriptorField, String> attributes) {
attributes.put(MIN, lowerLimit.toString());
attributes.put(MAX, upperLimit.toString());
}
/**
* Returns a string representing the range defined by the two bounds.
*
* @param low Lower bound
* @param up Upper bound
*
* @return String
*/
private static String rangeString(Number low, Number up) {
return "(" + low + " -> " + up + ")";
}
}
| 2,213 | 22.553191 | 101 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/constraints/NumericConstraints.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.constraints;
/**
* Common constraints for properties dealing with numbers.
*
* @author Clément Fournier
* @see PropertyConstraint
* @since 6.10.0
*/
public final class NumericConstraints {
private NumericConstraints() {
}
// Methods are named to mix well with the "require" syntax.
/**
* Requires the number to be inside a range.
*
* @param <N> Type of number
*
* @return A range constraint
*/
public static <N extends Number & Comparable<N>> PropertyConstraint<N> inRange(final N minInclusive, final N maxInclusive) {
return PropertyConstraint.fromPredicate(
t -> minInclusive.compareTo(t) <= 0 && maxInclusive.compareTo(t) >= 0,
"Should be between " + minInclusive + " and " + maxInclusive
);
}
/**
* Requires the number to be strictly positive.
* The int values of the number is used for comparison
* so there may be some unexpected behaviour with decimal
* numbers.
*
* @param <N> Type of number
*
* @return A positivity constraint
*/
public static <N extends Number> PropertyConstraint<N> positive() {
return PropertyConstraint.fromPredicate(
t -> t.intValue() > 0,
"Should be positive"
);
}
}
| 1,442 | 24.315789 | 128 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/constraints/PropertyConstraint.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.constraints;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.annotation.Experimental;
/**
* Validates the value of a property.
*
* <p>This interface will change a lot with PMD 7.0.0,
* because of the switch to Java 8. Please use
* only the ready-made validators in {@link NumericConstraints}
* for now.
*
* @param <T> Type of value to handle
*
* @author Clément Fournier
* @since 6.10.0
*/
@Experimental
public interface PropertyConstraint<T> {
default boolean test(T t) {
return validate(t) == null;
}
/**
* Returns a diagnostic message if the value
* has a problem. Otherwise returns an empty
* optional.
*
* @param value The value to validate
*
* @return An optional diagnostic message
*/
@Nullable
String validate(T value); // Future make default
/**
* Returns a description of the constraint
* imposed by this validator on the values.
* E.g. "Should be positive", or "Should be one of A | B | C."
*
* <p>This is used to generate documentation.
*
* @return A description of the constraint
*/
String getConstraintDescription();
/**
* Returns a constraint that validates a collection of Ts
* by checking each component conforms to this constraint.
*/
@Experimental
default PropertyConstraint<Iterable<? extends T>> toCollectionConstraint() {
return new PropertyConstraint<Iterable<? extends T>>() {
private final PropertyConstraint<? super T> itemConstraint = PropertyConstraint.this;
@Override
public @Nullable String validate(Iterable<? extends T> value) {
List<String> errors = new ArrayList<>();
int i = 0;
for (T u : value) {
String err = itemConstraint.validate(u);
if (err != null) {
errors.add("Item " + i + " " + StringUtils.uncapitalize(err));
}
i++;
}
return errors.isEmpty() ? null : String.join("; ", errors);
}
@Override
public String getConstraintDescription() {
return "Components " + StringUtils.uncapitalize(itemConstraint.getConstraintDescription());
}
};
}
/**
* Builds a new validator from a predicate, and description.
*
* @param pred The predicate. If it returns
* false on a value, then the
* value is deemed to have a
* problem
* @param constraintDescription Description of the constraint,
* see {@link PropertyConstraint#getConstraintDescription()}.
* @param <U> Type of value to validate
*
* @return A new validator
*/
@Experimental
static <U> PropertyConstraint<U> fromPredicate(final Predicate<? super U> pred, final String constraintDescription) {
return new PropertyConstraint<U>() {
// TODO message could be better, eg include name of the property
@Override
public String validate(U value) {
return pred.test(value) ? null : "Constraint violated on property value '" + value + "' (" + StringUtils.uncapitalize(constraintDescription) + ")";
}
@Override
public String getConstraintDescription() {
return StringUtils.capitalize(constraintDescription);
}
};
}
}
| 3,931 | 29.96063 | 163 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/PropertyDescriptorBuilderConversionWrapper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.DELIMITER;
import static net.sourceforge.pmd.properties.PropertyDescriptorField.LEGAL_PACKAGES;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.MultiValuePropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyDescriptorField;
import net.sourceforge.pmd.properties.ValueParser;
import net.sourceforge.pmd.properties.ValueParserConstants;
/**
* Wraps a property builder and maps its inputs from strings to the target types of the descriptor.
*
* @param <E> Value type of the descriptor
* @param <T> Concrete type of the underlying builder
*
* @deprecated This was not public API and will be removed by 7.0.0
* @author Clément Fournier
* @since 6.0.0
*/
@Deprecated
public abstract class PropertyDescriptorBuilderConversionWrapper<E, T extends PropertyDescriptorBuilder<E, T>>
implements PropertyDescriptorExternalBuilder<E> {
private final Class<?> valueType;
protected PropertyDescriptorBuilderConversionWrapper(Class<?> valueType) {
this.valueType = valueType;
}
/** Populates the builder with extracted fields. To be overridden. */
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
builder.desc(fields.get(PropertyDescriptorField.DESCRIPTION));
if (fields.containsKey(PropertyDescriptorField.UI_ORDER)) {
builder.uiOrder(Float.parseFloat(fields.get(PropertyDescriptorField.UI_ORDER)));
}
}
@Override
public abstract boolean isMultiValue();
@Override
public Class<?> valueType() {
return valueType;
}
protected abstract T newBuilder(String name); // FUTURE 1.8: use a Supplier constructor parameter
@Override
public PropertyDescriptor<E> build(Map<PropertyDescriptorField, String> fields) {
T builder = newBuilder(fields.get(PropertyDescriptorField.NAME));
populate(builder, fields);
builder.isDefinedInXML = true;
return builder.build();
}
protected static String[] legalPackageNamesIn(Map<PropertyDescriptorField, String> valuesById, char delimiter) {
String names = valuesById.get(LEGAL_PACKAGES);
return StringUtils.isBlank(names) ? null : StringUtils.split(names, delimiter);
}
private static char delimiterIn(Map<PropertyDescriptorField, String> valuesById, char defalt) {
String characterStr = "";
if (valuesById.containsKey(DELIMITER)) {
characterStr = valuesById.get(DELIMITER).trim();
}
if (StringUtils.isBlank(characterStr)) {
return defalt;
}
if (characterStr.length() != 1) {
throw new RuntimeException("Ambiguous delimiter character, must have length 1: \"" + characterStr + "\"");
}
return characterStr.charAt(0);
}
/**
* For multi-value properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
*/
public abstract static class MultiValue<V, T extends MultiValuePropertyBuilder<V, T>>
extends PropertyDescriptorBuilderConversionWrapper<List<V>, T> {
protected final ValueParser<V> parser;
protected MultiValue(Class<V> valueType, ValueParser<V> parser) {
super(valueType);
this.parser = parser;
}
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
char delim = delimiterIn(fields, builder.multiValueDelimiter);
builder.delim(delim).defaultValues(ValueParserConstants.multi(parser, delim)
.valueOf(fields.get(PropertyDescriptorField.DEFAULT_VALUE)));
}
@Override
public boolean isMultiValue() {
return true;
}
/**
* For multi-value numeric properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
*/
public abstract static class Numeric<V, T extends MultiNumericPropertyBuilder<V, T>>
extends MultiValue<V, T> {
protected Numeric(Class<V> valueType, ValueParser<V> parser) {
super(valueType, parser);
}
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
V min = parser.valueOf(fields.get(PropertyDescriptorField.MIN));
V max = parser.valueOf(fields.get(PropertyDescriptorField.MAX));
builder.range(min, max);
}
}
/**
* For multi-value packaged properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
*/
public abstract static class Packaged<V, T extends MultiPackagedPropertyBuilder<V, T>>
extends MultiValue<V, T> {
protected Packaged(Class<V> valueType, ValueParser<V> parser) {
super(valueType, parser);
}
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
builder.legalPackages(legalPackageNamesIn(fields, PropertyDescriptorBuilderConversionWrapper.delimiterIn(fields,
MultiValuePropertyDescriptor.DEFAULT_DELIMITER)));
}
}
}
/**
* For single-value properties.
*
* @param <E> Value type of the property
* @param <T> Concrete type of the underlying builder
*/
public abstract static class SingleValue<E, T extends SingleValuePropertyBuilder<E, T>>
extends PropertyDescriptorBuilderConversionWrapper<E, T> {
protected final ValueParser<E> parser;
protected SingleValue(Class<E> valueType, ValueParser<E> parser) {
super(valueType);
this.parser = parser;
}
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
builder.defaultValue(parser.valueOf(fields.get(PropertyDescriptorField.DEFAULT_VALUE)));
}
@Override
public boolean isMultiValue() {
return false;
}
/**
* For single-value numeric properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
*/
public abstract static class Numeric<V, T extends SingleNumericPropertyBuilder<V, T>>
extends SingleValue<V, T> {
protected Numeric(Class<V> valueType, ValueParser<V> parser) {
super(valueType, parser);
}
// CPD-OFF - same code in the multi-valued variant
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
V min = parser.valueOf(fields.get(PropertyDescriptorField.MIN));
V max = parser.valueOf(fields.get(PropertyDescriptorField.MAX));
builder.range(min, max);
}
// CPD-ON
}
/**
* For single-value packaged properties.
*
* @param <E> Element type of the list
* @param <T> Concrete type of the underlying builder
*/
public abstract static class Packaged<E, T extends SinglePackagedPropertyBuilder<E, T>>
extends SingleValue<E, T> {
protected Packaged(Class<E> valueType, ValueParser<E> parser) {
super(valueType, parser);
}
@Override
protected void populate(T builder, Map<PropertyDescriptorField, String> fields) {
super.populate(builder, fields);
builder.legalPackageNames(legalPackageNamesIn(fields, PropertyDescriptorBuilderConversionWrapper.delimiterIn(fields,
MultiValuePropertyDescriptor.DEFAULT_DELIMITER)));
}
}
}
}
| 8,612 | 31.625 | 132 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/SingleNumericPropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
/**
* @author Clément Fournier
* @since 6.0.0
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
*/
@Deprecated
public abstract class SingleNumericPropertyBuilder<V, T extends SingleNumericPropertyBuilder<V, T>>
extends SingleValuePropertyBuilder<V, T> {
protected V lowerLimit;
protected V upperLimit;
public SingleNumericPropertyBuilder(String name) {
super(name);
}
/**
* Specify the range of acceptable values.
*
* @param min Lower bound
* @param max Upper bound
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T range(V min, V max) {
this.lowerLimit = min;
this.upperLimit = max;
return (T) this;
}
}
| 922 | 20.97619 | 99 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/MultiNumericPropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import net.sourceforge.pmd.properties.MultiValuePropertyDescriptor;
/**
* For multi-value numeric properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
*/
@Deprecated
public abstract class MultiNumericPropertyBuilder<V, T extends MultiNumericPropertyBuilder<V, T>>
extends MultiValuePropertyBuilder<V, T> {
protected V lowerLimit;
protected V upperLimit;
protected MultiNumericPropertyBuilder(String name) {
super(name);
multiValueDelimiter = MultiValuePropertyDescriptor.DEFAULT_NUMERIC_DELIMITER;
}
/**
* Specify the range of acceptable values.
*
* @param min Lower bound, inclusive
* @param max Upper bound, inclusive
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T range(V min, V max) {
this.lowerLimit = min;
this.upperLimit = max;
return (T) this;
}
}
| 1,190 | 23.8125 | 97 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/PropertyDescriptorBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import org.apache.commons.lang3.StringUtils;
import net.sourceforge.pmd.properties.PropertyBuilder;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* Base class for property builders.
*
* @param <E> Value type of the built descriptor
* @param <T> Concrete type of this builder instance. Removes code duplication at the expense of a few unchecked casts.
* Everything goes well if this parameter's value is correctly set.
*
* @deprecated From 7.0.0 on, the only supported way to build properties will be through {@link PropertyFactory}.
* This class hierarchy is replaced by the newer {@link PropertyBuilder}.
* @author Clément Fournier
* @since 6.0.0
*/
@Deprecated
public abstract class PropertyDescriptorBuilder<E, T extends PropertyDescriptorBuilder<E, T>> {
protected String name;
protected String description;
protected float uiOrder = 0f;
protected boolean isDefinedInXML = false;
protected PropertyDescriptorBuilder(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Name must be provided");
}
this.name = name;
}
/**
* Specify the description of the property.
*
* @param desc The description
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T desc(String desc) {
if (StringUtils.isBlank(desc)) {
throw new IllegalArgumentException("Description must be provided");
}
this.description = desc;
return (T) this;
}
/**
* Specify the UI order of the property.
*
* @param f The UI order
*
* @return The same builder
* @deprecated See {@link PropertyDescriptor#uiOrder()}
*/
@SuppressWarnings("unchecked")
@Deprecated
public T uiOrder(float f) {
this.uiOrder = f;
return (T) this;
}
/**
* Builds the descriptor and returns it.
*
* @return The built descriptor
* @throws IllegalArgumentException if parameters are incorrect
*/
public abstract PropertyDescriptor<E> build();
/**
* Returns the name of the property to be built.
*/
public String getName() {
return name;
}
}
| 2,465 | 25.516129 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/PropertyDescriptorExternalBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import java.util.Map;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyDescriptorField;
/**
* Builds properties from a map of key value pairs, eg extracted from an XML element.
*
* @param <E> The type of values.
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
* @author Clément Fournier
* @since 6.0.0
* @deprecated The property XML API will not need this anymore
*/
@Deprecated
public interface PropertyDescriptorExternalBuilder<E> {
/**
* Whether this descriptor is multi-valued.
*
* @return True if this descriptor is multi-valued
*/
boolean isMultiValue();
/**
* Type of the values of the descriptor, or component type if this descriptor is multi-valued.
*
* @return Type of the values
*/
Class<?> valueType();
/**
* Builds a descriptor. The descriptor returned is tagged as built externally.
*
* @param fields Key value pairs
*
* @return A builder
*/
PropertyDescriptor<E> build(Map<PropertyDescriptorField, String> fields);
}
| 1,282 | 23.673077 | 98 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/MultiPackagedPropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import java.util.Arrays;
/**
* @author Clément Fournier
* @since 6.0.0
*
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
*/
@Deprecated
public abstract class MultiPackagedPropertyBuilder<V, T extends MultiPackagedPropertyBuilder<V, T>>
extends MultiValuePropertyBuilder<V, T> {
protected String[] legalPackageNames;
protected MultiPackagedPropertyBuilder(String name) {
super(name);
}
@SuppressWarnings("unchecked")
public T legalPackages(String[] packs) {
if (packs != null) {
this.legalPackageNames = Arrays.copyOf(packs, packs.length);
}
return (T) this;
}
}
| 834 | 21.567568 | 99 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/MultiValuePropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import net.sourceforge.pmd.properties.MultiValuePropertyDescriptor;
/**
* For multi-value properties.
*
* @param <V> Element type of the list
* @param <T> Concrete type of the underlying builder
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
*/
@Deprecated
public abstract class MultiValuePropertyBuilder<V, T extends MultiValuePropertyBuilder<V, T>>
extends PropertyDescriptorBuilder<List<V>, T> {
protected List<V> defaultValues;
protected char multiValueDelimiter = MultiValuePropertyDescriptor.DEFAULT_DELIMITER;
protected MultiValuePropertyBuilder(String name) {
super(name);
}
/**
* Specify a default value.
*
* @param val List of values
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T defaultValues(Collection<? extends V> val) {
this.defaultValues = new ArrayList<>(val);
return (T) this;
}
/**
* Specify default values.
*
* @param val List of values
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T defaultValues(V... val) {
this.defaultValues = Arrays.asList(val);
return (T) this;
}
/**
* Specify a delimiter character. By default it's {@link MultiValuePropertyDescriptor#DEFAULT_DELIMITER}, or {@link
* MultiValuePropertyDescriptor#DEFAULT_NUMERIC_DELIMITER} for numeric properties.
*
* @param delim Delimiter
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T delim(char delim) {
this.multiValueDelimiter = delim;
return (T) this;
}
}
| 1,942 | 24.233766 | 119 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/SinglePackagedPropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
import java.util.Arrays;
import java.util.Collection;
/**
* @author Clément Fournier
* @since 6.0.0
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
*/
@Deprecated
public abstract class SinglePackagedPropertyBuilder<V, T extends SinglePackagedPropertyBuilder<V, T>>
extends SingleValuePropertyBuilder<V, T> {
protected String[] legalPackageNames;
public SinglePackagedPropertyBuilder(String name) {
super(name);
}
/**
* Specify the allowed package prefixes.
*
* @param packs The package prefixes
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T legalPackageNames(String... packs) {
if (packs != null) {
this.legalPackageNames = Arrays.copyOf(packs, packs.length);
}
return (T) this;
}
/**
* Specify the allowed package prefixes.
*
* @param packs The package prefixes
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T legalPackageNames(Collection<String> packs) {
if (packs != null) {
this.legalPackageNames = packs.toArray(new String[0]);
}
return (T) this;
}
}
| 1,393 | 22.233333 | 101 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/properties/builders/SingleValuePropertyBuilder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties.builders;
/**
* For single-value property descriptors.
*
* @deprecated see {@link net.sourceforge.pmd.properties.builders.PropertyDescriptorBuilder}
* @param <E> Value type of the built descriptor
* @param <T> Concrete type of this builder instance.
*/
@Deprecated
public abstract class SingleValuePropertyBuilder<E, T extends SingleValuePropertyBuilder<E, T>>
extends PropertyDescriptorBuilder<E, T> {
protected E defaultValue;
protected SingleValuePropertyBuilder(String name) {
super(name);
}
/**
* Specify a default value.
*
* @param val Value
*
* @return The same builder
*/
@SuppressWarnings("unchecked")
public T defaultValue(E val) {
this.defaultValue = val;
return (T) this;
}
}
| 916 | 21.365854 | 95 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.reporting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* An initializer for {@link GlobalAnalysisListener} that gets notified of
* general analysis parameters.
*
* <p>Each method will be called exactly once, before any events on the
* {@link GlobalAnalysisListener}. The order of calls is unspecified,
* except that {@link #close()} is called last, and before
* {@link GlobalAnalysisListener#startFileAnalysis(TextFile)} is called
* for the first time.
*/
public interface ListenerInitializer extends AutoCloseable {
/**
* Notifies the total number of files collected for analysis.
*/
default void setNumberOfFilesToAnalyze(int totalFiles) {
// noop
}
/**
* Notify this listener that the given {@link FileNameRenderer} will
* be used by default for this analysis. This is mostly only relevant
* for {@link Renderer} listeners.
*
* @param fileNameRenderer The renderer
*/
default void setFileNameRenderer(FileNameRenderer fileNameRenderer) {
// noop
}
/**
* Signals the end of initialization: no further calls will be made
* to this object.
*
* @throws Exception If an exception occurs, eg IOException when writing to a renderer
*/
@Override
default void close() throws Exception {
// by default do nothing
}
/**
* A listener that does nothing.
*/
static ListenerInitializer noop() {
return NoopListenerInitializer.INSTANCE;
}
/**
* Produce an analysis listener that forwards all events to the given
* listeners.
*
* @param listeners Listeners
*
* @return A new listener
*
* @throws IllegalArgumentException If the parameter is empty
* @throws NullPointerException If the parameter or any of its elements is null
*/
@SuppressWarnings("PMD.CloseResource")
static ListenerInitializer tee(Collection<? extends ListenerInitializer> listeners) {
AssertionUtil.requireParamNotNull("Listeners", listeners);
AssertionUtil.requireNotEmpty("Listeners", listeners);
AssertionUtil.requireContainsNoNullValue("Listeners", listeners);
List<ListenerInitializer> list = new ArrayList<>(listeners);
list.removeIf(it -> it == NoopListenerInitializer.INSTANCE);
if (list.isEmpty()) {
return noop();
} else if (list.size() == 1) {
return list.iterator().next();
}
class TeeListener implements ListenerInitializer {
@Override
public void setNumberOfFilesToAnalyze(int totalFiles) {
for (ListenerInitializer initializer : list) {
initializer.setNumberOfFilesToAnalyze(totalFiles);
}
}
@Override
public void setFileNameRenderer(FileNameRenderer fileNameRenderer) {
for (ListenerInitializer initializer : list) {
initializer.setFileNameRenderer(fileNameRenderer);
}
}
@Override
public void close() throws Exception {
Exception composed = IOUtil.closeAll(list);
if (composed != null) {
throw composed;
}
}
@Override
public String toString() {
return "Tee" + list;
}
}
return new TeeListener();
}
}
| 3,822 | 29.584 | 90 | java |
pmd | pmd-master/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileAnalysisListener.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.reporting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.util.AssertionUtil;
/**
* A handler for events occuring during analysis of a single file. Instances
* are only used on a single thread for their entire lifetime, so don't
* need to be synchronized to access state they own. File listeners are
* spawned by a {@link GlobalAnalysisListener}.
*
* <p>Listeners are assumed to be ready to receive events as soon as they
* are constructed.
*
* @see Report.ReportBuilderListener
*/
public interface FileAnalysisListener extends AutoCloseable {
/**
* Handle a new violation (not suppressed).
*/
void onRuleViolation(RuleViolation violation);
/**
* Handle a new suppressed violation.
*/
default void onSuppressedRuleViolation(SuppressedViolation violation) {
// by default do nothing
}
/**
* Handle an error that occurred while processing a file.
*/
default void onError(ProcessingError error) {
// by default do nothing
}
/**
* Signals the end of the analysis: no further calls will be made
* to this listener. This is run in the thread the listener has
* been used in. This means, if this routine merges some state
* into some global state of the {@link GlobalAnalysisListener),
* then that must be synchronized.
*
* @throws Exception If an exception occurs, eg IOException when writing to a renderer
*/
@Override
default void close() throws Exception {
// by default do nothing
}
/**
* A listener that does nothing.
*/
static FileAnalysisListener noop() {
return NoopFileListener.INSTANCE;
}
/**
* Produce an analysis listener that forwards all events to the given
* listeners.
*
* @param listeners Listeners
*
* @return A new listener
*
* @throws IllegalArgumentException If the parameter is empty
* @throws NullPointerException If the parameter or any of its elements is null
*/
@SuppressWarnings("PMD.CloseResource")
static FileAnalysisListener tee(Collection<? extends FileAnalysisListener> listeners) {
AssertionUtil.requireParamNotNull("Listeners", listeners);
AssertionUtil.requireNotEmpty("Listeners", listeners);
AssertionUtil.requireContainsNoNullValue("Listeners", listeners);
List<FileAnalysisListener> list = new ArrayList<>(listeners);
list.removeIf(it -> it == NoopFileListener.INSTANCE);
if (list.isEmpty()) {
return noop();
} else if (list.size() == 1) {
return list.iterator().next();
}
class TeeListener implements FileAnalysisListener {
@Override
public void onRuleViolation(RuleViolation violation) {
for (FileAnalysisListener it : list) {
it.onRuleViolation(violation);
}
}
@Override
public void onSuppressedRuleViolation(SuppressedViolation violation) {
for (FileAnalysisListener it : list) {
it.onSuppressedRuleViolation(violation);
}
}
@Override
public void onError(ProcessingError error) {
for (FileAnalysisListener it : list) {
it.onError(error);
}
}
@Override
public void close() throws Exception {
Exception composed = IOUtil.closeAll(list);
if (composed != null) {
throw composed;
}
}
@Override
public String toString() {
return "Tee" + list;
}
}
return new TeeListener();
}
}
| 4,225 | 28.347222 | 91 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.