From 4599b6989a8a4ec2e7af7f8517faa6710f00955d Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Mon, 23 Dec 2019 18:18:26 +0100 Subject: [PATCH 01/22] [plsql] Fix StringLiteral token StringLiterals can use a custom quote delimiter that marks the end of a string literal. This quote delimiter is only effective together with the quote character. A single quote character, that is not preceded by the delimiter, should be allowed. Additionally, the ASTStringLiteral node gives now access to the plain string value of the literal without the quoting. Fixes #2008 --- docs/pages/release_notes.md | 2 + pmd-plsql/etc/grammar/PldocAST.jjt | 106 +++++++----------- pmd-plsql/src/main/ant/alljavacc.xml | 1 + .../pmd/lang/plsql/ast/ASTStringLiteral.java | 43 +++++++ .../lang/plsql/ast/StringLiteralsTest.java | 41 +++++++ .../pmd/lang/plsql/ast/StringLiterals.pls | 45 ++++++++ 6 files changed, 172 insertions(+), 66 deletions(-) create mode 100644 pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTStringLiteral.java create mode 100644 pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java create mode 100644 pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/StringLiterals.pls diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..f30607224a 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -55,6 +55,8 @@ the implementation based on your feedback. * [#2140](https://github.com/pmd/pmd/issues/2140): \[java] AvoidLiteralsInIfCondition: false negative for expressions * java-performance * [#2141](https://github.com/pmd/pmd/issues/2141): \[java] StringInstatiation: False negative with String-array access +* plsql + * [#2008](https://github.com/pmd/pmd/issues/2008): \[plsql] In StringLiteral using alternative quoting mechanism single quotes cause parsing errors ### API Changes diff --git a/pmd-plsql/etc/grammar/PldocAST.jjt b/pmd-plsql/etc/grammar/PldocAST.jjt index f01524dc45..27790459c8 100644 --- a/pmd-plsql/etc/grammar/PldocAST.jjt +++ b/pmd-plsql/etc/grammar/PldocAST.jjt @@ -3425,54 +3425,10 @@ ASTLiteral Literal() : } ASTStringLiteral StringLiteral() : +{} { - Token thisToken = null; - StringBuilder literal = new StringBuilder() ; - char startDelimiter ; - char endDelimiter ; - String terminator = null; -} -{ - //Essentially unchanged - ( - thisToken = - { - literal.append(thisToken.image); - /* - This might be Q-Quoted string and this might be only a partial string - The token will only match up to the first single quote. - The code below appends any remaining part, theh returns the complete string - */ - if (thisToken.image.toUpperCase().startsWith("Q'") - && thisToken.image.length() > 2 - ) - { - // Get the first token of the string so that the delimiter can be identified - - startDelimiter= thisToken.image.charAt(2) ; - /* - if the start delimiter is one of [, {, <, or (, the end delimiter - is the corresponding closing character - */ - switch (startDelimiter) - { - case '<' : endDelimiter = '>' ; break ; - case '{' : endDelimiter = '}' ; break ; - case '(' : endDelimiter = ')' ; break ; - case '[' : endDelimiter = ']' ; break ; - default: endDelimiter = startDelimiter ; - } - - terminator = new String(endDelimiter + "'"); - if (!thisToken.image.endsWith(terminator)) - { - //Loop until we find atoken that ends with a single-quote precede by the terminator - literal.append(ReadPastNextOccurrence(terminator)); - } - } - } - ) - { jjtThis.setImage(literal.toString()) ; jjtThis.value = literal.toString() ; return jjtThis ; } + + { jjtThis.setImage(token.image); return jjtThis ; } } @@ -5109,26 +5065,9 @@ TOKEN : | < #INTEGER_LITERAL: ( )+ > | - -< #_WHATEVER_CHARACTER_WO_ASTERISK: (~["'"]) > +< #_WHATEVER_CHARACTER_WO_APOSTROPHE: (~["'"]) > | -< CHARACTER_LITERAL: "'" (<_WHATEVER_CHARACTER_WO_ASTERISK> | )? "'" > -//|< STRING_LITERAL: -// (["q","Q"])* "'" (<_WHATEVER_CHARACTER_WO_ASTERISK> | | "''")* "'" -//> //Cope with Q-quoted stringswithout single quotes in them -|< STRING_LITERAL: -// Hard-code the most likely q-quote strings - "'" (<_WHATEVER_CHARACTER_WO_ASTERISK> | | "''")* "'" -|(["n","N"]) "'" (<_WHATEVER_CHARACTER_WO_ASTERISK> | | "''")* "'" //National Character Set String -|(["q","Q"]) "'" (<_WHATEVER_CHARACTER_WO_ASTERISK> | | "''")* "'" // Bug 160632 -|(["q","Q"]) "'[" (~["[","]"])* "]'" -|(["q","Q"]) "'{" (~["{","}"])* "}'" -|(["q","Q"]) "'<" (~["<",">"])* ">'" -|(["q","Q"]) "'(" (~["(",")"])* ")'" -|(["q","Q"]) "'/" (~["/"])* "/'" -|(["q","Q"]) "'!" (~["!"])* "!'" -|(["q","Q"]) "'#" (~["#"])* "#'" -> //Cope with Q-quoted stringswithout single quotes in them +< CHARACTER_LITERAL: "'" (<_WHATEVER_CHARACTER_WO_APOSTROPHE> | )? "'" > | < #_WHATEVER_CHARACTER_WO_QUOTE: (~["\""]) > | @@ -5147,6 +5086,41 @@ TOKEN : } +/** + * https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA + */ + MORE : +{ + < #_ALTERNATIVE_QUOTING_STRING_LITERAL: + (["q","Q"]) "'[" (~["]"] | "]" ~["'"] )* "]" + | (["q","Q"]) "'{" (~["}"] | "}" ~["'"] )* "}" + | (["q","Q"]) "'<" (~[">"] | ">" ~["'"] )* ">" + | (["q","Q"]) "'(" (~[")"] | ")" ~["'"] )* ")" + > + | <(["n","N"])? "'" (<_WHATEVER_CHARACTER_WO_APOSTROPHE> | | "''")*> : IN_STRING_LITERAL_TOKENIZE + | <(["n","N"])? <_ALTERNATIVE_QUOTING_STRING_LITERAL>> : IN_STRING_LITERAL_TOKENIZE + + // special handling for custom quote delimiters + | <(["n","N"])? (["q","Q"]) "'" (~[" ", "\t", "\r", "\n", "[", "{", "<", "("])> : IN_STRING_LITERAL +} + MORE : { + <~["'"]> + | <"'"> { + int quoteDelimiter = image.charAt(2); + if (image.charAt(0) == 'n' || image.charAt(0) == 'N') { + quoteDelimiter = image.charAt(3); + } + int beforeQuote = image.charAt(image.length() - 2); + if (quoteDelimiter == beforeQuote) { + input_stream.backup(1); + image.setLength(image.length() - 1); + SwitchTo(IN_STRING_LITERAL_TOKENIZE); + } + } +} + TOKEN : { : DEFAULT } + + /** * PL/SQL Reserved words * diff --git a/pmd-plsql/src/main/ant/alljavacc.xml b/pmd-plsql/src/main/ant/alljavacc.xml index d22c66587a..c161ad16ca 100644 --- a/pmd-plsql/src/main/ant/alljavacc.xml +++ b/pmd-plsql/src/main/ant/alljavacc.xml @@ -67,6 +67,7 @@ + diff --git a/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTStringLiteral.java b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTStringLiteral.java new file mode 100644 index 0000000000..d66683fafc --- /dev/null +++ b/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTStringLiteral.java @@ -0,0 +1,43 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + + +package net.sourceforge.pmd.lang.plsql.ast; + +public final class ASTStringLiteral extends net.sourceforge.pmd.lang.plsql.ast.AbstractPLSQLNode { + + + ASTStringLiteral(int id) { + super(id); + } + + + ASTStringLiteral(PLSQLParser p, int id) { + super(p, id); + } + + + @Override + public Object jjtAccept(PLSQLParserVisitor visitor, Object data) { + return visitor.visit(this, data); + } + + /** + * Gets the plain string from the string literal. + * @return the plain string value from the string literal. + */ + public String getString() { + String image = getImage(); + if (image.charAt(0) == 'N' || image.charAt(0) == 'n') { + image = image.substring(1); + } + + if (image.charAt(0) == '\'') { + image = image.substring(1, image.length() - 1); + } else if (image.charAt(0) == 'Q' || image.charAt(0) == 'q') { + image = image.substring("q'x".length(), image.length() - 2); + } + return image; + } +} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java new file mode 100644 index 0000000000..7a3082e61f --- /dev/null +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java @@ -0,0 +1,41 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.plsql.ast; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; + +import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst; + +public class StringLiteralsTest extends AbstractPLSQLParserTst { + + + @Test + public void parseStringLiterals() throws Exception { + String code = IOUtils.toString(this.getClass().getResourceAsStream("StringLiterals.pls"), + StandardCharsets.UTF_8); + ASTInput input = parsePLSQL(code); + List strings = input.findDescendantsOfType(ASTStringLiteral.class); + Assert.assertEquals(20, strings.size()); + + assertString("'Hello'", "Hello", 0, strings); + assertString("N'nchar literal'", "nchar literal", 4, strings); + assertString("nQ'[ab']cd]'", "ab']cd", 11, strings); + assertString("Q'{SELECT * FROM employees WHERE last_name = 'Smith';}'", + "SELECT * FROM employees WHERE last_name = 'Smith';", 13, strings); + assertString("q'{\n" + " also multiple\n" + " lines\n" + " }'", + "\n" + " also multiple\n" + " lines\n" + " ", 15, strings); + } + + + private static void assertString(String quoted, String plain, int index, List strings) { + Assert.assertEquals(quoted, strings.get(index).getImage()); + Assert.assertEquals(plain, strings.get(index).getString()); + } +} diff --git a/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/StringLiterals.pls b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/StringLiterals.pls new file mode 100644 index 0000000000..66118495ad --- /dev/null +++ b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/StringLiterals.pls @@ -0,0 +1,45 @@ +-- +-- See https://github.com/pmd/pmd/issues/2008 +-- [plsql] In StringLiteral using alternative quoting mechanism single quotes cause parsing errors +-- +-- https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA +-- + +declare + + literal1 clob := 'Hello'; + literal2 clob := 'ORACLE.dbs'; + literal3 clob := 'Jackie''s raincoat'; + literal4 clob := '09-MAR-98'; + literal5 clob := N'nchar literal'; + + -- alternative quoting mechanism + qliteral1a clob := q'[abc]'; + qliteral1b clob := q'[ab']cd]'; + qliteral1c clob := q'[ab[cd]'; + qliteral1d clob := q'[ab]cd]'; + qliteral1e clob := q'[ab + cd]'; + qliteral1f clob := Nq'[a"b"c]'; + qliteral1g clob := nQ'[ab']cd]'; + + qliteral1 clob := q'!name LIKE '%DBMS_%%'!'; + qliteral2 clob := Q'{SELECT * FROM employees WHERE last_name = 'Smith';}'; + qliteral1a clob := q'! test !'; + qliteral2a clob := q'{ + also multiple + lines + }'; + qliteral3a clob := q'% test abc %'; + qliteral3b clob := q'% test % abc %'; + + + qliteral3c clob := q'% test'test %'; + qliteral4 clob := nq'!name LIKE '%DBMS_%%'!'; + + + +begin + null; +end; +/ From 04aa48e3f192dacee6c7c140ee8ccaad0bff7536 Mon Sep 17 00:00:00 2001 From: Piotr Szymanski Date: Wed, 21 Aug 2019 17:39:18 +0200 Subject: [PATCH 02/22] [plsql] Add additional test case for multi line string literals --- .../lang/plsql/ast/StringLiteralsTest.java | 9 +++++ .../pmd/lang/plsql/ast/MultilineVarchar.pls | 37 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/MultilineVarchar.pls diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java index 7a3082e61f..06910ce1ea 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java @@ -33,6 +33,15 @@ public class StringLiteralsTest extends AbstractPLSQLParserTst { "\n" + " also multiple\n" + " lines\n" + " ", 15, strings); } + @Test + public void parseMultilineVarchar() throws Exception { + String code = IOUtils.toString(this.getClass().getResourceAsStream("MultilineVarchar.pls"), + StandardCharsets.UTF_8); + ASTInput input = parsePLSQL(code); + List strings = input.findDescendantsOfType(ASTStringLiteral.class); + Assert.assertEquals(1, strings.size()); + Assert.assertTrue(strings.get(0).getString().startsWith("\ncreate or replace and")); + } private static void assertString(String quoted, String plain, int index, List strings) { Assert.assertEquals(quoted, strings.get(index).getImage()); diff --git a/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/MultilineVarchar.pls b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/MultilineVarchar.pls new file mode 100644 index 0000000000..dad51aed4f --- /dev/null +++ b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/MultilineVarchar.pls @@ -0,0 +1,37 @@ +-- +-- From https://github.com/pmd/pmd/pull/1988 +-- +declare + + w_java_source clob := q'% +create or replace and compile java source named PdfUtils as + /** BLOB encryption class using AES 128bit + * Load class to oracle db. Class file is on the oracle serever: + * sql script: + * exec sys.dbms_java.loadjava('-v -r /tsfa/tia7400/PdfPassword.class'); + * command line: + * loadjava -user tia -resolve -verbose -r /tsfa/tia7400/PdfPassword.java + * dropjava -user tia -resolve -verbose -r /tsfa/tia7400/PdfPassword.java + */ + /** + * Function reads input blob, encrypts and returns it to the caller + * @author Karol Wozniak + * @param secret password key + * @param fortuneBLOB blob var + * @return oracle.sql.BLOB + */ + public static BLOB encryptPdf(String secret, Blob blobVar) throws Exception { + System.out.println("Start readBlob"); + blobfile = writeToBlob(boas.toByteArray()); + is.close(); + reader.close(); + System.out.println("encrypted using password " + secret); + System.out.println("End readBlob"); + return blobfile; + } +}; +%'; + +begin + null; +end; \ No newline at end of file From ad02dcac5ef38bba052f8ca2f6726903eed6b3a9 Mon Sep 17 00:00:00 2001 From: Piotr Szymanski Date: Thu, 22 Aug 2019 11:31:50 +0200 Subject: [PATCH 03/22] [plsql] Add test case for multiple ddl statements Refs #2009 --- .../plsql/ast/MultipleDDLStatementsTest.java | 26 +++++++++++++++++++ .../pmd/lang/plsql/ast/DDLCommands.sql | 5 ++++ 2 files changed, 31 insertions(+) create mode 100644 pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java create mode 100644 pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java new file mode 100644 index 0000000000..37bfe03804 --- /dev/null +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java @@ -0,0 +1,26 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.plsql.ast; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; + +import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst; + +public class MultipleDDLStatementsTest extends AbstractPLSQLParserTst { + + @Test + public void parseDDLCommands() throws Exception { + String code = IOUtils.toString(this.getClass().getResourceAsStream("DDLCommands.sql"), + StandardCharsets.UTF_8); + ASTInput input = parsePLSQL(code); + List ddlcommands = input.findDescendantsOfType(ASTDDLCommand.class); + Assert.assertEquals(3, ddlcommands.size()); + } +} diff --git a/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql new file mode 100644 index 0000000000..619aa4aa89 --- /dev/null +++ b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql @@ -0,0 +1,5 @@ +COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; + +COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; + +COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; From e230027f9aa2e01819814e8ec79cb08aae5f68dd Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Tue, 24 Dec 2019 11:17:59 +0100 Subject: [PATCH 04/22] [plsql] Support COMMENT statement Ref #2009 --- pmd-plsql/etc/grammar/PldocAST.jjt | 49 ++++++++++++------- .../plsql/ast/MultipleDDLStatementsTest.java | 3 ++ 2 files changed, 33 insertions(+), 19 deletions(-) diff --git a/pmd-plsql/etc/grammar/PldocAST.jjt b/pmd-plsql/etc/grammar/PldocAST.jjt index f01524dc45..f256faa56c 100644 --- a/pmd-plsql/etc/grammar/PldocAST.jjt +++ b/pmd-plsql/etc/grammar/PldocAST.jjt @@ -227,6 +227,9 @@ public class PLSQLParser { /** * Semantic lookahead to check if the next identifier is a * specific keyword. + * + *

