diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PMD.java b/pmd-core/src/main/java/net/sourceforge/pmd/PMD.java index 8af2e793c8..0eda16cd36 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PMD.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PMD.java @@ -380,6 +380,13 @@ public class PMD { */ public static List getApplicableFiles(PMDConfiguration configuration, Set languages) { long startFiles = System.nanoTime(); + List files = internalGetApplicableFiles(configuration, languages); + long endFiles = System.nanoTime(); + Benchmarker.mark(Benchmark.CollectFiles, endFiles - startFiles, 0); + return files; + } + + private static List internalGetApplicableFiles(PMDConfiguration configuration, Set languages) { LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(languages); List files = new ArrayList(); @@ -398,8 +405,6 @@ public class PMD { throw new RuntimeException("Problem with DBURI: " + uriString, ex); } } - long endFiles = System.nanoTime(); - Benchmarker.mark(Benchmark.CollectFiles, endFiles - startFiles, 0); return files; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index d385545ec5..2e65b910f3 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -309,17 +309,15 @@ public class RuleSet { Benchmarker.mark(Benchmark.Rule, rule.getName(), end - start, 1); start = end; } - } catch (Throwable t) { - if (t instanceof ThreadDeath) { - throw (ThreadDeath)t; - } else if (ctx.isIgnoreExceptions()) { + } catch (RuntimeException e) { + if (ctx.isIgnoreExceptions()) { if (LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Exception applying rule " + rule.getName() + " on file " + ctx.getSourceCodeFilename() + ", continuing with next rule", - t); + e); } } else { - throw new RuntimeException(t); + throw e; } } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java index 1de515a616..88fe46ed13 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java @@ -37,524 +37,560 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** - * RuleSetFactory is responsible for creating RuleSet instances from XML content. - * By default Rules will be loaded using the ClassLoader for this class, using - * the {@link RulePriority#LOW} priority, with Rule deprecation warnings off. + * RuleSetFactory is responsible for creating RuleSet instances from XML + * content. By default Rules will be loaded using the ClassLoader for this + * class, using the {@link RulePriority#LOW} priority, with Rule deprecation + * warnings off. */ public class RuleSetFactory { - private static final Logger LOG = Logger.getLogger(RuleSetFactory.class.getName()); + private static final Logger LOG = Logger.getLogger(RuleSetFactory.class.getName()); - private ClassLoader classLoader = RuleSetFactory.class.getClassLoader(); - private RulePriority minimumPriority = RulePriority.LOW; - private boolean warnDeprecated = false; + private ClassLoader classLoader = RuleSetFactory.class.getClassLoader(); + private RulePriority minimumPriority = RulePriority.LOW; + private boolean warnDeprecated = false; - /** - * Set the ClassLoader to use when loading Rules. - * - * @param classLoader The ClassLoader to use. - */ - public void setClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - /** - * Set the minimum rule priority threshold for all Rules which are loaded - * from RuleSets via reference. - * - * @param minimumPriority The minimum priority. - */ - public void setMinimumPriority(RulePriority minimumPriority) { - this.minimumPriority = minimumPriority; - } - - /** - * Set whether warning messages should be logged for usage of deprecated Rules. - * @param warnDeprecated true to log warning messages. - */ - public void setWarnDeprecated(boolean warnDeprecated) { - this.warnDeprecated = warnDeprecated; - } - - /** - * Returns an Iterator of RuleSet objects loaded from descriptions from the - * "rulesets.properties" resource for each Language with Rule support. - * - * @return An Iterator of RuleSet objects. - */ - public Iterator getRegisteredRuleSets() throws RuleSetNotFoundException { - String rulesetsProperties = null; - try { - List ruleSetReferenceIds = new ArrayList(); - for (Language language : LanguageRegistry.findWithRuleSupport()) { - Properties props = new Properties(); - rulesetsProperties = "rulesets/" + language.getTerseName() + "/rulesets.properties"; - props.load(ResourceLoader.loadResourceAsStream(rulesetsProperties)); - String rulesetFilenames = props.getProperty("rulesets.filenames"); - ruleSetReferenceIds.addAll(RuleSetReferenceId.parse(rulesetFilenames)); - } - return createRuleSets(ruleSetReferenceIds).getRuleSetsIterator(); - } catch (IOException ioe) { - throw new RuntimeException("Couldn't find " + rulesetsProperties - + "; please ensure that the rulesets directory is on the classpath. The current classpath is: " - + System.getProperty("java.class.path")); - } - } - - /** - * Create a RuleSets from a comma separated list of RuleSet reference IDs. This is a - * convenience method which calls {@link RuleSetReferenceId#parse(String)}, and then calls - * {@link #createRuleSets(List)}. - * The currently configured ClassLoader is used. - * - * @param referenceString A comma separated list of RuleSet reference IDs. - * @return The new RuleSets. - * @throws RuleSetNotFoundException if unable to find a resource. - */ - public synchronized RuleSets createRuleSets(String referenceString) throws RuleSetNotFoundException { - return createRuleSets(RuleSetReferenceId.parse(referenceString)); - } - - /** - * Create a RuleSets from a list of RuleSetReferenceIds. - * The currently configured ClassLoader is used. - * - * @param ruleSetReferenceIds The List of RuleSetReferenceId of the RuleSets to create. - * @return The new RuleSets. - * @throws RuleSetNotFoundException if unable to find a resource. - */ - public synchronized RuleSets createRuleSets(List ruleSetReferenceIds) - throws RuleSetNotFoundException { - RuleSets ruleSets = new RuleSets(); - for (RuleSetReferenceId ruleSetReferenceId : ruleSetReferenceIds) { - RuleSet ruleSet = createRuleSet(ruleSetReferenceId); - ruleSets.addRuleSet(ruleSet); - } - return ruleSets; - } - - /** - * Create a RuleSet from a RuleSet reference ID string. This is a - * convenience method which calls {@link RuleSetReferenceId#parse(String)}, gets the first - * item in the List, and then calls {@link #createRuleSet(RuleSetReferenceId)}. - * The currently configured ClassLoader is used. - * - * @param referenceString A comma separated list of RuleSet reference IDs. - * @return A new RuleSet. - * @throws RuleSetNotFoundException if unable to find a resource. - */ - public synchronized RuleSet createRuleSet(String referenceString) throws RuleSetNotFoundException { - List references = RuleSetReferenceId.parse(referenceString); - if (references.isEmpty()) { - throw new RuleSetNotFoundException("No RuleSetReferenceId can be parsed from the string: <" - + referenceString + ">"); - } - return createRuleSet(references.get(0)); - } - - /** - * Create a RuleSet from a RuleSetReferenceId. Priority filtering is ignored when loading - * a single Rule. - * The currently configured ClassLoader is used. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet to create. - * @return A new RuleSet. - * @throws RuleSetNotFoundException if unable to find a resource. - */ - public synchronized RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId) throws RuleSetNotFoundException { - return createRuleSet(ruleSetReferenceId, false); - } - - private synchronized RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { - return parseRuleSetNode(ruleSetReferenceId, ruleSetReferenceId.getInputStream(this.classLoader), withDeprecatedRuleReferences); + /** + * Set the ClassLoader to use when loading Rules. + * + * @param classLoader The ClassLoader to use. + */ + public void setClassLoader(ClassLoader classLoader) { + this.classLoader = classLoader; } - /** - * Create a Rule from a RuleSet created from a file name resource. - * The currently configured ClassLoader is used. - *

- * Any Rules in the RuleSet other than the one being created, are _not_ created. - * Deprecated rules are _not_ ignored, so that they can be referenced. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet with the Rule to create. - * @param withDeprecatedRuleReferences Whether RuleReferences that are deprecated should be ignored or not - * @return A new Rule. - * @throws RuleSetNotFoundException if unable to find a resource. - */ - private Rule createRule(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { - if (ruleSetReferenceId.isAllRules()) { - throw new IllegalArgumentException("Cannot parse a single Rule from an all Rule RuleSet reference: <" - + ruleSetReferenceId + ">."); - } - RuleSet ruleSet = createRuleSet(ruleSetReferenceId, withDeprecatedRuleReferences); - return ruleSet.getRuleByName(ruleSetReferenceId.getRuleName()); - } - /** - * Parse a ruleset node to construct a RuleSet. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed. - * @param inputStream InputStream containing the RuleSet XML configuration. - * @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored or not - * @return The new RuleSet. - */ - private RuleSet parseRuleSetNode(RuleSetReferenceId ruleSetReferenceId, InputStream inputStream, boolean withDeprecatedRuleReferences) { - if (!ruleSetReferenceId.isExternal()) { - throw new IllegalArgumentException("Cannot parse a RuleSet from a non-external reference: <" - + ruleSetReferenceId + ">."); - } - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document document = builder.parse(inputStream); - Element ruleSetElement = document.getDocumentElement(); + /** + * Set the minimum rule priority threshold for all Rules which are loaded + * from RuleSets via reference. + * + * @param minimumPriority The minimum priority. + */ + public void setMinimumPriority(RulePriority minimumPriority) { + this.minimumPriority = minimumPriority; + } - RuleSet ruleSet = new RuleSet(); - ruleSet.setFileName(ruleSetReferenceId.getRuleSetFileName()); - ruleSet.setName(ruleSetElement.getAttribute("name")); + /** + * Set whether warning messages should be logged for usage of deprecated + * Rules. + * + * @param warnDeprecated true to log warning messages. + */ + public void setWarnDeprecated(boolean warnDeprecated) { + this.warnDeprecated = warnDeprecated; + } - NodeList nodeList = ruleSetElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - String nodeName = node.getNodeName(); - if ("description".equals(nodeName)) { - ruleSet.setDescription(parseTextNode(node)); - } else if ("include-pattern".equals(nodeName)) { - ruleSet.addIncludePattern(parseTextNode(node)); - } else if ("exclude-pattern".equals(nodeName)) { - ruleSet.addExcludePattern(parseTextNode(node)); - } else if ("rule".equals(nodeName)) { - parseRuleNode(ruleSetReferenceId, ruleSet, node, withDeprecatedRuleReferences); - } else { - throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() - + "> encountered as child of element."); - } - } - } + /** + * Returns an Iterator of RuleSet objects loaded from descriptions from the + * "rulesets.properties" resource for each Language with Rule support. + * + * @return An Iterator of RuleSet objects. + */ + public Iterator getRegisteredRuleSets() throws RuleSetNotFoundException { + String rulesetsProperties = null; + try { + List ruleSetReferenceIds = new ArrayList(); + for (Language language : LanguageRegistry.findWithRuleSupport()) { + Properties props = new Properties(); + rulesetsProperties = "rulesets/" + language.getTerseName() + "/rulesets.properties"; + props.load(ResourceLoader.loadResourceAsStream(rulesetsProperties)); + String rulesetFilenames = props.getProperty("rulesets.filenames"); + ruleSetReferenceIds.addAll(RuleSetReferenceId.parse(rulesetFilenames)); + } + return createRuleSets(ruleSetReferenceIds).getRuleSetsIterator(); + } catch (IOException ioe) { + throw new RuntimeException("Couldn't find " + rulesetsProperties + + "; please ensure that the rulesets directory is on the classpath. The current classpath is: " + + System.getProperty("java.class.path")); + } + } - return ruleSet; - } catch (ClassNotFoundException cnfe) { - return classNotFoundProblem(cnfe); - } catch (InstantiationException ie) { - return classNotFoundProblem(ie); - } catch (IllegalAccessException iae) { - return classNotFoundProblem(iae); - } catch (ParserConfigurationException pce) { - return classNotFoundProblem(pce); - } catch (RuleSetNotFoundException rsnfe) { - return classNotFoundProblem(rsnfe); - } catch (IOException ioe) { - return classNotFoundProblem(ioe); - } catch (SAXException se) { - return classNotFoundProblem(se); - } - } + /** + * Create a RuleSets from a comma separated list of RuleSet reference IDs. + * This is a convenience method which calls + * {@link RuleSetReferenceId#parse(String)}, and then calls + * {@link #createRuleSets(List)}. The currently configured ClassLoader is + * used. + * + * @param referenceString A comma separated list of RuleSet reference IDs. + * @return The new RuleSets. + * @throws RuleSetNotFoundException if unable to find a resource. + */ + public synchronized RuleSets createRuleSets(String referenceString) throws RuleSetNotFoundException { + return createRuleSets(RuleSetReferenceId.parse(referenceString)); + } - private static RuleSet classNotFoundProblem(Exception ex) throws RuntimeException { - ex.printStackTrace(); - throw new RuntimeException("Couldn't find the class " + ex.getMessage()); - } + /** + * Create a RuleSets from a list of RuleSetReferenceIds. The currently + * configured ClassLoader is used. + * + * @param ruleSetReferenceIds The List of RuleSetReferenceId of the RuleSets + * to create. + * @return The new RuleSets. + * @throws RuleSetNotFoundException if unable to find a resource. + */ + public synchronized RuleSets createRuleSets(List ruleSetReferenceIds) + throws RuleSetNotFoundException { + RuleSets ruleSets = new RuleSets(); + for (RuleSetReferenceId ruleSetReferenceId : ruleSetReferenceIds) { + RuleSet ruleSet = createRuleSet(ruleSetReferenceId); + ruleSets.addRuleSet(ruleSet); + } + return ruleSets; + } - /** - * Parse a rule node. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed. - * @param ruleSet The RuleSet being constructed. - * @param ruleNode Must be a rule element node. - * @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored or not - */ - private void parseRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, boolean withDeprecatedRuleReferences) - throws ClassNotFoundException, InstantiationException, IllegalAccessException, RuleSetNotFoundException { - Element ruleElement = (Element) ruleNode; - String ref = ruleElement.getAttribute("ref"); - if (ref.endsWith("xml")) { - parseRuleSetReferenceNode(ruleSetReferenceId, ruleSet, ruleElement, ref); - } else if (StringUtil.isEmpty(ref)) { - parseSingleRuleNode(ruleSetReferenceId, ruleSet, ruleNode); - } else { - parseRuleReferenceNode(ruleSetReferenceId, ruleSet, ruleNode, ref, withDeprecatedRuleReferences); - } - } + /** + * Create a RuleSet from a RuleSet reference ID string. This is a + * convenience method which calls {@link RuleSetReferenceId#parse(String)}, + * gets the first item in the List, and then calls + * {@link #createRuleSet(RuleSetReferenceId)}. The currently configured + * ClassLoader is used. + * + * @param referenceString A comma separated list of RuleSet reference IDs. + * @return A new RuleSet. + * @throws RuleSetNotFoundException if unable to find a resource. + */ + public synchronized RuleSet createRuleSet(String referenceString) throws RuleSetNotFoundException { + List references = RuleSetReferenceId.parse(referenceString); + if (references.isEmpty()) { + throw new RuleSetNotFoundException("No RuleSetReferenceId can be parsed from the string: <" + + referenceString + ">"); + } + return createRuleSet(references.get(0)); + } - /** - * Parse a rule node as an RuleSetReference for all Rules. Every Rule from - * the referred to RuleSet will be added as a RuleReference except for those - * explicitly excluded, below the minimum priority threshold for this - * RuleSetFactory, or which are deprecated. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed. - * @param ruleSet The RuleSet being constructed. - * @param ruleElement Must be a rule element node. - * @param ref The RuleSet reference. - */ - private void parseRuleSetReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Element ruleElement, - String ref) throws RuleSetNotFoundException { - RuleSetReference ruleSetReference = new RuleSetReference(); - ruleSetReference.setAllRules(true); - ruleSetReference.setRuleSetFileName(ref); - String priority = null; - NodeList childNodes = ruleElement.getChildNodes(); - Set excludedRulesCheck = new HashSet(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node child = childNodes.item(i); - if (isElementNode(child,"exclude")) { - Element excludeElement = (Element) child; - String excludedRuleName = excludeElement.getAttribute("name"); + /** + * Create a RuleSet from a RuleSetReferenceId. Priority filtering is ignored + * when loading a single Rule. The currently configured ClassLoader is used. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet to + * create. + * @return A new RuleSet. + * @throws RuleSetNotFoundException if unable to find a resource. + */ + public synchronized RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId) throws RuleSetNotFoundException { + return createRuleSet(ruleSetReferenceId, false); + } + + private synchronized RuleSet createRuleSet(RuleSetReferenceId ruleSetReferenceId, + boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { + return parseRuleSetNode(ruleSetReferenceId, ruleSetReferenceId.getInputStream(this.classLoader), + withDeprecatedRuleReferences); + } + + /** + * Create a Rule from a RuleSet created from a file name resource. The + * currently configured ClassLoader is used. + *

+ * Any Rules in the RuleSet other than the one being created, are _not_ + * created. Deprecated rules are _not_ ignored, so that they can be + * referenced. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet with the + * Rule to create. + * @param withDeprecatedRuleReferences Whether RuleReferences that are + * deprecated should be ignored or not + * @return A new Rule. + * @throws RuleSetNotFoundException if unable to find a resource. + */ + private Rule createRule(RuleSetReferenceId ruleSetReferenceId, boolean withDeprecatedRuleReferences) + throws RuleSetNotFoundException { + if (ruleSetReferenceId.isAllRules()) { + throw new IllegalArgumentException("Cannot parse a single Rule from an all Rule RuleSet reference: <" + + ruleSetReferenceId + ">."); + } + RuleSet ruleSet = createRuleSet(ruleSetReferenceId, withDeprecatedRuleReferences); + return ruleSet.getRuleByName(ruleSetReferenceId.getRuleName()); + } + + /** + * Parse a ruleset node to construct a RuleSet. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being + * parsed. + * @param inputStream InputStream containing the RuleSet XML configuration. + * @param withDeprecatedRuleReferences whether rule references that are + * deprecated should be ignored or not + * @return The new RuleSet. + */ + private RuleSet parseRuleSetNode(RuleSetReferenceId ruleSetReferenceId, InputStream inputStream, + boolean withDeprecatedRuleReferences) { + if (!ruleSetReferenceId.isExternal()) { + throw new IllegalArgumentException("Cannot parse a RuleSet from a non-external reference: <" + + ruleSetReferenceId + ">."); + } + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document document = builder.parse(inputStream); + Element ruleSetElement = document.getDocumentElement(); + + RuleSet ruleSet = new RuleSet(); + ruleSet.setFileName(ruleSetReferenceId.getRuleSetFileName()); + ruleSet.setName(ruleSetElement.getAttribute("name")); + + NodeList nodeList = ruleSetElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + String nodeName = node.getNodeName(); + if ("description".equals(nodeName)) { + ruleSet.setDescription(parseTextNode(node)); + } else if ("include-pattern".equals(nodeName)) { + ruleSet.addIncludePattern(parseTextNode(node)); + } else if ("exclude-pattern".equals(nodeName)) { + ruleSet.addExcludePattern(parseTextNode(node)); + } else if ("rule".equals(nodeName)) { + parseRuleNode(ruleSetReferenceId, ruleSet, node, withDeprecatedRuleReferences); + } else { + throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() + + "> encountered as child of element."); + } + } + } + + return ruleSet; + } catch (ClassNotFoundException cnfe) { + return classNotFoundProblem(cnfe); + } catch (InstantiationException ie) { + return classNotFoundProblem(ie); + } catch (IllegalAccessException iae) { + return classNotFoundProblem(iae); + } catch (ParserConfigurationException pce) { + return classNotFoundProblem(pce); + } catch (RuleSetNotFoundException rsnfe) { + return classNotFoundProblem(rsnfe); + } catch (IOException ioe) { + return classNotFoundProblem(ioe); + } catch (SAXException se) { + return classNotFoundProblem(se); + } + } + + private static RuleSet classNotFoundProblem(Exception ex) throws RuntimeException { + ex.printStackTrace(); + throw new RuntimeException("Couldn't find the class " + ex.getMessage()); + } + + /** + * Parse a rule node. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being + * parsed. + * @param ruleSet The RuleSet being constructed. + * @param ruleNode Must be a rule element node. + * @param withDeprecatedRuleReferences whether rule references that are + * deprecated should be ignored or not + */ + private void parseRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, + boolean withDeprecatedRuleReferences) throws ClassNotFoundException, InstantiationException, + IllegalAccessException, RuleSetNotFoundException { + Element ruleElement = (Element) ruleNode; + String ref = ruleElement.getAttribute("ref"); + if (ref.endsWith("xml")) { + parseRuleSetReferenceNode(ruleSetReferenceId, ruleSet, ruleElement, ref); + } else if (StringUtil.isEmpty(ref)) { + parseSingleRuleNode(ruleSetReferenceId, ruleSet, ruleNode); + } else { + parseRuleReferenceNode(ruleSetReferenceId, ruleSet, ruleNode, ref, withDeprecatedRuleReferences); + } + } + + /** + * Parse a rule node as an RuleSetReference for all Rules. Every Rule from + * the referred to RuleSet will be added as a RuleReference except for those + * explicitly excluded, below the minimum priority threshold for this + * RuleSetFactory, or which are deprecated. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being + * parsed. + * @param ruleSet The RuleSet being constructed. + * @param ruleElement Must be a rule element node. + * @param ref The RuleSet reference. + */ + private void parseRuleSetReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Element ruleElement, + String ref) throws RuleSetNotFoundException { + RuleSetReference ruleSetReference = new RuleSetReference(); + ruleSetReference.setAllRules(true); + ruleSetReference.setRuleSetFileName(ref); + String priority = null; + NodeList childNodes = ruleElement.getChildNodes(); + Set excludedRulesCheck = new HashSet(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node child = childNodes.item(i); + if (isElementNode(child, "exclude")) { + Element excludeElement = (Element) child; + String excludedRuleName = excludeElement.getAttribute("name"); ruleSetReference.addExclude(excludedRuleName); excludedRulesCheck.add(excludedRuleName); - } else if (isElementNode(child, "priority")) { - priority = parseTextNode(child).trim(); - } - } - - RuleSetFactory ruleSetFactory = new RuleSetFactory(); - ruleSetFactory.setClassLoader(classLoader); - RuleSet otherRuleSet = ruleSetFactory.createRuleSet(RuleSetReferenceId.parse(ref).get(0)); - for (Rule rule : otherRuleSet.getRules()) { - excludedRulesCheck.remove(rule.getName()); - if (!ruleSetReference.getExcludes().contains(rule.getName()) - && rule.getPriority().compareTo(minimumPriority) <= 0 && !rule.isDeprecated()) { - RuleReference ruleReference = new RuleReference(); - ruleReference.setRuleSetReference(ruleSetReference); - ruleReference.setRule(rule); - ruleSet.addRuleIfNotExists(ruleReference); - - // override the priority - if (priority != null) { - ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(priority))); - } - } - } - if (!excludedRulesCheck.isEmpty()) { - throw new IllegalArgumentException("Unable to exclude rules " - + excludedRulesCheck + "; perhaps the rule name is mispelled?"); + } else if (isElementNode(child, "priority")) { + priority = parseTextNode(child).trim(); + } } - } - /** - * Parse a rule node as a single Rule. The Rule has been fully defined within - * the context of the current RuleSet. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed. - * @param ruleSet The RuleSet being constructed. - * @param ruleNode Must be a rule element node. - */ - private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode) - throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Element ruleElement = (Element) ruleNode; + RuleSetFactory ruleSetFactory = new RuleSetFactory(); + ruleSetFactory.setClassLoader(classLoader); + RuleSet otherRuleSet = ruleSetFactory.createRuleSet(RuleSetReferenceId.parse(ref).get(0)); + for (Rule rule : otherRuleSet.getRules()) { + excludedRulesCheck.remove(rule.getName()); + if (!ruleSetReference.getExcludes().contains(rule.getName()) + && rule.getPriority().compareTo(minimumPriority) <= 0 && !rule.isDeprecated()) { + RuleReference ruleReference = new RuleReference(); + ruleReference.setRuleSetReference(ruleSetReference); + ruleReference.setRule(rule); + ruleSet.addRuleIfNotExists(ruleReference); - // Stop if we're looking for a particular Rule, and this element is not it. - if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) - && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { - return; - } + // override the priority + if (priority != null) { + ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(priority))); + } + } + } + if (!excludedRulesCheck.isEmpty()) { + throw new IllegalArgumentException("Unable to exclude rules " + excludedRulesCheck + + "; perhaps the rule name is mispelled?"); + } + } - String attribute = ruleElement.getAttribute("class"); - if ( attribute == null || "".equals(attribute)) { - throw new IllegalArgumentException("The 'class' field of rule can't be null, nor empty."); - } - Rule rule = (Rule) classLoader.loadClass(attribute).newInstance(); - rule.setName(ruleElement.getAttribute("name")); + /** + * Parse a rule node as a single Rule. The Rule has been fully defined + * within the context of the current RuleSet. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being + * parsed. + * @param ruleSet The RuleSet being constructed. + * @param ruleNode Must be a rule element node. + */ + private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { + Element ruleElement = (Element) ruleNode; - if (ruleElement.hasAttribute("language")) { - String languageName = ruleElement.getAttribute("language"); - Language language = LanguageRegistry.findLanguageByTerseName(languageName); - if (language == null) { - throw new IllegalArgumentException("Unknown Language '" + languageName + "' for Rule " + rule.getName() - + ", supported Languages are " - + LanguageRegistry.commaSeparatedTerseNamesForLanguage(LanguageRegistry.findWithRuleSupport())); - } - rule.setLanguage(language); - } + // Stop if we're looking for a particular Rule, and this element is not + // it. + if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) + && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { + return; + } - Language language = rule.getLanguage(); - if (language == null) { - throw new IllegalArgumentException("Rule " + rule.getName() - + " does not have a Language; missing 'language' attribute?"); - } + String attribute = ruleElement.getAttribute("class"); + if (attribute == null || "".equals(attribute)) { + throw new IllegalArgumentException("The 'class' field of rule can't be null, nor empty."); + } + Rule rule = (Rule) classLoader.loadClass(attribute).newInstance(); + rule.setName(ruleElement.getAttribute("name")); - if (ruleElement.hasAttribute("minimumLanguageVersion")) { - String minimumLanguageVersionName = ruleElement.getAttribute("minimumLanguageVersion"); - LanguageVersion minimumLanguageVersion = language.getVersion(minimumLanguageVersionName); - if (minimumLanguageVersion == null) { - throw new IllegalArgumentException("Unknown minimum Language Version '" + minimumLanguageVersionName - + "' for Language '" + language.getTerseName() + "' for Rule " + rule.getName() - + "; supported Language Versions are: " - + LanguageRegistry.commaSeparatedTerseNamesForLanguageVersion(language.getVersions())); - } - rule.setMinimumLanguageVersion(minimumLanguageVersion); - } + if (ruleElement.hasAttribute("language")) { + String languageName = ruleElement.getAttribute("language"); + Language language = LanguageRegistry.findLanguageByTerseName(languageName); + if (language == null) { + throw new IllegalArgumentException("Unknown Language '" + languageName + "' for Rule " + rule.getName() + + ", supported Languages are " + + LanguageRegistry.commaSeparatedTerseNamesForLanguage(LanguageRegistry.findWithRuleSupport())); + } + rule.setLanguage(language); + } - if (ruleElement.hasAttribute("maximumLanguageVersion")) { - String maximumLanguageVersionName = ruleElement.getAttribute("maximumLanguageVersion"); - LanguageVersion maximumLanguageVersion = language.getVersion(maximumLanguageVersionName); - if (maximumLanguageVersion == null) { - throw new IllegalArgumentException("Unknown maximum Language Version '" + maximumLanguageVersionName - + "' for Language '" + language.getTerseName() + "' for Rule " + rule.getName() - + "; supported Language Versions are: " - + LanguageRegistry.commaSeparatedTerseNamesForLanguageVersion(language.getVersions())); - } - rule.setMaximumLanguageVersion(maximumLanguageVersion); - } + Language language = rule.getLanguage(); + if (language == null) { + throw new IllegalArgumentException("Rule " + rule.getName() + + " does not have a Language; missing 'language' attribute?"); + } - if (rule.getMinimumLanguageVersion() != null && rule.getMaximumLanguageVersion() != null) { - throw new IllegalArgumentException("The minimum Language Version '" - + rule.getMinimumLanguageVersion().getTerseName() - + "' must be prior to the maximum Language Version '" - + rule.getMaximumLanguageVersion().getTerseName() + "' for Rule " + rule.getName() - + "; perhaps swap them around?"); - } + if (ruleElement.hasAttribute("minimumLanguageVersion")) { + String minimumLanguageVersionName = ruleElement.getAttribute("minimumLanguageVersion"); + LanguageVersion minimumLanguageVersion = language.getVersion(minimumLanguageVersionName); + if (minimumLanguageVersion == null) { + throw new IllegalArgumentException("Unknown minimum Language Version '" + minimumLanguageVersionName + + "' for Language '" + language.getTerseName() + "' for Rule " + rule.getName() + + "; supported Language Versions are: " + + LanguageRegistry.commaSeparatedTerseNamesForLanguageVersion(language.getVersions())); + } + rule.setMinimumLanguageVersion(minimumLanguageVersion); + } - String since = ruleElement.getAttribute("since"); - if (StringUtil.isNotEmpty(since)) { - rule.setSince(since); - } - rule.setMessage(ruleElement.getAttribute("message")); - rule.setRuleSetName(ruleSet.getName()); - rule.setExternalInfoUrl(ruleElement.getAttribute("externalInfoUrl")); + if (ruleElement.hasAttribute("maximumLanguageVersion")) { + String maximumLanguageVersionName = ruleElement.getAttribute("maximumLanguageVersion"); + LanguageVersion maximumLanguageVersion = language.getVersion(maximumLanguageVersionName); + if (maximumLanguageVersion == null) { + throw new IllegalArgumentException("Unknown maximum Language Version '" + maximumLanguageVersionName + + "' for Language '" + language.getTerseName() + "' for Rule " + rule.getName() + + "; supported Language Versions are: " + + LanguageRegistry.commaSeparatedTerseNamesForLanguageVersion(language.getVersions())); + } + rule.setMaximumLanguageVersion(maximumLanguageVersion); + } - if (hasAttributeSetTrue(ruleElement,"dfa")) { - rule.setUsesDFA(); - } + if (rule.getMinimumLanguageVersion() != null && rule.getMaximumLanguageVersion() != null) { + throw new IllegalArgumentException("The minimum Language Version '" + + rule.getMinimumLanguageVersion().getTerseName() + + "' must be prior to the maximum Language Version '" + + rule.getMaximumLanguageVersion().getTerseName() + "' for Rule " + rule.getName() + + "; perhaps swap them around?"); + } - if (hasAttributeSetTrue(ruleElement,"typeResolution")) { - rule.setUsesTypeResolution(); - } + String since = ruleElement.getAttribute("since"); + if (StringUtil.isNotEmpty(since)) { + rule.setSince(since); + } + rule.setMessage(ruleElement.getAttribute("message")); + rule.setRuleSetName(ruleSet.getName()); + rule.setExternalInfoUrl(ruleElement.getAttribute("externalInfoUrl")); - final NodeList nodeList = ruleElement.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } - String nodeName = node.getNodeName(); - if (nodeName.equals("description")) { - rule.setDescription(parseTextNode(node)); - } else if (nodeName.equals("example")) { - rule.addExample(parseTextNode(node)); - } else if (nodeName.equals("priority")) { - rule.setPriority(RulePriority.valueOf(Integer.parseInt(parseTextNode(node).trim()))); - } else if (nodeName.equals("properties")) { - parsePropertiesNode(rule, node); - } else { - throw new IllegalArgumentException("Unexpected element <" + nodeName - + "> encountered as child of element for Rule " + rule.getName()); - } + if (hasAttributeSetTrue(ruleElement, "dfa")) { + rule.setUsesDFA(); + } - } - if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) || rule.getPriority().compareTo(minimumPriority) <= 0) { - ruleSet.addRule(rule); - } - } + if (hasAttributeSetTrue(ruleElement, "typeResolution")) { + rule.setUsesTypeResolution(); + } - private static boolean hasAttributeSetTrue(Element element, String attributeId) { - return element.hasAttribute(attributeId) && "true".equalsIgnoreCase(element.getAttribute(attributeId)); - } + final NodeList nodeList = ruleElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + String nodeName = node.getNodeName(); + if (nodeName.equals("description")) { + rule.setDescription(parseTextNode(node)); + } else if (nodeName.equals("example")) { + rule.addExample(parseTextNode(node)); + } else if (nodeName.equals("priority")) { + rule.setPriority(RulePriority.valueOf(Integer.parseInt(parseTextNode(node).trim()))); + } else if (nodeName.equals("properties")) { + parsePropertiesNode(rule, node); + } else { + throw new IllegalArgumentException("Unexpected element <" + nodeName + + "> encountered as child of element for Rule " + rule.getName()); + } - /** - * Parse a rule node as a RuleReference. A RuleReference is a single Rule - * which comes from another RuleSet with some of it's attributes potentially - * overridden. - * - * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being parsed. - * @param ruleSet The RuleSet being constructed. - * @param ruleNode Must be a rule element node. - * @param ref A reference to a Rule. - * @param withDeprecatedRuleReferences whether rule references that are deprecated should be ignored or not - */ - private void parseRuleReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, - String ref, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { - Element ruleElement = (Element) ruleNode; - boolean isSameRuleSet = false; + } + if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) + || rule.getPriority().compareTo(minimumPriority) <= 0) { + ruleSet.addRule(rule); + } + } - // Stop if we're looking for a particular Rule, and this element is not it. - if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) - && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { - return; - } + private static boolean hasAttributeSetTrue(Element element, String attributeId) { + return element.hasAttribute(attributeId) && "true".equalsIgnoreCase(element.getAttribute(attributeId)); + } - RuleSetFactory ruleSetFactory = new RuleSetFactory(); - ruleSetFactory.setClassLoader(classLoader); + /** + * Parse a rule node as a RuleReference. A RuleReference is a single Rule + * which comes from another RuleSet with some of it's attributes potentially + * overridden. + * + * @param ruleSetReferenceId The RuleSetReferenceId of the RuleSet being + * parsed. + * @param ruleSet The RuleSet being constructed. + * @param ruleNode Must be a rule element node. + * @param ref A reference to a Rule. + * @param withDeprecatedRuleReferences whether rule references that are + * deprecated should be ignored or not + */ + private void parseRuleReferenceNode(RuleSetReferenceId ruleSetReferenceId, RuleSet ruleSet, Node ruleNode, + String ref, boolean withDeprecatedRuleReferences) throws RuleSetNotFoundException { + Element ruleElement = (Element) ruleNode; - RuleSetReferenceId otherRuleSetReferenceId = RuleSetReferenceId.parse(ref).get(0); - if (!otherRuleSetReferenceId.isExternal() && containsRule(ruleSetReferenceId, otherRuleSetReferenceId.getRuleName())) { - otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId); - isSameRuleSet = true; - } - Rule referencedRule = ruleSetFactory.createRule(otherRuleSetReferenceId, true); // do not ignore deprecated rule references - if (referencedRule == null) { - throw new IllegalArgumentException("Unable to find referenced rule " - + otherRuleSetReferenceId.getRuleName() + "; perhaps the rule name is mispelled?"); - } + // Stop if we're looking for a particular Rule, and this element is not + // it. + if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) + && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { + return; + } - if (warnDeprecated && referencedRule.isDeprecated()) { - if (referencedRule instanceof RuleReference) { - RuleReference ruleReference = (RuleReference) referencedRule; - if (LOG.isLoggable(Level.WARNING)) { - LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + "/" - + ruleReference.getOriginalName() + " instead of the deprecated Rule name " + otherRuleSetReferenceId - + ". Future versions of PMD will remove support for this deprecated Rule name usage."); - } - } else if (referencedRule instanceof MockRule) { + RuleSetFactory ruleSetFactory = new RuleSetFactory(); + ruleSetFactory.setClassLoader(classLoader); + + boolean isSameRuleSet = false; + RuleSetReferenceId otherRuleSetReferenceId = RuleSetReferenceId.parse(ref).get(0); + if (!otherRuleSetReferenceId.isExternal() + && containsRule(ruleSetReferenceId, otherRuleSetReferenceId.getRuleName())) { + otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId); + isSameRuleSet = true; + } + Rule referencedRule = ruleSetFactory.createRule(otherRuleSetReferenceId, true); // do + // not + // ignore + // deprecated + // rule + // references + if (referencedRule == null) { + throw new IllegalArgumentException("Unable to find referenced rule " + + otherRuleSetReferenceId.getRuleName() + "; perhaps the rule name is mispelled?"); + } + + if (warnDeprecated && referencedRule.isDeprecated()) { + if (referencedRule instanceof RuleReference) { + RuleReference ruleReference = (RuleReference) referencedRule; + if (LOG.isLoggable(Level.WARNING)) { + LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + "/" + + ruleReference.getOriginalName() + " instead of the deprecated Rule name " + + otherRuleSetReferenceId + + ". Future versions of PMD will remove support for this deprecated Rule name usage."); + } + } else if (referencedRule instanceof MockRule) { if (LOG.isLoggable(Level.WARNING)) { LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId - + " as it has been removed from PMD and no longer functions." - + " Future versions of PMD will remove support for this Rule."); + + " as it has been removed from PMD and no longer functions." + + " Future versions of PMD will remove support for this Rule."); } - } else { + } else { if (LOG.isLoggable(Level.WARNING)) { LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId - + " as it is scheduled for removal from PMD." - + " Future versions of PMD will remove support for this Rule."); + + " as it is scheduled for removal from PMD." + + " Future versions of PMD will remove support for this Rule."); } - } - } + } + } - RuleSetReference ruleSetReference = new RuleSetReference(); - ruleSetReference.setAllRules(false); - ruleSetReference.setRuleSetFileName(otherRuleSetReferenceId.getRuleSetFileName()); + RuleSetReference ruleSetReference = new RuleSetReference(); + ruleSetReference.setAllRules(false); + ruleSetReference.setRuleSetFileName(otherRuleSetReferenceId.getRuleSetFileName()); - RuleReference ruleReference = new RuleReference(); - ruleReference.setRuleSetReference(ruleSetReference); - ruleReference.setRule(referencedRule); + RuleReference ruleReference = new RuleReference(); + ruleReference.setRuleSetReference(ruleSetReference); + ruleReference.setRule(referencedRule); - if (ruleElement.hasAttribute("deprecated")) { - ruleReference.setDeprecated(Boolean.parseBoolean(ruleElement.getAttribute("deprecated"))); - } - if (ruleElement.hasAttribute("name")) { - ruleReference.setName(ruleElement.getAttribute("name")); - } - if (ruleElement.hasAttribute("message")) { - ruleReference.setMessage(ruleElement.getAttribute("message")); - } - if (ruleElement.hasAttribute("externalInfoUrl")) { - ruleReference.setExternalInfoUrl(ruleElement.getAttribute("externalInfoUrl")); - } - for (int i = 0; i < ruleElement.getChildNodes().getLength(); i++) { - Node node = ruleElement.getChildNodes().item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equals("description")) { - ruleReference.setDescription(parseTextNode(node)); - } else if (node.getNodeName().equals("example")) { - ruleReference.addExample(parseTextNode(node)); - } else if (node.getNodeName().equals("priority")) { - ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(parseTextNode(node)))); - } else if (node.getNodeName().equals("properties")) { - parsePropertiesNode(ruleReference, node); - } else { - throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() - + "> encountered as child of element for Rule " + ruleReference.getName()); - } - } - } + if (ruleElement.hasAttribute("deprecated")) { + ruleReference.setDeprecated(Boolean.parseBoolean(ruleElement.getAttribute("deprecated"))); + } + if (ruleElement.hasAttribute("name")) { + ruleReference.setName(ruleElement.getAttribute("name")); + } + if (ruleElement.hasAttribute("message")) { + ruleReference.setMessage(ruleElement.getAttribute("message")); + } + if (ruleElement.hasAttribute("externalInfoUrl")) { + ruleReference.setExternalInfoUrl(ruleElement.getAttribute("externalInfoUrl")); + } + for (int i = 0; i < ruleElement.getChildNodes().getLength(); i++) { + Node node = ruleElement.getChildNodes().item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equals("description")) { + ruleReference.setDescription(parseTextNode(node)); + } else if (node.getNodeName().equals("example")) { + ruleReference.addExample(parseTextNode(node)); + } else if (node.getNodeName().equals("priority")) { + ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(parseTextNode(node)))); + } else if (node.getNodeName().equals("properties")) { + parsePropertiesNode(ruleReference, node); + } else { + throw new IllegalArgumentException("Unexpected element <" + node.getNodeName() + + "> encountered as child of element for Rule " + ruleReference.getName()); + } + } + } - if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) || referencedRule.getPriority().compareTo( - minimumPriority) <= 0) { + if (StringUtil.isNotEmpty(ruleSetReferenceId.getRuleName()) + || referencedRule.getPriority().compareTo(minimumPriority) <= 0) { if (withDeprecatedRuleReferences || !isSameRuleSet || !ruleReference.isDeprecated()) { ruleSet.addRuleReplaceIfExists(ruleReference); } } - } + } /** * Check whether the given ruleName is contained in the given ruleset. + * * @param ruleSetReferenceId the ruleset to check * @param ruleName the rule name to search for * @return true if the ruleName exists @@ -568,7 +604,7 @@ public class RuleSetFactory { NodeList rules = ruleSetElement.getElementsByTagName("rule"); for (int i = 0; i < rules.getLength(); i++) { - Element rule = (Element)rules.item(i); + Element rule = (Element) rules.item(i); if (rule.hasAttribute("name")) { if (rule.getAttribute("name").equals(ruleName)) { found = true; @@ -584,168 +620,178 @@ public class RuleSetFactory { } private static boolean isElementNode(Node node, String name) { - return node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name); - } - /** - * Parse a properties node. - * - * @param rule The Rule to which the properties should be added. - * @param propertiesNode Must be a properties element node. - */ - private static void parsePropertiesNode(Rule rule, Node propertiesNode) { - for (int i = 0; i < propertiesNode.getChildNodes().getLength(); i++) { - Node node = propertiesNode.getChildNodes().item(i); - if (isElementNode(node, "property")) { - parsePropertyNodeBR(rule, node); - } - } - } + return node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name); + } - private static String valueFrom(Node parentNode) { + /** + * Parse a properties node. + * + * @param rule The Rule to which the properties should be added. + * @param propertiesNode Must be a properties element node. + */ + private static void parsePropertiesNode(Rule rule, Node propertiesNode) { + for (int i = 0; i < propertiesNode.getChildNodes().getLength(); i++) { + Node node = propertiesNode.getChildNodes().item(i); + if (isElementNode(node, "property")) { + parsePropertyNodeBR(rule, node); + } + } + } - final NodeList nodeList = parentNode.getChildNodes(); + private static String valueFrom(Node parentNode) { - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (isElementNode(node, "value")) { - return parseTextNode(node); - } - } - return null; - } + final NodeList nodeList = parentNode.getChildNodes(); - /** - * Parse a property node. - * - * @param rule The Rule to which the property should be added. - * //@param propertyNode Must be a property element node. - */ - @SuppressWarnings("unchecked") -// private static void parsePropertyNode(Rule rule, Node propertyNode) { -// Element propertyElement = (Element) propertyNode; -// String name = propertyElement.getAttribute("name"); -// String description = propertyElement.getAttribute("description"); -// String type = propertyElement.getAttribute("type"); -// String delimiter = propertyElement.getAttribute("delimiter"); -// String min = propertyElement.getAttribute("min"); -// String max = propertyElement.getAttribute("max"); -// String value = propertyElement.getAttribute("value"); -// -// // If value not provided, get from child element. -// if (StringUtil.isEmpty(value)) { -// for (int i = 0; i < propertyNode.getChildNodes().getLength(); i++) { -// Node node = propertyNode.getChildNodes().item(i); -// if ((node.getNodeType() == Node.ELEMENT_NODE) && node.getNodeName().equals("value")) { -// value = parseTextNode(node); -// } -// } -// } -// -// // Setting of existing property, or defining a new property? -// if (StringUtil.isEmpty(type)) { -// PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(name); -// if (propertyDescriptor == null) { -// throw new IllegalArgumentException("Cannot set non-existant property '" + name + "' on Rule " + rule.getName()); -// } else { -// Object realValue = propertyDescriptor.valueFrom(value); -// rule.setProperty(propertyDescriptor, realValue); -// } -// } else { -// PropertyDescriptor propertyDescriptor = PropertyDescriptorFactory.createPropertyDescriptor(name, description, type, delimiter, min, max, value); -// rule.definePropertyDescriptor(propertyDescriptor); -// } -// } + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (isElementNode(node, "value")) { + return parseTextNode(node); + } + } + return null; + } - private static void setValue(Rule rule, PropertyDescriptor desc, String strValue) { - Object realValue = desc.valueFrom(strValue); - rule.setProperty(desc, realValue); - } + /** + * Parse a property node. + * + * @param rule The Rule to which the property should be added. //@param + * propertyNode Must be a property element node. + */ + @SuppressWarnings("unchecked") + // private static void parsePropertyNode(Rule rule, Node propertyNode) { + // Element propertyElement = (Element) propertyNode; + // String name = propertyElement.getAttribute("name"); + // String description = propertyElement.getAttribute("description"); + // String type = propertyElement.getAttribute("type"); + // String delimiter = propertyElement.getAttribute("delimiter"); + // String min = propertyElement.getAttribute("min"); + // String max = propertyElement.getAttribute("max"); + // String value = propertyElement.getAttribute("value"); + // + // // If value not provided, get from child element. + // if (StringUtil.isEmpty(value)) { + // for (int i = 0; i < propertyNode.getChildNodes().getLength(); i++) { + // Node node = propertyNode.getChildNodes().item(i); + // if ((node.getNodeType() == Node.ELEMENT_NODE) && + // node.getNodeName().equals("value")) { + // value = parseTextNode(node); + // } + // } + // } + // + // // Setting of existing property, or defining a new property? + // if (StringUtil.isEmpty(type)) { + // PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(name); + // if (propertyDescriptor == null) { + // throw new IllegalArgumentException("Cannot set non-existant property '" + + // name + "' on Rule " + rule.getName()); + // } else { + // Object realValue = propertyDescriptor.valueFrom(value); + // rule.setProperty(propertyDescriptor, realValue); + // } + // } else { + // PropertyDescriptor propertyDescriptor = + // PropertyDescriptorFactory.createPropertyDescriptor(name, description, + // type, delimiter, min, max, value); + // rule.definePropertyDescriptor(propertyDescriptor); + // } + // } + private static void setValue(Rule rule, PropertyDescriptor desc, String strValue) { + Object realValue = desc.valueFrom(strValue); + rule.setProperty(desc, realValue); + } - @SuppressWarnings("unchecked") - private static void parsePropertyNodeBR(Rule rule, Node propertyNode) { + @SuppressWarnings("unchecked") + private static void parsePropertyNodeBR(Rule rule, Node propertyNode) { - Element propertyElement = (Element) propertyNode; - String typeId = propertyElement.getAttribute(PropertyDescriptorFields.TYPE); - String strValue = propertyElement.getAttribute(PropertyDescriptorFields.VALUE); - if (StringUtil.isEmpty(strValue)) { - strValue = valueFrom(propertyElement); - } + Element propertyElement = (Element) propertyNode; + String typeId = propertyElement.getAttribute(PropertyDescriptorFields.TYPE); + String strValue = propertyElement.getAttribute(PropertyDescriptorFields.VALUE); + if (StringUtil.isEmpty(strValue)) { + strValue = valueFrom(propertyElement); + } - // Setting of existing property, or defining a new property? - if (StringUtil.isEmpty(typeId)) { - String name = propertyElement.getAttribute(PropertyDescriptorFields.NAME); + // Setting of existing property, or defining a new property? + if (StringUtil.isEmpty(typeId)) { + String name = propertyElement.getAttribute(PropertyDescriptorFields.NAME); - PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(name); - if (propertyDescriptor == null) { - throw new IllegalArgumentException("Cannot set non-existant property '" + name + "' on Rule " + rule.getName()); - } else { - setValue(rule, propertyDescriptor, strValue); - } - return; - } + PropertyDescriptor propertyDescriptor = rule.getPropertyDescriptor(name); + if (propertyDescriptor == null) { + throw new IllegalArgumentException("Cannot set non-existant property '" + name + "' on Rule " + + rule.getName()); + } else { + setValue(rule, propertyDescriptor, strValue); + } + return; + } - net.sourceforge.pmd.PropertyDescriptorFactory pdFactory = PropertyDescriptorUtil.factoryFor(typeId); - if (pdFactory == null) { - throw new RuntimeException("No property descriptor factory for type: " + typeId); - } + net.sourceforge.pmd.PropertyDescriptorFactory pdFactory = PropertyDescriptorUtil.factoryFor(typeId); + if (pdFactory == null) { + throw new RuntimeException("No property descriptor factory for type: " + typeId); + } - Map valueKeys = pdFactory.expectedFields(); - Map values = new HashMap(valueKeys.size()); + Map valueKeys = pdFactory.expectedFields(); + Map values = new HashMap(valueKeys.size()); - // populate a map of values for an individual descriptor - for (Map.Entry entry : valueKeys.entrySet()) { - String valueStr = propertyElement.getAttribute(entry.getKey()); - if (entry.getValue() && StringUtil.isEmpty(valueStr)) { - System.out.println("Missing required value for: " + entry.getKey()); // debug pt TODO - } - values.put(entry.getKey(), valueStr); - } + // populate a map of values for an individual descriptor + for (Map.Entry entry : valueKeys.entrySet()) { + String valueStr = propertyElement.getAttribute(entry.getKey()); + if (entry.getValue() && StringUtil.isEmpty(valueStr)) { + System.out.println("Missing required value for: " + entry.getKey()); // debug + // pt + // TODO + } + values.put(entry.getKey(), valueStr); + } - PropertyDescriptor desc = pdFactory.createWith(values); - PropertyDescriptorWrapper wrapper = new PropertyDescriptorWrapper(desc); + PropertyDescriptor desc = pdFactory.createWith(values); + PropertyDescriptorWrapper wrapper = new PropertyDescriptorWrapper(desc); - rule.definePropertyDescriptor(wrapper); - setValue(rule, desc, strValue); - } + rule.definePropertyDescriptor(wrapper); + setValue(rule, desc, strValue); + } - /** - * Parse a String from a textually type node. - * - * @param node The node. - * @return The String. - */ - private static String parseTextNode(Node node) { + /** + * Parse a String from a textually type node. + * + * @param node The node. + * @return The String. + */ + private static String parseTextNode(Node node) { - final int nodeCount = node.getChildNodes().getLength(); - if (nodeCount == 0) { - return ""; - } + final int nodeCount = node.getChildNodes().getLength(); + if (nodeCount == 0) { + return ""; + } - StringBuilder buffer = new StringBuilder(); + 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(); - } + 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(); + } - /** - * Determine if the specified rule element will represent a Rule with the given name. - * @param ruleElement The rule element. - * @param ruleName The Rule name. - * @return true if the Rule would have the given name, false otherwise. - */ - private boolean isRuleName(Element ruleElement, String ruleName) { - if (ruleElement.hasAttribute("name")) { - return ruleElement.getAttribute("name").equals(ruleName); - } else if (ruleElement.hasAttribute("ref")) { - RuleSetReferenceId ruleSetReferenceId = RuleSetReferenceId.parse(ruleElement.getAttribute("ref")).get(0); - return ruleSetReferenceId.getRuleName() != null && ruleSetReferenceId.getRuleName().equals(ruleName); - } else { - return false; - } - } + /** + * Determine if the specified rule element will represent a Rule with the + * given name. + * + * @param ruleElement The rule element. + * @param ruleName The Rule name. + * @return true if the Rule would have the given name, + * false otherwise. + */ + private boolean isRuleName(Element ruleElement, String ruleName) { + if (ruleElement.hasAttribute("name")) { + return ruleElement.getAttribute("name").equals(ruleName); + } else if (ruleElement.hasAttribute("ref")) { + RuleSetReferenceId ruleSetReferenceId = RuleSetReferenceId.parse(ruleElement.getAttribute("ref")).get(0); + return ruleSetReferenceId.getRuleName() != null && ruleSetReferenceId.getRuleName().equals(ruleName); + } else { + return false; + } + } } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMethod.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMethod.java index baf3a7b28a..4ca5d55a89 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMethod.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTMethod.java @@ -39,8 +39,6 @@ import org.apache.commons.lang3.StringUtils; * @version $Id: ASTMethod.java 720228 2008-11-24 16:58:33Z nbubna $ */ public class ASTMethod extends AbstractVmNode { - private final String methodName = ""; - /** * @param id */ @@ -139,7 +137,7 @@ public class ASTMethod extends AbstractVmNode { * @since 1.5 */ public String getMethodName() { - return methodName; + return ""; } } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTReference.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTReference.java index 5e77659ffa..ec7be06676 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTReference.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTReference.java @@ -94,8 +94,9 @@ public class ASTReference extends AbstractVmNode { * do only once */ - if (this.literal == null) + if (this.literal == null) { this.literal = literal; + } } /** @@ -106,8 +107,9 @@ public class ASTReference extends AbstractVmNode { */ @Override public String literal() { - if (literal != null) + if (literal != null) { return literal; + } // this value could be cached in this.literal but it increases memory usage return super.literal(); diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTStringLiteral.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTStringLiteral.java index cc9541337f..171397434a 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTStringLiteral.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/ASTStringLiteral.java @@ -28,9 +28,6 @@ import org.apache.commons.lang3.text.StrBuilder; * @version $Id: ASTStringLiteral.java 705297 2008-10-16 17:59:24Z nbubna $ */ public class ASTStringLiteral extends AbstractVmNode { - /* cache the value of the interpolation switch */ - private final boolean interpolate = true; - /** * @param id */ @@ -59,11 +56,13 @@ public class ASTStringLiteral extends AbstractVmNode { // If tok is on the first line, then the actual column is // offset by the template column. - if (tok.beginLine == 1) + if (tok.beginLine == 1) { tok.beginColumn += getColumn(); + } - if (tok.endLine == 1) + if (tok.endLine == 1) { tok.endColumn += getColumn(); + } tok.beginLine += getLine() - 1; tok.endLine += getLine() - 1; @@ -76,8 +75,9 @@ public class ASTStringLiteral extends AbstractVmNode { */ public static String unescape(final String string) { int u = string.indexOf("\\u"); - if (u < 0) + if (u < 0) { return string; + } final StrBuilder result = new StrBuilder(); @@ -118,7 +118,7 @@ public class ASTStringLiteral extends AbstractVmNode { * @since 1.6 */ public boolean isConstant() { - return !interpolate; + return false; } } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/AbstractVmNode.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/AbstractVmNode.java index 5315a94273..cffd376840 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/AbstractVmNode.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/AbstractVmNode.java @@ -162,7 +162,7 @@ public class AbstractVmNode extends AbstractNode implements VmNode { * @param prefix */ public void dump(final String prefix, final boolean recurse, final Writer writer) { - final PrintWriter printWriter = (writer instanceof PrintWriter) ? (PrintWriter) writer + final PrintWriter printWriter = writer instanceof PrintWriter ? (PrintWriter) writer : new PrintWriter(writer); printWriter.println(toString(prefix)); if (children != null && recurse) { @@ -183,13 +183,13 @@ public class AbstractVmNode extends AbstractNode implements VmNode { public String literal() { // if we have only one string, just return it and avoid // buffer allocation. VELOCITY-606 - if (first == last) { + if (first != null && first.equals(last)) { return NodeUtils.tokenLiteral(first); } Token t = first; final StrBuilder sb = new StrBuilder(NodeUtils.tokenLiteral(t)); - while (t != last) { + while (t != null && !t.equals(last)) { t = t.next; sb.append(NodeUtils.tokenLiteral(t)); } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/MacroParseException.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/MacroParseException.java index 3179f66a0d..ae2ed9a776 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/MacroParseException.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/MacroParseException.java @@ -66,7 +66,7 @@ public class MacroParseException extends ParseException { * @since 1.5 */ public int getLineNumber() { - if ((currentToken != null) && (currentToken.next != null)) { + if (currentToken != null && currentToken.next != null) { return currentToken.next.beginLine; } else if (currentToken != null) { @@ -84,7 +84,7 @@ public class MacroParseException extends ParseException { * @since 1.5 */ public int getColumnNumber() { - if ((currentToken != null) && (currentToken.next != null)) { + if (currentToken != null && currentToken.next != null) { return currentToken.next.beginColumn; } else if (currentToken != null) { diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/NodeUtils.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/NodeUtils.java index 31fa19424f..330d72f539 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/NodeUtils.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/NodeUtils.java @@ -42,16 +42,16 @@ public class NodeUtils { private static StrBuilder getSpecialText(final Token t) { final StrBuilder sb = new StrBuilder(); - Token tmp_t = t.specialToken; + Token tmpToken = t.specialToken; - while (tmp_t.specialToken != null) { - tmp_t = tmp_t.specialToken; + while (tmpToken.specialToken != null) { + tmpToken = tmpToken.specialToken; } - while (tmp_t != null) { - final String st = tmp_t.image; + while (tmpToken != null) { + final String st = tmpToken.image; - for (int i = 0, is = st.length(); i < is; i++) { + for (int i = 0; i < st.length(); i++) { final char c = st.charAt(i); if (c == '#' || c == '$') { @@ -69,7 +69,7 @@ public class NodeUtils { boolean term = false; int j = i; - for (ok = true; ok && j < is; j++) { + for (ok = true; ok && j < st.length(); j++) { final char cc = st.charAt(j); if (cc == '\\') { @@ -101,7 +101,7 @@ public class NodeUtils { } } - tmp_t = tmp_t.next; + tmpToken = tmpToken.next; } return sb; } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TemplateParseException.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TemplateParseException.java index 244ab4a2c8..c78315f07c 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TemplateParseException.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TemplateParseException.java @@ -109,7 +109,7 @@ public class TemplateParseException extends ParseException { * @return The line number where this exception occured. */ public int getLineNumber() { - if ((currentToken != null) && (currentToken.next != null)) { + if (currentToken != null && currentToken.next != null) { return currentToken.next.beginLine; } else { @@ -123,7 +123,7 @@ public class TemplateParseException extends ParseException { * @return The column number where this exception occured. */ public int getColumnNumber() { - if ((currentToken != null) && (currentToken.next != null)) { + if (currentToken != null && currentToken.next != null) { return currentToken.next.beginColumn; } else { @@ -158,7 +158,7 @@ public class TemplateParseException extends ParseException { } for (int j = 0; j < expectedTokenSequences[i].length; j++) { - expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" "); + expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { @@ -173,7 +173,7 @@ public class TemplateParseException extends ParseException { for (int i = 0; i < maxSize; i++) { if (i != 0) { - retval.append(" "); + retval.append(' '); } if (tok.kind == 0) { diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TokenMgrError.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TokenMgrError.java index 23213ca159..abd1b21e8d 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TokenMgrError.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/ast/TokenMgrError.java @@ -2,7 +2,7 @@ package net.sourceforge.pmd.lang.vm.ast; /* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */ -public class TokenMgrError extends Error { +public class TokenMgrError extends RuntimeException { /* * Ordinals for various reasons why an Error of this type can be thrown. */ @@ -46,40 +46,41 @@ public class TokenMgrError extends Error { for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0: - continue; + break; case '\b': retval.append("\\b"); - continue; + break; case '\t': retval.append("\\t"); - continue; + break; case '\n': retval.append("\\n"); - continue; + break; case '\f': retval.append("\\f"); - continue; + break; case '\r': retval.append("\\r"); - continue; + break; case '\"': retval.append("\\\""); - continue; + break; case '\'': retval.append("\\\'"); - continue; + break; case '\\': retval.append("\\\\"); - continue; + break; default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + ch = str.charAt(i); + if (ch < 0x20 || ch > 0x7e) { final String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } - continue; + break; } } return retval.toString(); @@ -103,19 +104,6 @@ public class TokenMgrError extends Error { + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } - /** - * You can also modify the body of this method to customize your error messages. For example, cases like - * LOOP_DETECTED and INVALID_LEXICAL_STATE are not of end-users concern, so you can return something like : - * - * "Internal Error : Please file a bug report .... " - * - * from this method for such cases in the release version of your parser. - */ - @Override - public String getMessage() { - return super.getMessage(); - } - /* * Constructors of various flavors follow. */ diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/Directive.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/Directive.java index a84b89daa5..bba142a8dd 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/Directive.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/Directive.java @@ -26,8 +26,14 @@ package net.sourceforge.pmd.lang.vm.directive; * @author Nathan Bubna * @version $Id: Directive.java 778045 2009-05-23 22:17:46Z nbubna $ */ -public abstract class Directive implements DirectiveConstants, Cloneable +public abstract class Directive implements Cloneable { + /** Block directive indicator */ + public static final int BLOCK = 1; + + /** Line directive indicator */ + public static final int LINE = 2; + private int line = 0; private int column = 0; private boolean provideScope = false; diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/DirectiveConstants.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/DirectiveConstants.java deleted file mode 100644 index 6c6d17fef0..0000000000 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/DirectiveConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sourceforge.pmd.lang.vm.directive; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Base class for all directives used in Velocity. - * - * @author Geir Magnusson Jr. - * @version $Id: DirectiveConstants.java 463298 2006-10-12 16:10:32Z henning $ - */ -public interface DirectiveConstants -{ - /** Block directive indicator */ - public static final int BLOCK = 1; - - /** Line directive indicator */ - public static final int LINE = 2; -} diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/InputBase.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/InputBase.java index 30a50d7f08..f0548ff513 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/InputBase.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/InputBase.java @@ -28,5 +28,9 @@ package net.sourceforge.pmd.lang.vm.directive; */ public abstract class InputBase extends Directive { - + /** + * Return name of this directive. + * @return The name of this directive. + */ + public abstract String getName(); } diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/VelocimacroProxy.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/VelocimacroProxy.java index 2155c57dbb..82f90b822d 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/VelocimacroProxy.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/directive/VelocimacroProxy.java @@ -30,8 +30,6 @@ package net.sourceforge.pmd.lang.vm.directive; public class VelocimacroProxy extends Directive { private String macroName; - private String[] argArray = null; - private String[] literalArgArray = null; private int numMacroArgs = 0; /** @@ -69,22 +67,11 @@ public class VelocimacroProxy extends Directive */ public void setArgArray(String[] arr) { - argArray = arr; - - // for performance reasons we precache these strings - they are needed in - // "render literal if null" functionality - literalArgArray = new String[arr.length]; - for(int i = 0; i < arr.length; i++) - { - literalArgArray[i] = ".literal.$" + argArray[i]; - } - /* * get the arg count from the arg array. remember that the arg array has the macro name as * it's 0th element */ - - numMacroArgs = argArray.length - 1; + numMacroArgs = arr.length - 1; } /** diff --git a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/util/VelocityCharStream.java b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/util/VelocityCharStream.java index 0a41be920b..a3c3372e0e 100644 --- a/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/util/VelocityCharStream.java +++ b/pmd-vm/src/main/java/net/sourceforge/pmd/lang/vm/util/VelocityCharStream.java @@ -40,7 +40,7 @@ import net.sourceforge.pmd.lang.ast.CharStream; public final class VelocityCharStream implements CharStream { - public static final boolean staticFlag = false; + public static final boolean STATIC_FLAG = false; int bufsize; private int nextBufExpand; int available; @@ -62,7 +62,7 @@ implements CharStream private int maxNextCharInd = 0; private int inBuf = 0; - private final void ExpandBuff(boolean wrapAround) + private void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + nextBufExpand]; int newbufline[] = new int[bufsize + nextBufExpand]; @@ -85,7 +85,7 @@ implements CharStream System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; - maxNextCharInd = (bufpos += (bufsize - tokenBegin)); + maxNextCharInd = (bufpos += bufsize - tokenBegin); } else { @@ -113,7 +113,7 @@ implements CharStream tokenBegin = 0; } - private final void FillBuff() throws java.io.IOException + private void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { @@ -150,8 +150,8 @@ implements CharStream int i; try { - if ((i = inputStream.read(buffer, maxNextCharInd, - available - maxNextCharInd)) == -1) + i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd); + if (i == -1) { inputStream.close(); throw new java.io.IOException(); @@ -177,7 +177,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#BeginToken() */ - public final char BeginToken() throws java.io.IOException + public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); @@ -186,7 +186,7 @@ implements CharStream return c; } - private final void UpdateLineColumn(char c) + private void UpdateLineColumn(char c) { column++; @@ -218,7 +218,7 @@ implements CharStream break; case '\t' : column--; - column += (8 - (column & 07)); + column += 8 - (column & 07); break; default : break; @@ -231,7 +231,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#readChar() */ - public final char readChar() throws java.io.IOException + public char readChar() throws java.io.IOException { if (inBuf > 0) { @@ -243,7 +243,8 @@ implements CharStream return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]; } - if (++bufpos >= maxNextCharInd) + bufpos++; + if (bufpos >= maxNextCharInd) { FillBuff(); } @@ -254,14 +255,14 @@ implements CharStream char c = buffer[bufpos]; UpdateLineColumn(c); - return (c); + return c; } /** * @see org.apache.velocity.runtime.parser.CharStream#getColumn() * @deprecated */ - public final int getColumn() + public int getColumn() { return bufcolumn[bufpos]; } @@ -270,7 +271,7 @@ implements CharStream * @see org.apache.velocity.runtime.parser.CharStream#getLine() * @deprecated */ - public final int getLine() + public int getLine() { return bufline[bufpos]; } @@ -278,7 +279,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#getEndColumn() */ - public final int getEndColumn() + public int getEndColumn() { return bufcolumn[bufpos]; } @@ -286,7 +287,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#getEndLine() */ - public final int getEndLine() + public int getEndLine() { return bufline[bufpos]; } @@ -294,7 +295,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#getBeginColumn() */ - public final int getBeginColumn() + public int getBeginColumn() { return bufcolumn[tokenBegin]; } @@ -302,7 +303,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#getBeginLine() */ - public final int getBeginLine() + public int getBeginLine() { return bufline[tokenBegin]; } @@ -310,12 +311,14 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#backup(int) */ - public final void backup(int amount) + public void backup(int amount) { inBuf += amount; - if ((bufpos -= amount) < 0) + bufpos -= amount; + if (bufpos < 0) { bufpos += bufsize; + } } /** @@ -429,7 +432,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#GetImage() */ - public final String GetImage() + public String GetImage() { if (bufpos >= tokenBegin) { @@ -445,7 +448,7 @@ implements CharStream /** * @see org.apache.velocity.runtime.parser.CharStream#GetSuffix(int) */ - public final char[] GetSuffix(int len) + public char[] GetSuffix(int len) { char[] ret = new char[len]; @@ -492,8 +495,11 @@ implements CharStream len = bufsize - tokenBegin + bufpos + 1 + inBuf; } - int i = 0, j = 0, k = 0; - int nextColDiff = 0, columnDiff = 0; + int i = 0; + int j = 0; + int k = 0; + int nextColDiff = 0; + int columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) @@ -512,10 +518,13 @@ implements CharStream while (i++ < len) { - if (bufline[j = start % bufsize] != bufline[++start % bufsize]) + j = start % bufsize; + start++; + if (bufline[j] != bufline[start % bufsize]) { bufline[j] = newLine++; - else + } else { bufline[j] = newLine; + } } } diff --git a/pmd-xml/src/main/java/net/sourceforge/pmd/lang/xml/ast/DOMLineNumbers.java b/pmd-xml/src/main/java/net/sourceforge/pmd/lang/xml/ast/DOMLineNumbers.java index ae8beb7d7c..0e092c4878 100644 --- a/pmd-xml/src/main/java/net/sourceforge/pmd/lang/xml/ast/DOMLineNumbers.java +++ b/pmd-xml/src/main/java/net/sourceforge/pmd/lang/xml/ast/DOMLineNumbers.java @@ -11,8 +11,6 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; -import org.w3c.dom.Entity; -import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList;