net.sourceforge.pmd.Rule类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(15.0k)|赞(0)|评价(0)|浏览(148)

本文整理了Java中net.sourceforge.pmd.Rule类的一些代码示例,展示了Rule类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Rule类的具体详情如下:
包路径:net.sourceforge.pmd.Rule
类名称:Rule

Rule介绍

[英]This is the basic Rule interface for PMD rules.

Thread safety: PMD will create one instance of a rule per thread. The instances are not shared across different threads. However, a single rule instance is reused for analyzing multiple files.
[中]这是PMD规则的基本规则接口。
线程安全:PMD将为每个线程创建一个规则实例。这些实例不会在不同的线程之间共享。但是,一个规则实例被重新用于分析多个文件。

代码示例

代码示例来源:origin: pmd/pmd

private void glomConfigurationErrors(final Writer writer, final List<ConfigurationError> configErrors) throws IOException {
  if (configErrors.isEmpty()) {
    return;
  }
  writer.write("<hr/>");
  writer.write("<center><h3>Configuration errors</h3></center>");
  writer.write("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>" + PMD.EOL
      + "<th>Rule</th><th>Problem</th></tr>" + PMD.EOL);
  StringBuilder buf = new StringBuilder(500);
  boolean colorize = true;
  for (Report.ConfigurationError ce : configErrors) {
    buf.setLength(0);
    buf.append("<tr");
    if (colorize) {
      buf.append(" bgcolor=\"lightgrey\"");
    }
    colorize = !colorize;
    buf.append("> " + PMD.EOL);
    buf.append("<td>" + ce.rule().getName() + "</td>" + PMD.EOL);
    buf.append("<td>" + ce.issue() + "</td>" + PMD.EOL);
    buf.append("</tr>" + PMD.EOL);
    writer.write(buf.toString());
  }
  writer.write("</table>");
}

代码示例来源:origin: pmd/pmd