+ * Usage: LOOKAHEAD({isKeyword("WAIT")}) KEYWORD("WAIT") */ private boolean isKeyword(String keyword) { return getToken(1).kind == IDENTIFIER && getToken(1).image.equalsIgnoreCase(keyword); @@ -259,12 +262,12 @@ ASTInput Input(String sourcecode) : {} | LOOKAHEAD(6) Directory() | LOOKAHEAD(6) DatabaseLink() | LOOKAHEAD(6) Global() - | LOOKAHEAD(6) DDLCommand() //Ignore any other DDL Event + | (LOOKAHEAD(6) DDLCommand())+ | LOOKAHEAD(2) SqlPlusCommand() | UpdateStatement() | DeleteStatement() | InsertStatement() - | SelectStatement() (";")? + | SelectStatement() [";"] |(|||||) SkipPastNextTokenOccurrence(SQLPLUS_TERMINATOR) //Ignore SQL statements in scripts ) ("/")* @@ -279,8 +282,15 @@ ASTDDLCommand DDLCommand() : } { ( - simpleNode = DDLEvent() - SkipPastNextTokenOccurrence(SQLPLUS_TERMINATOR) + ( + LOOKAHEAD({isKeyword("COMMENT")}) + simpleNode = Comment() + ) + | + ( + simpleNode = DDLEvent() + SkipPastNextTokenOccurrence(SQLPLUS_TERMINATOR) + ) ) { jjtThis.setImage(simpleNode.getImage()) ; return jjtThis ; } } @@ -315,7 +325,7 @@ ASTSqlPlusCommand SqlPlusCommand() : | | // DDL that might be encountered - | + | LOOKAHEAD({isKeyword("COMMENT")}) KEYWORD("COMMENT") | | | @@ -3904,19 +3914,22 @@ ASTViewColumn ViewColumn() : { return jjtThis ; } } +/** + * https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/COMMENT.html#GUID-65F447C4-6914-4823-9691-F15D52DB74D7 + */ ASTComment Comment() : { } { - ( + LOOKAHEAD({isKeyword("COMMENT")}) KEYWORD("COMMENT") + ( ((
| | ) [LOOKAHEAD(2) ID()"."] ID()) | ( [LOOKAHEAD(ID()"."ID()"."ID()) ID()"."] ID() "." ID()) ) - - [";"] - { return jjtThis ; } + StringLiteral() + ";" + { return jjtThis ; } } -// SRT * / @@ -4489,23 +4502,26 @@ ASTNonDMLTrigger NonDMLTrigger() : { return jjtThis ; } } - +/** + * https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/Types-of-SQL-Statements.html#GUID-FD9A8CB4-6B9A-44E5-B114-EFB8DA76FC88 + */ ASTDDLEvent DDLEvent(): {} { ( | | | - | + | LOOKAHEAD({isKeyword("COMMENT")}) KEYWORD("COMMENT") | | | + // | | | + // | | | | - | ) { jjtThis.setImage(token.toString()) ; jjtThis.value = token ; return jjtThis ; } } @@ -4741,7 +4757,6 @@ TOKEN [IGNORE_CASE]: | | | - | | | | @@ -4997,7 +5012,6 @@ TOKEN [IGNORE_CASE]: | //11G Trigger Syntax | //11G Trigger Syntax | //11G Trigger Syntax -| //11G Trigger Syntax | //11G Trigger Syntax | //11G Trigger Syntax | //11G Trigger Syntax @@ -5386,7 +5400,6 @@ ASTKEYWORD_UNRESERVED KEYWORD_UNRESERVED (): {} //| //| //| -| | //| //| @@ -5447,7 +5460,6 @@ ASTKEYWORD_UNRESERVED KEYWORD_UNRESERVED (): {} //| //| | -| //| //| | @@ -6352,7 +6364,7 @@ ASTID ID(): {} | KEYWORD_UNRESERVED() //SRT 2011-04-17 /*KEYWORDS_UNRESERVED | | | | | | | | | - | | | | + | | | */ //20120501 | | | @@ -6615,7 +6627,6 @@ ASTQualifiedID QualifiedID(): {} // //| //20120501 | - //| //| // // diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java index 37bfe03804..91ac15b17e 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java @@ -22,5 +22,8 @@ public class MultipleDDLStatementsTest extends AbstractPLSQLParserTst { ASTInput input = parsePLSQL(code); List ddlcommands = input.findDescendantsOfType(ASTDDLCommand.class); Assert.assertEquals(3, ddlcommands.size()); + List comments = input.findDescendantsOfType(ASTComment.class); + Assert.assertEquals(3, comments.size()); + Assert.assertEquals("'abbreviated job title'", comments.get(0).getFirstChildOfType(ASTStringLiteral.class).getImage()); } } From e345e811bee1c5260490866612af3ab583863911 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Tue, 24 Dec 2019 11:37:41 +0100 Subject: [PATCH 05/22] [plsql] Use ReadPastNextOccurrence rather than SkipPastNextToken The token SQLPLUS_TERMINATOR is useless, since the token ";" is matched before. So, we always skipped till the end of the file. Improved the image of the skipped nodes, so that it can be of some use. Note: This will fix the problem #2009, but it doesn't parse DDL Commands fully. It just skips past the next ";". --- pmd-plsql/etc/grammar/PldocAST.jjt | 16 ++++++++-------- .../plsql/ast/MultipleDDLStatementsTest.java | 2 +- .../pmd/lang/plsql/ast/DDLCommands.sql | 2 ++ 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/pmd-plsql/etc/grammar/PldocAST.jjt b/pmd-plsql/etc/grammar/PldocAST.jjt index f256faa56c..9e492b7d1c 100644 --- a/pmd-plsql/etc/grammar/PldocAST.jjt +++ b/pmd-plsql/etc/grammar/PldocAST.jjt @@ -268,7 +268,7 @@ ASTInput Input(String sourcecode) : {} | DeleteStatement() | InsertStatement() | SelectStatement() [";"] - |(|||
||) SkipPastNextTokenOccurrence(SQLPLUS_TERMINATOR) //Ignore SQL statements in scripts + |(|||
||) ReadPastNextOccurrence(";") //Ignore SQL statements in scripts ) ("/")* )* @@ -289,7 +289,7 @@ ASTDDLCommand DDLCommand() : | ( simpleNode = DDLEvent() - SkipPastNextTokenOccurrence(SQLPLUS_TERMINATOR) + ReadPastNextOccurrence(";") ) ) { jjtThis.setImage(simpleNode.getImage()) ; return jjtThis ; } @@ -1131,6 +1131,7 @@ ASTRead2NextOccurrence Read2NextOccurrence(String target) : { nextToken = getNextToken(); sb.append(nextToken.image); + sb.append(' '); nextToken = getToken(1); } } @@ -1143,10 +1144,11 @@ ASTRead2NextOccurrence Read2NextOccurrence(String target) : */ ASTReadPastNextOccurrence ReadPastNextOccurrence(String target) : { + ASTRead2NextOccurrence skipped = Read2NextOccurrence(target); + StringBuilder sb = new StringBuilder(); - Token t = null; - sb.append(Read2NextOccurrence(target)) ; - t = getNextToken(); // Chomp this one + sb.append(skipped.getImage()) ; + Token t = getNextToken(); // Chomp this one sb.append(t.image); } { @@ -3921,7 +3923,7 @@ ASTComment Comment() : { } { - LOOKAHEAD({isKeyword("COMMENT")}) KEYWORD("COMMENT") + LOOKAHEAD({isKeyword("COMMENT")}) KEYWORD("COMMENT") { jjtThis.setImage(token.image); } ( ((
| | ) [LOOKAHEAD(2) ID()"."] ID()) | ( [LOOKAHEAD(ID()"."ID()"."ID()) ID()"."] ID() "." ID()) @@ -5157,8 +5159,6 @@ TOKEN : < JAVA_INTERFACE_CLASS: ( "SQLData" | "CustomDatum" | "OraData" ) > //| //< #BOOLEAN_LITERAL: "TRUE" | "FALSE" > -| - } /** diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java index 91ac15b17e..cbd5a74497 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java @@ -21,7 +21,7 @@ public class MultipleDDLStatementsTest extends AbstractPLSQLParserTst { StandardCharsets.UTF_8); ASTInput input = parsePLSQL(code); List ddlcommands = input.findDescendantsOfType(ASTDDLCommand.class); - Assert.assertEquals(3, ddlcommands.size()); + Assert.assertEquals(4, ddlcommands.size()); List comments = input.findDescendantsOfType(ASTComment.class); Assert.assertEquals(3, comments.size()); Assert.assertEquals("'abbreviated job title'", comments.get(0).getFirstChildOfType(ASTStringLiteral.class).getImage()); diff --git a/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql index 619aa4aa89..5833689339 100644 --- a/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql +++ b/pmd-plsql/src/test/resources/net/sourceforge/pmd/lang/plsql/ast/DDLCommands.sql @@ -2,4 +2,6 @@ COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; +DROP TABLE employees; + COMMENT ON COLUMN employees.job_id IS 'abbreviated job title'; From 9a82ce14544ce6bc75df4f5eda97d5b1fafc31c6 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Tue, 24 Dec 2019 11:38:35 +0100 Subject: [PATCH 06/22] [doc] Update release notes, fixes #2009 --- docs/pages/release_notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..6504119267 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -55,6 +55,8 @@ the implementation based on your feedback. * [#2140](https://github.com/pmd/pmd/issues/2140): \[java] AvoidLiteralsInIfCondition: false negative for expressions * java-performance * [#2141](https://github.com/pmd/pmd/issues/2141): \[java] StringInstatiation: False negative with String-array access +* plsql + * [#2009](https://github.com/pmd/pmd/issues/2009): \[plsql] Multiple DDL commands are skipped during parsing ### API Changes From 1c7e8fb2abebf2b5558ccbe066d76d07985a84a5 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Tue, 24 Dec 2019 11:47:41 +0100 Subject: [PATCH 07/22] Fix build under windows --- .../pmd/lang/plsql/ast/StringLiteralsTest.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java index 06910ce1ea..0b2087d077 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java @@ -40,11 +40,15 @@ public class StringLiteralsTest extends AbstractPLSQLParserTst { ASTInput input = parsePLSQL(code); List strings = input.findDescendantsOfType(ASTStringLiteral.class); Assert.assertEquals(1, strings.size()); - Assert.assertTrue(strings.get(0).getString().startsWith("\ncreate or replace and")); + Assert.assertTrue(normalizeEol(strings.get(0).getString()).startsWith("\ncreate or replace and")); } private static void assertString(String quoted, String plain, int index, List strings) { - Assert.assertEquals(quoted, strings.get(index).getImage()); - Assert.assertEquals(plain, strings.get(index).getString()); + Assert.assertEquals(quoted, normalizeEol(strings.get(index).getImage())); + Assert.assertEquals(plain, normalizeEol(strings.get(index).getString())); + } + + private static String normalizeEol(String s) { + return s.replaceAll("\n|\r|\r\n|\n\r", "\n"); } } From dcb623972528db27a4573dee9ead435012f5d467 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Tue, 24 Dec 2019 14:13:27 +0100 Subject: [PATCH 08/22] Fix build under windows --- .../net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java index 0b2087d077..fcc7777e03 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java @@ -49,6 +49,6 @@ public class StringLiteralsTest extends AbstractPLSQLParserTst { } private static String normalizeEol(String s) { - return s.replaceAll("\n|\r|\r\n|\n\r", "\n"); + return s.replaceAll("\r\n|\n\r|\n|\r", "\n"); } } From 3712b17e7709949c8c9b727e8010ec2f4036aae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 24 Dec 2019 14:19:24 +0100 Subject: [PATCH 09/22] Internalize API that exposes ResourceLoader --- .../sourceforge/pmd/RulesetsFactoryUtils.java | 47 +++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java b/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java index e13384111a..83a673b60d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java @@ -7,6 +7,7 @@ package net.sourceforge.pmd; import java.util.logging.Level; import java.util.logging.Logger; +import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.benchmark.TimeTracker; import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; @@ -61,24 +62,62 @@ public final class RulesetsFactoryUtils { * @throws IllegalArgumentException * if rulesets is empty (means, no rules have been found) or if * a ruleset couldn't be found. + * @deprecated Is internal API */ + @InternalApi + @Deprecated public static RuleSets getRuleSetsWithBenchmark(String rulesets, RuleSetFactory factory) { try (TimedOperation to = TimeTracker.startOperation(TimedOperationCategory.LOAD_RULES)) { return getRuleSets(rulesets, factory); } } + /** + * @deprecated Use {@link #createFactory(PMDConfiguration)} or {@link #createFactory(PMDConfiguration, ClassLoader)} + */ + @InternalApi + @Deprecated public static RuleSetFactory getRulesetFactory(final PMDConfiguration configuration, - final ResourceLoader resourceLoader) { + final ResourceLoader resourceLoader) { return new RuleSetFactory(resourceLoader, configuration.getMinimumPriority(), true, - configuration.isRuleSetFactoryCompatibilityEnabled()); + configuration.isRuleSetFactoryCompatibilityEnabled()); + } + + /** + * Returns a ruleset factory which uses the classloader for PMD + * classes to resolve resource references. + * + * @param configuration PMD configuration, contains info about the + * factory parameters + * + * @return A ruleset factory + * + * @see #createFactory(PMDConfiguration, ClassLoader) + */ + public static RuleSetFactory createFactory(final PMDConfiguration configuration) { + return getRulesetFactory(configuration, new ResourceLoader()); + } + + /** + * Returns a ruleset factory which uses the provided {@link ClassLoader} + * to resolve resource references. + * + * @param configuration PMD configuration, contains info about the + * factory parameters + * @param classLoader Class loader to load resources + * + * @return A ruleset factory + * + * @see #createFactory(PMDConfiguration) + */ + public static RuleSetFactory createFactory(final PMDConfiguration configuration, ClassLoader classLoader) { + return getRulesetFactory(configuration, new ResourceLoader(classLoader)); } /** * If in debug modus, print the names of the rules. * - * @param rulesets - * the RuleSets to print + * @param rulesets the RuleSets to print */ private static void printRuleNamesInDebug(RuleSets rulesets) { if (LOG.isLoggable(Level.FINER)) { From 05870c98cc05805d6272d12f5080afad3a14e2b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Tue, 24 Dec 2019 14:39:20 +0100 Subject: [PATCH 10/22] Deprecate RulesetFactory constructors --- .../net/sourceforge/pmd/RuleSetFactory.java | 17 +++-- .../sourceforge/pmd/RulesetsFactoryUtils.java | 63 ++++++++++++++++++- .../pmd/benchmark/Benchmarker.java | 5 +- .../pmd/RuleSetFactoryCompatibilityTest.java | 4 +- ...leSetFactoryDuplicatedRuleLoggingTest.java | 2 +- .../sourceforge/pmd/RuleSetFactoryTest.java | 40 ++++++------ .../java/net/sourceforge/pmd/RuleSetTest.java | 10 +-- .../sourceforge/pmd/RuleSetWriterTest.java | 4 +- .../processor/MultiThreadProcessorTest.java | 5 +- .../properties/PropertyDescriptorTest.java | 6 +- .../pmd/docs/GenerateRuleDocsCmd.java | 3 +- .../pmd/docs/RuleDocGenerator.java | 3 +- .../pmd/docs/RuleDocGeneratorTest.java | 3 +- .../pmd/docs/RuleSetResolverTest.java | 5 +- .../pmd/docs/SidebarGeneratorTest.java | 6 +- .../net/sourceforge/pmd/ExcludeLinesTest.java | 2 +- .../sourceforge/pmd/RuleSetFactoryTest.java | 2 +- .../xpath/XPathMetricFunctionTest.java | 4 +- .../pmd/lang/java/rule/XPathRuleTest.java | 4 +- .../pmd/lang/jsp/ast/XPathJspRuleTest.java | 6 +- .../pmd/lang/scala/rule/ScalaRuleTest.java | 4 +- .../pmd/lang/scala/rule/XPathRuleTest.java | 4 +- .../pmd/AbstractLanguageVersionTest.java | 2 +- .../pmd/AbstractRuleSetFactoryTest.java | 4 +- .../pmd/testframework/RuleTst.java | 6 +- 25 files changed, 143 insertions(+), 71 deletions(-) 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 878f60d873..ead9f81333 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSetFactory.java @@ -60,22 +60,31 @@ public class RuleSetFactory { private final boolean warnDeprecated; private final RuleSetFactoryCompatibility compatibilityFilter; + /** + * @deprecated Use {@link RulesetsFactoryUtils#defaultFactory()} + */ + @Deprecated // to be removed with PMD 7.0.0. public RuleSetFactory() { this(new ResourceLoader(), RulePriority.LOW, false, true); } /** - * @deprecated Use {@link #RuleSetFactory(ResourceLoader, RulePriority, boolean, boolean)} with - * {@link ResourceLoader} instead of a {@link ClassLoader}. + * @deprecated Use {@link RulesetsFactoryUtils#createFactory(ClassLoader, RulePriority, boolean, boolean)} + * or {@link RulesetsFactoryUtils#createFactory(RulePriority, boolean, boolean)} */ @Deprecated // to be removed with PMD 7.0.0. public RuleSetFactory(final ClassLoader classLoader, final RulePriority minimumPriority, - final boolean warnDeprecated, final boolean enableCompatibility) { + final boolean warnDeprecated, final boolean enableCompatibility) { this(new ResourceLoader(classLoader), minimumPriority, warnDeprecated, enableCompatibility); } + /** + * @deprecated Use {@link RulesetsFactoryUtils#createFactory(ClassLoader, RulePriority, boolean, boolean)} + * or {@link RulesetsFactoryUtils#createFactory(RulePriority, boolean, boolean)} + */ + @Deprecated // to be hidden with PMD 7.0.0. public RuleSetFactory(final ResourceLoader resourceLoader, final RulePriority minimumPriority, - final boolean warnDeprecated, final boolean enableCompatibility) { + final boolean warnDeprecated, final boolean enableCompatibility) { this.resourceLoader = resourceLoader; this.minimumPriority = minimumPriority; this.warnDeprecated = warnDeprecated; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java b/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java index 83a673b60d..2fb7dba856 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RulesetsFactoryUtils.java @@ -95,12 +95,24 @@ public final class RulesetsFactoryUtils { * @see #createFactory(PMDConfiguration, ClassLoader) */ public static RuleSetFactory createFactory(final PMDConfiguration configuration) { - return getRulesetFactory(configuration, new ResourceLoader()); + return createFactory(configuration, RulesetsFactoryUtils.class.getClassLoader()); + } + + /** + * Returns a ruleset factory with default parameters. It doesn't prune + * rules based on priority, and doesn't warn for deprecations. + * + * @return A ruleset factory + * + * @see #createFactory(PMDConfiguration, ClassLoader) + */ + public static RuleSetFactory defaultFactory() { + return new RuleSetFactory(); } /** * Returns a ruleset factory which uses the provided {@link ClassLoader} - * to resolve resource references. + * to resolve resource references. It warns for deprecated rule usages. * * @param configuration PMD configuration, contains info about the * factory parameters @@ -111,7 +123,52 @@ public final class RulesetsFactoryUtils { * @see #createFactory(PMDConfiguration) */ public static RuleSetFactory createFactory(final PMDConfiguration configuration, ClassLoader classLoader) { - return getRulesetFactory(configuration, new ResourceLoader(classLoader)); + return createFactory(classLoader, + configuration.getMinimumPriority(), + true, + configuration.isRuleSetFactoryCompatibilityEnabled()); + } + + /** + * Returns a ruleset factory which uses the provided {@link ClassLoader} + * to resolve resource references. + * + * @param minimumPriority Minimum priority for rules to be included + * @param warnDeprecated If true, print warnings when deprecated rules are included + * @param enableCompatibility If true, rule references to moved rules are mapped to their + * new location if they are known + * @param classLoader Class loader to load resources + * + * @return A ruleset factory + * + * @see #createFactory(PMDConfiguration) + */ + public static RuleSetFactory createFactory(ClassLoader classLoader, + RulePriority minimumPriority, + boolean warnDeprecated, + boolean enableCompatibility) { + + return new RuleSetFactory(new ResourceLoader(classLoader), minimumPriority, warnDeprecated, enableCompatibility); + } + + /** + * Returns a ruleset factory which uses the classloader for PMD + * classes to resolve resource references. + * + * @param minimumPriority Minimum priority for rules to be included + * @param warnDeprecated If true, print warnings when deprecated rules are included + * @param enableCompatibility If true, rule references to moved rules are mapped to their + * new location if they are known + * + * @return A ruleset factory + * + * @see #createFactory(PMDConfiguration) + */ + public static RuleSetFactory createFactory(RulePriority minimumPriority, + boolean warnDeprecated, + boolean enableCompatibility) { + + return new RuleSetFactory(new ResourceLoader(), minimumPriority, warnDeprecated, enableCompatibility); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java index 383244a334..42baa667b6 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/benchmark/Benchmarker.java @@ -27,6 +27,7 @@ import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; import net.sourceforge.pmd.RuleSets; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.SourceCodeProcessor; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageFilenameFilter; @@ -116,7 +117,7 @@ public final class Benchmarker { System.out.println("Checking directory " + srcDir); } Set results = new TreeSet<>(); - RuleSetFactory factory = new RuleSetFactory(); + RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); if (StringUtils.isNotBlank(ruleset)) { stress(languageVersion, factory.createRuleSet(ruleset), dataSources, results, debug); } else { @@ -174,7 +175,7 @@ public final class Benchmarker { private static void stress(LanguageVersion languageVersion, RuleSet ruleSet, List dataSources, Set results, boolean debug) throws PMDException, IOException { - final RuleSetFactory factory = new RuleSetFactory(); + final RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); for (Rule rule: ruleSet.getRules()) { if (debug) { System.out.println("Starting " + rule.getName()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryCompatibilityTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryCompatibilityTest.java index 8feadfdc10..dd7104c561 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryCompatibilityTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryCompatibilityTest.java @@ -28,7 +28,7 @@ public class RuleSetFactoryCompatibilityTest { + " Test\n" + "\n" + " \n" + "\n"; - RuleSetFactory factory = new RuleSetFactory(); + RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); factory.getCompatibilityFilter().addFilterRuleMoved("dummy", "notexisting", "basic", "DummyBasicMockRule"); RuleSet createdRuleSet = createRulesetFromString(ruleset, factory); @@ -66,7 +66,7 @@ public class RuleSetFactoryCompatibilityTest { + " Test\n" + "\n" + " \n" + " \n" + " \n" + "\n"; - RuleSetFactory factory = new RuleSetFactory(); + RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); factory.getCompatibilityFilter().addFilterRuleRenamed("dummy", "basic", "OldNameOfSampleXPathRule", "SampleXPathRule"); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryDuplicatedRuleLoggingTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryDuplicatedRuleLoggingTest.java index 0f30d2bb67..38f58273c5 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryDuplicatedRuleLoggingTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryDuplicatedRuleLoggingTest.java @@ -75,7 +75,7 @@ public class RuleSetFactoryDuplicatedRuleLoggingTest { } private RuleSet loadRuleSet(String ruleSetFilename) throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); return rsf.createRuleSet("net/sourceforge/pmd/rulesets/duplicatedRuleLoggingTest/" + ruleSetFilename); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java index ce75cab3e7..d405caaebd 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java @@ -45,7 +45,7 @@ public class RuleSetFactoryTest { RuleSet rs = loadRuleSet(EMPTY_RULESET); assertNull("RuleSet file name not expected", rs.getFileName()); - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); rs = rsf.createRuleSet("net/sourceforge/pmd/TestRuleset1.xml"); assertEquals("wrong RuleSet file name", rs.getFileName(), "net/sourceforge/pmd/TestRuleset1.xml"); } @@ -58,7 +58,7 @@ public class RuleSetFactoryTest { @Test public void testRefs() throws Exception { - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); RuleSet rs = rsf.createRuleSet("net/sourceforge/pmd/TestRuleset1.xml"); assertNotNull(rs.getRuleByName("TestRuleRef")); } @@ -69,7 +69,7 @@ public class RuleSetFactoryTest { assertNotNull("Test ruleset not found - can't continue with test!", in); in.close(); - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); RuleSets rs = rsf.createRuleSets("net/sourceforge/pmd/rulesets/reference-ruleset.xml"); // added by referencing a complete ruleset (TestRuleset1.xml) assertNotNull(rs.getRuleByName("MockRule1")); @@ -127,7 +127,7 @@ public class RuleSetFactoryTest { @Test(expected = RuleSetNotFoundException.class) public void testRuleSetNotFound() throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); rsf.createRuleSet("fooooo"); } @@ -534,7 +534,7 @@ public class RuleSetFactoryTest { assertNotNull(ruleset.getRuleByName("SampleXPathRule")); // now, load with default minimum priority - rsf = new RuleSetFactory(); + rsf = RulesetsFactoryUtils.defaultFactory(); ruleset = rsf.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-minimum-priority.xml"); assertEquals("Number of Rules", 2, ruleset.getRules().size()); Rule dummyBasicMockRule = ruleset.getRuleByName("DummyBasicMockRule"); @@ -543,13 +543,13 @@ public class RuleSetFactoryTest { @Test public void testExcludeWithMinimumPriority() throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(new ResourceLoader(), RulePriority.HIGH, true, true); + RuleSetFactory rsf = RulesetsFactoryUtils.createFactory(RulePriority.HIGH, true, true); RuleSet ruleset = rsf.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-minimum-priority-exclusion.xml"); // no rules should be loaded assertEquals("Number of Rules", 0, ruleset.getRules().size()); // now, load with default minimum priority - rsf = new RuleSetFactory(); + rsf = RulesetsFactoryUtils.defaultFactory(); ruleset = rsf.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-minimum-priority-exclusion.xml"); // only one rule, we have excluded one... assertEquals("Number of Rules", 1, ruleset.getRules().size()); @@ -658,7 +658,7 @@ public class RuleSetFactoryTest { @Test public void testDeprecatedRuleSetReference() throws RuleSetNotFoundException { - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleSet = ruleSetFactory.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-deprecated.xml"); assertEquals(2, ruleSet.getRules().size()); } @@ -700,7 +700,7 @@ public class RuleSetFactoryTest { + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); ruleSetFactory.createRuleSet(ref); } @@ -718,7 +718,7 @@ public class RuleSetFactoryTest { + " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n" + " PMD Ruleset.\n" + "\n" + " .*Test.*\n" + "\n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset = ruleSetFactory.createRuleSet(ref); assertEquals(0, ruleset.getRules().size()); } @@ -761,7 +761,7 @@ public class RuleSetFactoryTest { + " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n" + " Custom ruleset for tests\n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); ruleSetFactory.createRuleSet(ref); } @@ -781,7 +781,7 @@ public class RuleSetFactoryTest { + " PMD Plugin preferences rule set\n" + "\n" + "\n" + "\n" + "\n" + ""); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet rs = ruleSetFactory.createRuleSet(ref); Rule r = rs.getRules().toArray(new Rule[1])[0]; @@ -808,7 +808,7 @@ public class RuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset = ruleSetFactory.createRuleSet(ref); assertEquals(4, ruleset.getRules().size()); } @@ -838,7 +838,7 @@ public class RuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset = ruleSetFactory.createRuleSet(ref1); assertNull(ruleset.getRuleByName("DummyBasicMockRule")); @@ -850,7 +850,7 @@ public class RuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory2 = new RuleSetFactory(); + RuleSetFactory ruleSetFactory2 = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset2 = ruleSetFactory2.createRuleSet(ref2); assertNotNull(ruleset2.getRuleByName("DummyBasicMockRule")); @@ -862,7 +862,7 @@ public class RuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory3 = new RuleSetFactory(); + RuleSetFactory ruleSetFactory3 = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset3 = ruleSetFactory3.createRuleSet(ref3); assertNotNull(ruleset3.getRuleByName("DummyBasicMockRule")); } @@ -880,7 +880,7 @@ public class RuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); ruleSetFactory.createRuleSet(ref); assertTrue(logging.getLog().contains("RuleSet name is missing.")); @@ -895,7 +895,7 @@ public class RuleSetFactoryTest { + " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n" + " \n" + " \n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); ruleSetFactory.createRuleSet(ref); assertTrue(logging.getLog().contains("RuleSet description is missing.")); } @@ -1095,12 +1095,12 @@ public class RuleSetFactoryTest { } private RuleSet loadRuleSet(String ruleSetXml) throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); return rsf.createRuleSet(createRuleSetReferenceId(ruleSetXml)); } private RuleSet loadRuleSetWithDeprecationWarnings(String ruleSetXml) throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(new ResourceLoader(), RulePriority.LOW, true, false); + RuleSetFactory rsf = RulesetsFactoryUtils.createFactory(RulePriority.LOW, true, false); return rsf.createRuleSet(createRuleSetReferenceId(ruleSetXml)); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java index 0dea767696..f19014a2c8 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java @@ -59,7 +59,7 @@ public class RuleSetTest { public void testNoDFA() { MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); - RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + RuleSet rs = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(mock); assertFalse(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); } @@ -68,7 +68,7 @@ public class RuleSetTest { MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); mock.setLanguage(LanguageRegistry.getLanguage(DummyLanguageModule.NAME)); mock.setDfa(true); - RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + RuleSet rs = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(mock); assertTrue(rs.usesDFA(LanguageRegistry.getLanguage(DummyLanguageModule.NAME))); } @@ -87,21 +87,21 @@ public class RuleSetTest { @Test public void testGetRuleByName() { MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + RuleSet rs = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(mock); assertEquals("unable to fetch rule by name", mock, rs.getRuleByName("name")); } @Test public void testGetRuleByName2() { MockRule mock = new MockRule("name", "desc", "msg", "rulesetname"); - RuleSet rs = new RuleSetFactory().createSingleRuleRuleSet(mock); + RuleSet rs = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(mock); assertNull("the rule FooRule must not be found!", rs.getRuleByName("FooRule")); } @Test public void testRuleList() { MockRule rule = new MockRule("name", "desc", "msg", "rulesetname"); - RuleSet ruleset = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet ruleset = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); assertEquals("Size of RuleSet isn't one.", 1, ruleset.size()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java index a451ecb150..d488f30fcc 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java @@ -51,7 +51,7 @@ public class RuleSetWriterTest { */ @Test public void testWrite() throws Exception { - RuleSet braces = new RuleSetFactory().createRuleSet("net/sourceforge/pmd/TestRuleset1.xml"); + RuleSet braces = RulesetsFactoryUtils.defaultFactory().createRuleSet("net/sourceforge/pmd/TestRuleset1.xml"); RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong()) .withName("ruleset") .withDescription("ruleset description") @@ -72,7 +72,7 @@ public class RuleSetWriterTest { */ @Test public void testRuleReferenceOverriddenName() throws Exception { - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet rs = ruleSetFactory.createRuleSet("dummy-basic"); RuleSetReference ruleSetReference = new RuleSetReference("rulesets/dummy/basic.xml"); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java index 096270b6b3..61d6480090 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java @@ -22,6 +22,7 @@ import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.ThreadSafeReportListener; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.AbstractRule; @@ -52,9 +53,9 @@ public class MultiThreadProcessorTest { ctx.getReport().addListener(reportListener); processor = new MultiThreadProcessor(configuration); - ruleSetFactory = new RuleSetFactory(); + ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); } - + @Test public void testRulesDysnfunctionalLog() throws IOException { setUpForTest("rulesets/MultiThreadProcessorTest/dysfunctional.xml"); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/properties/PropertyDescriptorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/properties/PropertyDescriptorTest.java index 8fa10cd46e..440f307fbe 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/properties/PropertyDescriptorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/properties/PropertyDescriptorTest.java @@ -30,7 +30,7 @@ import org.junit.rules.ExpectedException; import net.sourceforge.pmd.FooRule; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.properties.constraints.PropertyConstraint; @@ -57,7 +57,7 @@ public class PropertyDescriptorTest { FooRule rule = new FooRule(); rule.definePropertyDescriptor(intProperty); rule.setProperty(intProperty, 1000); - RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet ruleSet = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); List dysfunctional = new ArrayList<>(); ruleSet.removeDysfunctionalRules(dysfunctional); @@ -78,7 +78,7 @@ public class PropertyDescriptorTest { FooRule rule = new FooRule(); rule.definePropertyDescriptor(descriptor); rule.setProperty(descriptor, Collections.singletonList(1000d)); // not in range - RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet ruleSet = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); List dysfunctional = new ArrayList<>(); ruleSet.removeDysfunctionalRules(dysfunctional); diff --git a/pmd-doc/src/main/java/net/sourceforge/pmd/docs/GenerateRuleDocsCmd.java b/pmd-doc/src/main/java/net/sourceforge/pmd/docs/GenerateRuleDocsCmd.java index e58f1d72a7..fbb78a6898 100644 --- a/pmd-doc/src/main/java/net/sourceforge/pmd/docs/GenerateRuleDocsCmd.java +++ b/pmd-doc/src/main/java/net/sourceforge/pmd/docs/GenerateRuleDocsCmd.java @@ -22,6 +22,7 @@ import org.apache.commons.io.FilenameUtils; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; +import net.sourceforge.pmd.RulesetsFactoryUtils; public final class GenerateRuleDocsCmd { private GenerateRuleDocsCmd() { @@ -33,7 +34,7 @@ public final class GenerateRuleDocsCmd { Path output = FileSystems.getDefault().getPath(args[0]).resolve("..").toAbsolutePath().normalize(); System.out.println("Generating docs into " + output); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); Iterator registeredRuleSets = ruleSetFactory.getRegisteredRuleSets(); List additionalRulesets = findAdditionalRulesets(output); diff --git a/pmd-doc/src/main/java/net/sourceforge/pmd/docs/RuleDocGenerator.java b/pmd-doc/src/main/java/net/sourceforge/pmd/docs/RuleDocGenerator.java index 8b6f68f16a..4d1ffa2dee 100644 --- a/pmd-doc/src/main/java/net/sourceforge/pmd/docs/RuleDocGenerator.java +++ b/pmd-doc/src/main/java/net/sourceforge/pmd/docs/RuleDocGenerator.java @@ -38,6 +38,7 @@ import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; @@ -111,7 +112,7 @@ public class RuleDocGenerator { } List rulesets = new ArrayList<>(); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); for (String filename : additionalRulesets) { try { // do not take rulesets from pmd-test or pmd-core diff --git a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleDocGeneratorTest.java b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleDocGeneratorTest.java index 65ee4ef4a7..47e3d21f23 100644 --- a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleDocGeneratorTest.java +++ b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleDocGeneratorTest.java @@ -26,6 +26,7 @@ import org.junit.Test; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.docs.MockedFileWriter.FileEntry; public class RuleDocGeneratorTest { @@ -76,7 +77,7 @@ public class RuleDocGeneratorTest { public void testSingleRuleset() throws RuleSetNotFoundException, IOException { RuleDocGenerator generator = new RuleDocGenerator(writer, root); - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset = rsf.createRuleSet("rulesets/ruledoctest/sample.xml"); generator.generate(Arrays.asList(ruleset).iterator(), diff --git a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleSetResolverTest.java b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleSetResolverTest.java index f6fa28da16..c2c082c44f 100644 --- a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleSetResolverTest.java +++ b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/RuleSetResolverTest.java @@ -17,6 +17,7 @@ import org.junit.Test; import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; +import net.sourceforge.pmd.RulesetsFactoryUtils; public class RuleSetResolverTest { @@ -30,10 +31,10 @@ public class RuleSetResolverTest { public void resolveAllRulesets() { Path basePath = FileSystems.getDefault().getPath(".").resolve("..").toAbsolutePath().normalize(); List additionalRulesets = GenerateRuleDocsCmd.findAdditionalRulesets(basePath); - + filterRuleSets(additionalRulesets); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); for (String filename : additionalRulesets) { try { ruleSetFactory.createRuleSet(filename); diff --git a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/SidebarGeneratorTest.java b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/SidebarGeneratorTest.java index 474e8683f6..ea01604b3c 100644 --- a/pmd-doc/src/test/java/net/sourceforge/pmd/docs/SidebarGeneratorTest.java +++ b/pmd-doc/src/test/java/net/sourceforge/pmd/docs/SidebarGeneratorTest.java @@ -25,7 +25,7 @@ import org.yaml.snakeyaml.DumperOptions.LineBreak; import org.yaml.snakeyaml.Yaml; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -40,8 +40,8 @@ public class SidebarGeneratorTest { @Test public void testSidebar() throws IOException { Map> rulesets = new HashMap<>(); - RuleSet ruleSet1 = new RuleSetFactory().createNewRuleSet("test", "test", "bestpractices.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - RuleSet ruleSet2 = new RuleSetFactory().createNewRuleSet("test2", "test", "codestyle.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + RuleSet ruleSet1 = RulesetsFactoryUtils.defaultFactory().createNewRuleSet("test", "test", "bestpractices.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + RuleSet ruleSet2 = RulesetsFactoryUtils.defaultFactory().createNewRuleSet("test2", "test", "codestyle.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); rulesets.put(LanguageRegistry.findLanguageByTerseName("java"), Arrays.asList(ruleSet1, ruleSet2)); rulesets.put(LanguageRegistry.findLanguageByTerseName("ecmascript"), Arrays.asList(ruleSet1)); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java index 4042da9c20..5704ef0951 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/ExcludeLinesTest.java @@ -41,7 +41,7 @@ public class ExcludeLinesTest extends RuleTst { ctx.setReport(r); ctx.setSourceCodeFile(new File("n/a")); ctx.setLanguageVersion(LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getDefaultVersion()); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(TEST3), new RuleSets(rules), ctx); assertTrue(r.isEmpty()); assertEquals(r.getSuppressedRuleViolations().size(), 1); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java index cd0d8e16f2..c3ba3904f0 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java @@ -23,7 +23,7 @@ public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + " Custom ruleset for tests\n" + " \n" + " \n" + " \n" + "\n"); - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleset = ruleSetFactory.createRuleSet(ref); Rule rule = ruleset.getRuleByName("UselessParentheses"); assertNull(rule); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/xpath/XPathMetricFunctionTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/xpath/XPathMetricFunctionTest.java index d64d57fde7..48d4c672ec 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/xpath/XPathMetricFunctionTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/xpath/XPathMetricFunctionTest.java @@ -19,9 +19,9 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.java.JavaLanguageModule; import net.sourceforge.pmd.lang.java.xpath.MetricFunction; @@ -55,7 +55,7 @@ public class XPathMetricFunctionTest { ctx.setReport(report); ctx.setSourceCodeFile(new File("n/a")); ctx.setIgnoreExceptions(false); // for test, we want immediate exceptions thrown and not collect them - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(code), new RuleSets(rules), ctx); return report.iterator(); } diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java index 9c26da06a2..4a74a42e91 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java @@ -21,9 +21,9 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.Parser; @@ -211,7 +211,7 @@ public class XPathRuleTest extends RuleTst { Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFile(new File("n/a")); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(r); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(r); p.getSourceCodeProcessor().processSourceCode(new StringReader(test), new RuleSets(rules), ctx); return report; } diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java index 11f3bc77e9..3597fa8496 100644 --- a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java +++ b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/ast/XPathJspRuleTest.java @@ -16,9 +16,9 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.jsp.JspLanguageModule; import net.sourceforge.pmd.lang.rule.XPathRule; @@ -28,14 +28,14 @@ public class XPathJspRuleTest extends RuleTst { /** * Test matching a XPath expression against a JSP source. - * @throws PMDException + * @throws PMDException */ @Test public void testExpressionMatching() throws PMDException { Rule rule = new XPathRule(XPATH_EXPRESSION); rule.setMessage("Test"); rule.setLanguage(LanguageRegistry.getLanguage(JspLanguageModule.NAME)); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); RuleContext ctx = new RuleContext(); Report report = new Report(); diff --git a/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/ScalaRuleTest.java b/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/ScalaRuleTest.java index e3d0b2fd37..8c7cc39599 100644 --- a/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/ScalaRuleTest.java +++ b/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/ScalaRuleTest.java @@ -19,8 +19,8 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.internal.util.IteratorUtil; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersionHandler; @@ -77,7 +77,7 @@ public class ScalaRuleTest { Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFile(new File("test.scala")); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(r); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(r); p.getSourceCodeProcessor().processSourceCode(new StringReader(test), new RuleSets(rules), ctx); return report; } diff --git a/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/XPathRuleTest.java b/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/XPathRuleTest.java index 31de1124f4..5c64d291df 100644 --- a/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/XPathRuleTest.java +++ b/pmd-scala/src/test/java/net/sourceforge/pmd/lang/scala/rule/XPathRuleTest.java @@ -19,9 +19,9 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.rule.XPathRule; import net.sourceforge.pmd.lang.rule.xpath.XPathRuleQuery; @@ -57,7 +57,7 @@ public class XPathRuleTest extends RuleTst { Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFile(new File("test.scala")); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(r); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(r); p.getSourceCodeProcessor().processSourceCode(new StringReader(test), new RuleSets(rules), ctx); return report; } diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java index 93f3c317c6..f4367a7e06 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java @@ -156,7 +156,7 @@ public class AbstractLanguageVersionTest { String rulesetFilenames = props.getProperty("rulesets.filenames"); assertNotNull(rulesetFilenames); - RuleSetFactory factory = new RuleSetFactory(); + RuleSetFactory factory = RulesetsFactoryUtils.defaultFactory(); if (rulesetFilenames.trim().isEmpty()) { return; diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java index 16f9f85c25..752fe19afd 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java @@ -261,7 +261,7 @@ public abstract class AbstractRuleSetFactoryTest { } private RuleSet loadRuleSetByFileName(String ruleSetFileName) throws RuleSetNotFoundException { - RuleSetFactory rsf = new RuleSetFactory(); + RuleSetFactory rsf = RulesetsFactoryUtils.defaultFactory(); return rsf.createRuleSet(ruleSetFileName); } @@ -360,7 +360,7 @@ public abstract class AbstractRuleSetFactoryTest { // System.out.println("xml2: " + xml2); // Read RuleSet from XML, first time - RuleSetFactory ruleSetFactory = new RuleSetFactory(); + RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.defaultFactory(); RuleSet ruleSet2 = ruleSetFactory.createRuleSet(createRuleSetReferenceId(xml2)); // Do write/read a 2nd time, just to be sure diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java index 5ba2ce9815..512eff922d 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java @@ -40,10 +40,10 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; -import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetNotFoundException; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.RulesetsFactoryUtils; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.properties.PropertyDescriptor; @@ -99,7 +99,7 @@ public abstract class RuleTst { */ public Rule findRule(String ruleSet, String ruleName) { try { - Rule rule = new RuleSetFactory().createRuleSets(ruleSet).getRuleByName(ruleName); + Rule rule = RulesetsFactoryUtils.defaultFactory().createRuleSets(ruleSet).getRuleByName(ruleName); if (rule == null) { fail("Rule " + ruleName + " not found in ruleset " + ruleSet); } else { @@ -280,7 +280,7 @@ public abstract class RuleTst { ctx.setSourceCodeFile(new File("n/a")); ctx.setLanguageVersion(languageVersion); ctx.setIgnoreExceptions(false); - RuleSet rules = new RuleSetFactory().createSingleRuleRuleSet(rule); + RuleSet rules = RulesetsFactoryUtils.defaultFactory().createSingleRuleRuleSet(rule); p.getSourceCodeProcessor().processSourceCode(new StringReader(code), new RuleSets(rules), ctx); } catch (Exception e) { throw new RuntimeException(e); From 3f5ad7cfbeb9d0b0bf9a8288d8cfe035a4a54327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Thu, 26 Dec 2019 14:30:08 +0100 Subject: [PATCH 11/22] Deprecate rule factory --- .../main/java/net/sourceforge/pmd/rules/RuleBuilder.java | 3 +++ .../main/java/net/sourceforge/pmd/rules/RuleFactory.java | 7 +++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleBuilder.java b/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleBuilder.java index d02bff25d0..ed1b09c401 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleBuilder.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleBuilder.java @@ -13,6 +13,7 @@ import org.w3c.dom.Element; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.RuleSetReference; +import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; @@ -27,6 +28,8 @@ import net.sourceforge.pmd.util.ResourceLoader; * @author Clément Fournier * @since 6.0.0 */ +@InternalApi +@Deprecated public class RuleBuilder { private List> definedProperties = new ArrayList<>(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleFactory.java b/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleFactory.java index 9a11c36927..217bfe2084 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleFactory.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/rules/RuleFactory.java @@ -26,6 +26,7 @@ import org.w3c.dom.NodeList; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.RuleSetReference; +import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyDescriptorField; @@ -40,6 +41,8 @@ import net.sourceforge.pmd.util.ResourceLoader; * @author Clément Fournier * @since 6.0.0 */ +@InternalApi +@Deprecated public class RuleFactory { private static final Logger LOG = Logger.getLogger(RuleFactory.class.getName()); @@ -57,7 +60,7 @@ public class RuleFactory { private static final String DESCRIPTION = "description"; private static final String PROPERTY = "property"; private static final String CLASS = "class"; - + private static final List REQUIRED_ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(NAME, CLASS)); private final ResourceLoader resourceLoader; @@ -337,7 +340,7 @@ public class RuleFactory { Attr a = (Attr) atts.item(i); values.put(PropertyDescriptorField.getConstant(a.getName()), a.getValue()); } - + if (StringUtils.isBlank(values.get(DEFAULT_VALUE))) { NodeList children = propertyElement.getElementsByTagName(DEFAULT_VALUE.attributeName()); if (children.getLength() == 1) { From 1b9b94a794671723b22754f52d17173f3bba08e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Thu, 26 Dec 2019 14:33:44 +0100 Subject: [PATCH 12/22] Update release notes --- docs/pages/release_notes.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..7860da50d1 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -76,6 +76,11 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr eg {% jdoc java::lang.java.rule.JavaRuleViolation %}. See javadoc of {% jdoc core::RuleViolation %}. +* {% jdoc core::rules.RuleFactory %} +* {% jdoc core::rules.RuleBuilder %} +* Constructors of {% jdoc core::RuleSetFactory %}, use factory methods from {% jdoc core::RulesetsFactoryUtils %} instead +* {% jdoc core::RulesetsFactoryUtils#getRulesetFactory(core::PMDConfiguration, core::util.ResourceLoader) %} + ##### For removal * {% jdoc java::lang.java.AbstractJavaParser %} From 41baa353b014b02cd5ce998cb3b70bb3f7747861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Thu, 26 Dec 2019 18:37:19 +0100 Subject: [PATCH 13/22] Deprecate API of TryStatement that will be renamed --- docs/pages/release_notes.md | 3 +- .../lang/java/ast/ASTFinallyStatement.java | 8 +++++ .../pmd/lang/java/ast/ASTTryStatement.java | 34 ++++++++++++++++++- .../codestyle/IdenticalCatchBranchesRule.java | 2 +- .../rule/errorprone/CloseResourceRule.java | 12 ++++--- 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..a236e35a83 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -97,7 +97,8 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr instead. This affects {% jdoc !!java::lang.java.ast.ASTAnnotationTypeDeclaration#getImage() %}, {% jdoc !!java::lang.java.ast.ASTClassOrInterfaceDeclaration#getImage() %}, and {% jdoc !!java::lang.java.ast.ASTEnumDeclaration#getImage() %}. - +* Several methods of {% jdoc java::lang.java.ast.ASTTryStatement %}, replacements with other names + have been added. This includes the XPath attribute `@Finally`, replace it with a test for `child::FinallyStatement`. ### External Contributions diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFinallyStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFinallyStatement.java index fcecbddf4b..2b77bf38e4 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFinallyStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFinallyStatement.java @@ -24,4 +24,12 @@ public class ASTFinallyStatement extends AbstractJavaNode { public Object jjtAccept(JavaParserVisitor visitor, Object data) { return visitor.visit(this, data); } + + + /** + * Returns the body of this finally clause. + */ + public ASTBlock getBody() { + return (ASTBlock) jjtGetChild(0); + } } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java index 7ac0ee055c..6a0381ad5a 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java @@ -45,19 +45,40 @@ public class ASTTryStatement extends AbstractJavaNode { } + /** + * Returns the body of this try statement. + */ + public ASTBlock getBody() { + return getFirstChildOfType(ASTBlock.class); + } + /** * Returns the catch statement nodes of this try statement. * If there are none, returns an empty list. + * + * @deprecated Use {@link #getCatchClauses()} */ + @Deprecated public List getCatchStatements() { return findChildrenOfType(ASTCatchStatement.class); } + /** + * Returns the catch clauses of this try statement. + * If there are none, returns an empty list. + */ + public List getCatchClauses() { + return findChildrenOfType(ASTCatchStatement.class); + } + /** * Returns true if this try statement has a {@code finally} statement, - * in which case {@link #getFinally()} won't return {@code null}. + * in which case {@link #getFinallyClause()} won't return {@code null}. + * + * @deprecated Check for nullity of {@link #getFinallyClause()} */ + @Deprecated public boolean hasFinally() { return getFirstChildOfType(ASTFinallyStatement.class) != null; } @@ -67,9 +88,20 @@ public class ASTTryStatement extends AbstractJavaNode { * Returns the {@code finally} statement of this try statement, if any. * * @return The finally statement, or null if there is none + * + * @deprecated Use {@link #getFinallyClause()} */ public ASTFinallyStatement getFinally() { return getFirstChildOfType(ASTFinallyStatement.class); } + /** + * Returns the {@code finally} clause of this try statement, if any. + * + * @return The finally statement, or null if there is none + */ + public ASTFinallyStatement getFinallyClause() { + return getFirstChildOfType(ASTFinallyStatement.class); + } + } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/IdenticalCatchBranchesRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/IdenticalCatchBranchesRule.java index ba10b3f3c7..9701dbfd37 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/IdenticalCatchBranchesRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/IdenticalCatchBranchesRule.java @@ -88,7 +88,7 @@ public class IdenticalCatchBranchesRule extends AbstractJavaRule { @Override public Object visit(ASTTryStatement node, Object data) { - List catchStatements = node.getCatchStatements(); + List catchStatements = node.getCatchClauses(); Set> equivClasses = equivalenceClasses(catchStatements); for (List identicalStmts : equivClasses) { diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloseResourceRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloseResourceRule.java index 65468b515b..6889605762 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloseResourceRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloseResourceRule.java @@ -26,6 +26,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; +import net.sourceforge.pmd.lang.java.ast.ASTFinallyStatement; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; @@ -362,9 +363,10 @@ public class CloseResourceRule extends AbstractJavaRule { } } - if (t.getBeginLine() > id.getBeginLine() && t.hasFinally()) { - ASTBlock f = (ASTBlock) t.getFinally().jjtGetChild(0); - List names = f.findDescendantsOfType(ASTName.class); + ASTFinallyStatement finallyClause = t.getFinallyClause(); + if (t.getBeginLine() > id.getBeginLine() && finallyClause != null) { + ASTBlock finallyBody = finallyClause.getBody(); + List names = finallyBody.findDescendantsOfType(ASTName.class); for (ASTName oName : names) { String name = oName.getImage(); if (name != null && name.contains(".")) { @@ -373,7 +375,7 @@ public class CloseResourceRule extends AbstractJavaRule { String methodName = parts[1]; String varName = parts[0]; if (varName.equals(variableToClose) && closeTargets.contains(methodName) - && nullCheckIfCondition(f, oName, varName)) { + && nullCheckIfCondition(finallyBody, oName, varName)) { closed = true; break; } @@ -386,7 +388,7 @@ public class CloseResourceRule extends AbstractJavaRule { } List exprs = new ArrayList<>(); - f.findDescendantsOfType(ASTStatementExpression.class, exprs, true); + finallyBody.findDescendantsOfType(ASTStatementExpression.class, exprs, true); for (ASTStatementExpression stmt : exprs) { ASTPrimaryExpression expr = stmt.getFirstChildOfType(ASTPrimaryExpression.class); if (expr != null) { From 0a0bb6e4bbd5be386ac139ccac3a9c474409d1e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Thu, 26 Dec 2019 18:47:28 +0100 Subject: [PATCH 14/22] Rename getGuardExpressionNode -> getCondition --- docs/pages/release_notes.md | 1 + .../pmd/lang/java/ast/ASTAssertStatement.java | 10 ++++++++++ .../lang/java/ast/ASTConditionalExpression.java | 11 +++++++++++ .../pmd/lang/java/ast/ASTDoStatement.java | 11 +++++++++++ .../pmd/lang/java/ast/ASTForStatement.java | 15 +++++++++++++++ .../pmd/lang/java/ast/ASTIfStatement.java | 11 +++++++++++ .../pmd/lang/java/ast/ASTWhileStatement.java | 11 +++++++++++ .../java/metrics/impl/internal/CycloVisitor.java | 12 ++++++------ 8 files changed, 76 insertions(+), 6 deletions(-) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index a236e35a83..1eb8ca3840 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -99,6 +99,7 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr {% jdoc !!java::lang.java.ast.ASTEnumDeclaration#getImage() %}. * Several methods of {% jdoc java::lang.java.ast.ASTTryStatement %}, replacements with other names have been added. This includes the XPath attribute `@Finally`, replace it with a test for `child::FinallyStatement`. +* Several methods named `getGuardExpressionNode` are replaced with `getCondition`. This affects the following nodes: WhileStatement, DoStatement, ForStatement, IfStatement, AssertStatement, ConditionalExpression. ### External Contributions diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssertStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssertStatement.java index 5cc2414249..ac13e5f048 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssertStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssertStatement.java @@ -37,8 +37,18 @@ public class ASTAssertStatement extends AbstractJavaNode { /** * Returns the expression tested by this assert statement. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public ASTExpression getGuardExpressionNode() { + return getCondition(); + } + + /** + * Returns the expression tested by this assert statement. + */ + public ASTExpression getCondition() { return (ASTExpression) jjtGetChild(0); } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConditionalExpression.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConditionalExpression.java index 2f79681cd1..141e16949e 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConditionalExpression.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConditionalExpression.java @@ -62,11 +62,22 @@ public class ASTConditionalExpression extends AbstractJavaTypeNode { /** * Returns the node that represents the guard of this conditional. * That is the expression before the '?'. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public Node getGuardExpressionNode() { return jjtGetChild(0); } + /** + * Returns the node that represents the guard of this conditional. + * That is the expression before the '?'. + */ + public Node getCondition() { + return jjtGetChild(0); + } + /** * Returns the node that represents the expression that will be evaluated diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java index 8ca91febef..e2f7604650 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java @@ -36,8 +36,19 @@ public class ASTDoStatement extends AbstractJavaNode { /** * Returns the node that represents the guard of this loop. * This may be any expression of type boolean. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public ASTExpression getGuardExpressionNode() { + return getCondition(); + } + + /** + * Returns the node that represents the guard of this loop. + * This may be any expression of type boolean. + */ + public ASTExpression getCondition() { return (ASTExpression) jjtGetChild(1); } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForStatement.java index 9ae218b9f2..bb59aaa096 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTForStatement.java @@ -46,8 +46,23 @@ public class ASTForStatement extends AbstractJavaNode { * *

If this node represents a foreach loop, or if there is * no specified guard, then returns null. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public ASTExpression getGuardExpressionNode() { + return getCondition(); + } + + + /** + * Returns the node that represents the guard of this loop. + * This may be any expression of type boolean. + * + *

If this node represents a foreach loop, or if there is + * no specified guard, then returns null. + */ + public ASTExpression getCondition() { if (isForeach()) { return null; } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIfStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIfStatement.java index f9614c4fe8..50d3e6b58c 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIfStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIfStatement.java @@ -54,11 +54,22 @@ public class ASTIfStatement extends AbstractJavaNode { /** * Returns the node that represents the guard of this conditional. * This may be any expression of type boolean. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public ASTExpression getGuardExpressionNode() { return (ASTExpression) jjtGetChild(0); } + /** + * Returns the node that represents the guard of this conditional. + * This may be any expression of type boolean. + */ + public ASTExpression getCondition() { + return (ASTExpression) jjtGetChild(0); + } + /** * Returns the statement that will be run if the guard evaluates diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWhileStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWhileStatement.java index d0dedbf152..c58f92d20e 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWhileStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTWhileStatement.java @@ -35,11 +35,22 @@ public class ASTWhileStatement extends AbstractJavaNode { /** * Returns the node that represents the guard of this loop. * This may be any expression of type boolean. + * + * @deprecated Use {@link #getCondition()} */ + @Deprecated public ASTExpression getGuardExpressionNode() { return (ASTExpression) jjtGetChild(0); } + /** + * Returns the node that represents the guard of this loop. + * This may be any expression of type boolean. + */ + public ASTExpression getCondition() { + return (ASTExpression) jjtGetChild(0); + } + /** * Returns the statement that will be run while the guard diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/impl/internal/CycloVisitor.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/impl/internal/CycloVisitor.java index a3a78083f2..9515e3963c 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/impl/internal/CycloVisitor.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/impl/internal/CycloVisitor.java @@ -80,7 +80,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { public Object visit(ASTConditionalExpression node, Object data) { ((MutableInt) data).increment(); if (considerBooleanPaths) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @@ -90,7 +90,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { public Object visit(ASTWhileStatement node, Object data) { ((MutableInt) data).increment(); if (considerBooleanPaths) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @@ -100,7 +100,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { public Object visit(ASTIfStatement node, Object data) { ((MutableInt) data).increment(); if (considerBooleanPaths) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); @@ -112,7 +112,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { ((MutableInt) data).increment(); if (considerBooleanPaths && !node.isForeach()) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); @@ -123,7 +123,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { public Object visit(ASTDoStatement node, Object data) { ((MutableInt) data).increment(); if (considerBooleanPaths) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); @@ -150,7 +150,7 @@ public class CycloVisitor extends JavaParserVisitorAdapter { ((MutableInt) data).add(2); // equivalent to if (condition) { throw .. } if (considerBooleanPaths) { - ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getGuardExpressionNode())); + ((MutableInt) data).add(CycloMetric.booleanExpressionComplexity(node.getCondition())); } } From f33291e37234e57cf26edf36e2fd093dd6e67bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Thu, 26 Dec 2019 18:50:58 +0100 Subject: [PATCH 15/22] Deprecate ASTYieldStatement implementing TypeNode --- docs/pages/release_notes.md | 5 +++- .../pmd/lang/java/ast/ASTTryStatement.java | 2 +- .../pmd/lang/java/ast/ASTYieldStatement.java | 28 +++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 1eb8ca3840..f31b968315 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -99,7 +99,10 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr {% jdoc !!java::lang.java.ast.ASTEnumDeclaration#getImage() %}. * Several methods of {% jdoc java::lang.java.ast.ASTTryStatement %}, replacements with other names have been added. This includes the XPath attribute `@Finally`, replace it with a test for `child::FinallyStatement`. -* Several methods named `getGuardExpressionNode` are replaced with `getCondition`. This affects the following nodes: WhileStatement, DoStatement, ForStatement, IfStatement, AssertStatement, ConditionalExpression. +* Several methods named `getGuardExpressionNode` are replaced with `getCondition`. This affects the + following nodes: WhileStatement, DoStatement, ForStatement, IfStatement, AssertStatement, ConditionalExpression. +* {% jdoc java::lang.java.ast.ASTYieldStatement %} will not implement {% jdoc java::lang.java.ast.TypeNode %} + anymore come 7.0.0. Test the type of the expression nested within it. ### External Contributions diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java index 6a0381ad5a..4b6b4f0e82 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java @@ -49,7 +49,7 @@ public class ASTTryStatement extends AbstractJavaNode { * Returns the body of this try statement. */ public ASTBlock getBody() { - return getFirstChildOfType(ASTBlock.class); + return (ASTBlock) jjtGetChild(1); } /** diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTYieldStatement.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTYieldStatement.java index b3a59c33ee..dec9488637 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTYieldStatement.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTYieldStatement.java @@ -4,6 +4,8 @@ package net.sourceforge.pmd.lang.java.ast; +import net.sourceforge.pmd.lang.java.typeresolution.typedefinition.JavaTypeDefinition; + public class ASTYieldStatement extends AbstractJavaTypeNode { ASTYieldStatement(int id) { @@ -27,4 +29,30 @@ public class ASTYieldStatement extends AbstractJavaTypeNode { } return result; } + + + /** Returns the yielded expression. */ + public ASTExpression getExpr() { + return (ASTExpression) jjtGetChild(0); + } + + + /** + * @deprecated Use the type of the expression yielded by {@link #getExpr()} + */ + @Deprecated + @Override + public Class getType() { + return super.getType(); + } + + /** + * @deprecated Use the type of the expression yielded by {@link #getExpr()} + */ + @Deprecated + @Override + public JavaTypeDefinition getTypeDefinition() { + return super.getTypeDefinition(); + } + } From 9efe803685924ea25863dbdb7074fc2f7ce4b49b Mon Sep 17 00:00:00 2001 From: Egor18 Date: Sun, 29 Dec 2019 21:52:48 +0300 Subject: [PATCH 16/22] Fix odd logic in test runner --- .../java/net/sourceforge/pmd/testframework/PMDTestRunner.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java index 0f9b6d310f..a0e05007bf 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java @@ -66,7 +66,7 @@ public class PMDTestRunner extends Runner implements Filterable, Sortable { try { unitTests.filter(filter); } catch (NoTestsRemainException e) { - noUnitTests = false; + noUnitTests = true; } if (noRuleTests && noUnitTests) { From 3b8d694be34027062cb8a5384ed6a3f1fd6eac52 Mon Sep 17 00:00:00 2001 From: Egor18 Date: Sun, 29 Dec 2019 22:00:13 +0300 Subject: [PATCH 17/22] Fix odd logic in AvoidUsingHardCodedIPRule --- .../java/rule/bestpractices/AvoidUsingHardCodedIPRule.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java index 364162fecf..55336967f0 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java @@ -104,11 +104,11 @@ public class AvoidUsingHardCodedIPRule extends AbstractJavaRule { } protected boolean isLatinDigit(char c) { - return '0' <= c || c <= '9'; + return '0' <= c && c <= '9'; } protected boolean isHexCharacter(char c) { - return isLatinDigit(c) || 'A' <= c || c <= 'F' || 'a' <= c || c <= 'f'; + return isLatinDigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f'; } protected boolean isIPv4(final char firstChar, final String s) { From 07de89f5162fd92988b10436a8acc613b9b2a7d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Mart=C3=ADn=20Sotuyo=20Dodero?= Date: Sat, 4 Jan 2020 04:33:40 -0300 Subject: [PATCH 18/22] Update changelog, refs #2193 --- docs/pages/release_notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..fd0f15dd38 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -105,6 +105,7 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr * [#2051](https://github.com/pmd/pmd/pull/2051): \[doc] Update the docs on adding a new language - [Anatoly Trosinenko](https://github.com/atrosinenko) * [#2069](https://github.com/pmd/pmd/pull/2069): \[java] CommentRequired: make property names consistent - [snuyanzin](https://github.com/snuyanzin) * [#2169](https://github.com/pmd/pmd/pull/2169): \[modelica] Follow-up fixes for Modelica language module - [Anatoly Trosinenko](https://github.com/atrosinenko) +* [#2193](https://github.com/pmd/pmd/pull/2193): \[core] Fix odd logic in test runner - [Egor Bredikhin](https://github.com/Egor18) {% endtocmaker %} From caaa5eba9a6be31ee507defbe7b4ac526bf1ecc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Mart=C3=ADn=20Sotuyo=20Dodero?= Date: Sat, 4 Jan 2020 04:37:13 -0300 Subject: [PATCH 19/22] Fix issue with analysis of IPv6 mapper IPv4 --- .../java/rule/bestpractices/AvoidUsingHardCodedIPRule.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java index 55336967f0..abda97d238 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java @@ -108,7 +108,7 @@ public class AvoidUsingHardCodedIPRule extends AbstractJavaRule { } protected boolean isHexCharacter(char c) { - return isLatinDigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f'; + return isLatinDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'); } protected boolean isIPv4(final char firstChar, final String s) { @@ -190,7 +190,7 @@ public class AvoidUsingHardCodedIPRule extends AbstractJavaRule { } } catch (NumberFormatException e) { // The last part can be a standard IPv4 address. - if (i != parts.length - 1 || !isIPv4(firstChar, part)) { + if (i != parts.length - 1 || !isIPv4(part.charAt(0), part)) { return false; } ipv4Mapped = true; From d614e7ab17fb4a3ba24dc31df4e6547378002c88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Mart=C3=ADn=20Sotuyo=20Dodero?= Date: Sat, 4 Jan 2020 04:38:59 -0300 Subject: [PATCH 20/22] Update changelog, refs #2194 --- docs/pages/release_notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 38e0ad5b77..8952b84ea1 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -105,6 +105,7 @@ You can identify them with the `@InternalApi` annotation. You'll also get a depr * [#2051](https://github.com/pmd/pmd/pull/2051): \[doc] Update the docs on adding a new language - [Anatoly Trosinenko](https://github.com/atrosinenko) * [#2069](https://github.com/pmd/pmd/pull/2069): \[java] CommentRequired: make property names consistent - [snuyanzin](https://github.com/snuyanzin) * [#2169](https://github.com/pmd/pmd/pull/2169): \[modelica] Follow-up fixes for Modelica language module - [Anatoly Trosinenko](https://github.com/atrosinenko) +* [#2194](https://github.com/pmd/pmd/pull/2194): \[java] Fix odd logic in AvoidUsingHardCodedIPRule - [Egor Bredikhin](https://github.com/Egor18) {% endtocmaker %} From 4cf6291ecbad92fabe790f8edef80d789a9bfc06 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Sun, 5 Jan 2020 18:20:26 +0100 Subject: [PATCH 21/22] Fix pmd --- .../lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java index abda97d238..998651feef 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java @@ -108,7 +108,7 @@ public class AvoidUsingHardCodedIPRule extends AbstractJavaRule { } protected boolean isHexCharacter(char c) { - return isLatinDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'); + return isLatinDigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f'; } protected boolean isIPv4(final char firstChar, final String s) { From 8e30425dfadd7d052cee4237f3539044112c92a3 Mon Sep 17 00:00:00 2001 From: Andreas Dangel Date: Sun, 5 Jan 2020 19:18:10 +0100 Subject: [PATCH 22/22] [doc] Update release notes, fixes #2161 --- docs/pages/release_notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pages/release_notes.md b/docs/pages/release_notes.md index 7860da50d1..82e675fb81 100644 --- a/docs/pages/release_notes.md +++ b/docs/pages/release_notes.md @@ -44,6 +44,7 @@ the implementation based on your feedback. * core * [#2006](https://github.com/pmd/pmd/issues/2006): \[core] PMD should warn about multiple instances of the same rule in a ruleset + * [#2161](https://github.com/pmd/pmd/issues/2161): \[core] ResourceLoader is deprecated and marked as internal but is exposed * [#2170](https://github.com/pmd/pmd/issues/2170): \[core] DocumentFile doesn't preserve newlines * java-bestpractices * [#2149](https://github.com/pmd/pmd/issues/2149): \[java] JUnitAssertionsShouldIncludeMessage - False positive with assertEquals and JUnit5