private <T> String getBody() {
  String result = "## " + rule.getName() + "\\n\\n" + "Since: PMD " + rule.getSince() + "\\n\\n" + "Priority: "
    + rule.getPriority() + "\\n\\n"
    + "[Categories](https://github.com/codeclimate/spec/blob/master/SPEC.md#categories): "
    + Arrays.toString(getCategories()).replaceAll("[\\[\\]]", "") + "\\n\\n"
    + "[Remediation Points](https://github.com/codeclimate/spec/blob/master/SPEC.md#remediation-points): "
    + getRemediationPoints() + "\\n\\n" + cleaned(rule.getDescription());
  if (!rule.getExamples().isEmpty()) {
    result += "\\n\\n### Example:\\n\\n";
    for (String snippet : rule.getExamples()) {
      String exampleSnippet = snippet.replaceAll("\\n", "\\\\n");
      exampleSnippet = exampleSnippet.replaceAll("\\t", "\\\\t");
  if (!rule.getPropertyDescriptors().isEmpty()) {
    result += "\\n\\n### [PMD properties](" + PMD_PROPERTIES_URL + ")\\n\\n";
    result += "Name | Value | Description\\n";
    result += "--- | --- | ---\\n";
    for (PropertyDescriptor<?> property : rule.getPropertyDescriptors()) {
      String propertyName = property.name().replaceAll("\\_", "\\\\_");
      if (INTERNAL_DEV_PROPERTIES.contains(propertyName)) {
      T value = rule.getProperty(typed);
      String propertyValue = typed.asDelimitedString(value);
      if (propertyValue == null) {

代码示例来源:origin: pmd/pmd

@Override
public void apply(List<? extends Node> nodes, RuleContext ctx) {
  rule.apply(nodes, ctx);
}

代码示例来源:origin: pmd/pmd

private int getRemediationPoints() {
  int remediationPoints = REMEDIATION_POINTS_DEFAULT;
  if (rule.hasDescriptor(CODECLIMATE_REMEDIATION_MULTIPLIER)) {
    remediationPoints *= rule.getProperty(CODECLIMATE_REMEDIATION_MULTIPLIER);
  }
  return remediationPoints;
}

代码示例来源:origin: pmd/pmd

/**
 * Code to be executed if the rule is reinitialised.
 *
 * @param rule The rule to reinitialise
 *
 * @return The rule once it has been reinitialised
 */
protected Rule reinitializeRule(Rule rule) {
  return findRule(rule.getRuleSetName(), rule.getName());
}

代码示例来源:origin: pmd/pmd

/**
 * Does any Rule for the given Language use Type Resolution?
 *
 * @param language
 *            The Language.
 * @return <code>true</code> if a Rule for the Language uses Type
 *         Resolution, <code>false</code> otherwise.
 * @deprecated See {@link Rule#isTypeResolution()}
 */
@Deprecated
public boolean usesTypeResolution(Language language) {
  for (Rule r : rules) {
    if (r.getLanguage().equals(language) && r.isTypeResolution()) {
      return true;
    }
  }
  return false;
}

代码示例来源:origin: pmd/pmd

buf.append("\" endcolumn=\"").append(rv.getEndColumn());
buf.append("\" rule=\"");
StringUtil.appendXmlEscaped(buf, rv.getRule().getName(), useUTF8);
buf.append("\" ruleset=\"");
StringUtil.appendXmlEscaped(buf, rv.getRule().getRuleSetName(), useUTF8);
buf.append('"');
maybeAdd("package", rv.getPackageName(), buf);
maybeAdd("method", rv.getMethodName(), buf);
maybeAdd("variable", rv.getVariableName(), buf);
maybeAdd("externalInfoUrl", rv.getRule().getExternalInfoUrl(), buf);
buf.append(" priority=\"");
buf.append(rv.getRule().getPriority().getPriority());
buf.append("\">").append(PMD.EOL);
StringUtil.appendXmlEscaped(buf, rv.getDescription(), useUTF8);
buf.append("</violation>");
buf.append(PMD.EOL);
writer.write(buf.toString());
writer.write("</file>");
writer.write(PMD.EOL);

代码示例来源:origin: pmd/pmd

private void glomRuleViolations(Writer writer, Iterator<RuleViolation> violations) throws IOException {
  StringBuilder buf = new StringBuilder(500);
  while (violations.hasNext()) {
    RuleViolation rv = violations.next();
    buf.setLength(0);
    buf.append("<tr");
    if (colorize) {
      buf.append(" bgcolor=\"lightgrey\"");
    }
    colorize = !colorize;
    buf.append("> " + PMD.EOL);
    buf.append("<td align=\"center\">" + violationCount + "</td>" + PMD.EOL);
    buf.append("<td width=\"*%\">"
        + maybeWrap(StringEscapeUtils.escapeHtml4(rv.getFilename()),
            linePrefix == null ? "" : linePrefix + Integer.toString(rv.getBeginLine()))
        + "</td>" + PMD.EOL);
    buf.append("<td align=\"center\" width=\"5%\">" + Integer.toString(rv.getBeginLine()) + "</td>" + PMD.EOL);
    String d = StringEscapeUtils.escapeHtml4(rv.getDescription());
    String infoUrl = rv.getRule().getExternalInfoUrl();
    if (StringUtils.isNotBlank(infoUrl)) {
      d = "<a href=\"" + infoUrl + "\">" + d + "</a>";
    }
    buf.append("<td width=\"*\">" + d + "</td>" + PMD.EOL);
    buf.append("</tr>" + PMD.EOL);
    writer.write(buf.toString());
    violationCount++;
  }
}

代码示例来源:origin: pmd/pmd

String name = ruleReference.getOverriddenName();
  String ref = ruleReference.getRuleSetReference().getRuleSetFileName() + '/'
      + ruleReference.getRule().getName();
  String message = ruleReference.getOverriddenMessage();
  String externalInfoUrl = ruleReference.getOverriddenExternalInfoUrl();
return createSingleRuleElement(rule instanceof ImmutableLanguage ? null : rule.getLanguage(),
    rule.getMinimumLanguageVersion(), rule.getMaximumLanguageVersion(), rule.isDeprecated(),
    rule.getName(), rule.getSince(), null, rule.getMessage(), rule.getExternalInfoUrl(),
    rule.getRuleClass(), rule.isDfa(), rule.isTypeResolution(), rule.isMultifile(),
    rule.getDescription(),
    rule.getPriority(), rule.getPropertyDescriptors(), rule.getPropertiesByPropertyDescriptor(),
    rule.getExamples());

代码示例来源:origin: pmd/pmd

assertEquals(message + ", Rule name", rule1.getName(), rule2.getName());
assertEquals(message + ", Rule class", rule1.getRuleClass(), rule2.getRuleClass());
assertEquals(message + ", Rule description " + rule1.getName(), rule1.getDescription(),
    rule2.getDescription());
assertEquals(message + ", Rule message", rule1.getMessage(), rule2.getMessage());
assertEquals(message + ", Rule external info url", rule1.getExternalInfoUrl(), rule2.getExternalInfoUrl());
assertEquals(message + ", Rule priority", rule1.getPriority(), rule2.getPriority());
assertEquals(message + ", Rule examples", rule1.getExamples(), rule2.getExamples());
List<PropertyDescriptor<?>> propertyDescriptors1 = rule1.getPropertyDescriptors();
List<PropertyDescriptor<?>> propertyDescriptors2 = rule2.getPropertyDescriptors();
assertEquals(message + ", Rule property descriptor ", propertyDescriptors1, propertyDescriptors2);
for (int j = 0; j < propertyDescriptors1.size(); j++) {
  Object value1 = rule1.getProperty(propertyDescriptors1.get(j));
  Object value2 = rule2.getProperty(propertyDescriptors2.get(j));

代码示例来源:origin: pmd/pmd

lines.add("## " + rule.getName());
lines.add("");
    lines.add("");
    lines.add("This rule has been renamed. Use instead: ["
        + ref.getRule().getName() + "](" + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
    lines.add("");
  } else {
    lines.add("");
    lines.add("The rule has been moved to another ruleset. Use instead: ["
        + ref.getRule().getName() + "](" + otherLink + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
    lines.add("");
if (rule.isDeprecated()) {
  lines.add(DEPRECATION_LABEL);
  lines.add("");
if (rule.getSince() != null) {
  lines.add("**Since:** PMD " + rule.getSince());
  lines.add("");
lines.add("**Priority:** " + rule.getPriority() + " (" + rule.getPriority().getPriority() + ")");
lines.add("");
if (rule.getMinimumLanguageVersion() != null) {
  lines.add("**Minimum Language Version:** "
      + rule.getLanguage().getName() + " " + rule.getMinimumLanguageVersion().getVersion());
  lines.add("");

代码示例来源:origin: pmd/pmd

@Override
public String getName() {
  return rule.getName();
}

代码示例来源:origin: pmd/pmd

Language language = rule.getLanguage();
String group = fileName.substring(fileName.lastIndexOf('/') + 1);
group = group.substring(0, group.indexOf(".xml"));
if (rule.getSince() == null) {
  invalidSinceAttributes++;
  messages += "Rule " + fileName + "/" + rule.getName() + " is missing 'since' attribute" + PMD.EOL;
if (rule.getExternalInfoUrl() == null || "".equalsIgnoreCase(rule.getExternalInfoUrl())) {
  invalidExternalInfoURL++;
  messages += "Rule " + fileName + "/" + rule.getName() + " is missing 'externalInfoURL' attribute"
      + PMD.EOL;
} else {
      + FilenameUtils.getBaseName(fileName)
      + ".html#"
      + rule.getName().toLowerCase(Locale.ROOT);
  if (rule.getExternalInfoUrl() == null
      || !rule.getExternalInfoUrl().matches(expectedExternalInfoURL)) {
    invalidExternalInfoURL++;
    messages += "Rule " + fileName + "/" + rule.getName()
        + " seems to have an invalid 'externalInfoURL' value (" + rule.getExternalInfoUrl()
        + "), it should be:" + expectedExternalInfoURL + PMD.EOL;
    + "." + rule.getName() + "Rule";
if (!rule.getRuleClass().equals(expectedClassName)
    && !validXPathClassNames.contains(rule.getRuleClass())) {
  invalidClassName++;
  messages += "Rule " + fileName + "/" + rule.getName() + " seems to have an invalid 'class' value ("

代码示例来源:origin: pmd/pmd

public void filterRulesByPriority(RulePriority minimumPriority) {
    Iterator<Rule> iterator = rules.iterator();
    while (iterator.hasNext()) {
      Rule rule = iterator.next();
      if (rule.getPriority().compareTo(minimumPriority) > 0) {
        LOG.fine("Removing rule " + rule.getName() + " due to priority: " + rule.getPriority() + " required: " + minimumPriority);
        iterator.remove();
      }
    }
  }
}

代码示例来源:origin: pmd/pmd

public Rule build() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
  Rule rule = (Rule) RuleBuilder.class.getClassLoader().loadClass(clazz).newInstance();
  rule.setName(name);
  rule.setRuleClass(clazz);
  if (rule.getLanguage() == null) {
    rule.setLanguage(language);
  rule.setSince(since);
  rule.setMessage(message);
  rule.setExternalInfoUrl(externalInfoUrl);
  rule.setDeprecated(isDeprecated);
  rule.setDescription(description);
  rule.setPriority(priority == null ? RulePriority.LOW : priority);
    rule.addExample(example);
    rule.setDfa(isUsesDfa);
    rule.setMultifile(isUsesMultifile);
    rule.setTypeResolution(isUsesTyperesolution);
    if (!rule.getPropertyDescriptors().contains(descriptor)) {
      rule.definePropertyDescriptor(descriptor);

代码示例来源:origin: pmd/pmd

/**
 * Add a new rule to this ruleset. Note that this method does not check
 * for duplicates.
 *
 * @param newRule
 *            the rule to be added
 * @return The same builder, for a fluid programming interface
 */
public RuleSetBuilder addRule(final Rule newRule) {
  if (newRule == null) {
    throw new IllegalArgumentException(MISSING_RULE);
  }
  // check for duplicates - adding more than one rule with the same name will
  // be problematic - see #RuleSet.getRuleByName(String)
  for (Rule rule : rules) {
    if (rule.getName().equals(newRule.getName()) && rule.getLanguage() == newRule.getLanguage()) {
      LOG.warning("The rule with name " + newRule.getName() + " is duplicated. "
          + "Future versions of PMD will reject to load such rulesets.");
      break;
    }
  }
  rules.add(newRule);
  return this;
}

代码示例来源:origin: pmd/pmd

/**
 * Creates a new RuleSet containing a single rule.
 *
 * @param rule
 *            The rule being created
 * @return The newly created RuleSet
 */
public RuleSet createSingleRuleRuleSet(final Rule rule) { // TODO make static?
  final long checksum;
  if (rule instanceof XPathRule) {
    checksum = rule.getProperty(XPathRule.XPATH_DESCRIPTOR).hashCode();
  } else {
    // TODO : Is this good enough? all properties' values + rule name
    checksum = rule.getPropertiesByPropertyDescriptor().values().hashCode() * 31 + rule.getName().hashCode();
  }
  final RuleSetBuilder builder = new RuleSetBuilder(checksum)
      .withName(rule.getName())
      .withDescription("RuleSet for " + rule.getName());
  builder.addRule(rule);
  return builder.build();
}

代码示例来源:origin: pmd/pmd

/**
 * Rules are equal if:
 * <ol>
 * <li>They have the same implementation class.</li>
 * <li>They have the same name.</li>
 * <li>They have the same priority.</li>
 * <li>They share the same properties.</li>
 * </ol>
 */
@Override
public boolean equals(Object o) {
  if (o == null) {
    return false; // trivial
  }
  if (this == o) {
    return true; // trivial
  }
  boolean equality = getClass() == o.getClass();
  if (equality) {
    Rule that = (Rule) o;
    equality = getName().equals(that.getName()) && getPriority().equals(that.getPriority())
        && getPropertiesByPropertyDescriptor().equals(that.getPropertiesByPropertyDescriptor());
  }
  return equality;
}

代码示例来源:origin: pmd/pmd

/**
 * Executes the rules in this ruleset against each of the given nodes.
 *
 * @param acuList
 *            the node list, usually the root nodes like compilation units
 * @param ctx
 *            the current context
 */
public void apply(List<? extends Node> acuList, RuleContext ctx) {
  try (TimedOperation to = TimeTracker.startOperation(TimedOperationCategory.RULE)) {
    for (Rule rule : rules) {
      if (!rule.isRuleChain() && applies(rule, ctx.getLanguageVersion())) {
        try (TimedOperation rto = TimeTracker.startOperation(TimedOperationCategory.RULE, rule.getName())) {
          rule.apply(acuList, ctx);
        } catch (RuntimeException e) {
          if (ctx.isIgnoreExceptions()) {
            ctx.getReport().addError(new Report.ProcessingError(e, ctx.getSourceCodeFilename()));
            if (LOG.isLoggable(Level.WARNING)) {
              LOG.log(Level.WARNING, "Exception applying rule " + rule.getName() + " on file "
                  + ctx.getSourceCodeFilename() + ", continuing with next rule", e);
            }
          } else {
            throw e;
          }
        }
      }
    }
  }
}

代码示例来源:origin: org.hudsonci.plugins/pmd

/**
   * Creates the message string to be shown for the specified rule.
   *
   * @param rule
   *            the rule
   * @return the message string to be shown for the specified rule
   */
  private String createMessage(final Rule rule) {
    List<String> examples = rule.getExamples();
    if (!examples.isEmpty()) {
      return rule.getDescription() + "<pre>" + examples.get(0) + "</pre>";
    }
    return rule.getDescription();
  }
}

相关文章