Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use P3C to implement custom code specification checking

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to use P3C to implement custom code specification checking. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

P3C, a code specification checking tool, has a corresponding ide plug-in, which can prompt the set rules during the coding process, so it intends to expand it to increase the check of whether fastjson checks whether the setAutoType feature is turned on.

  P3C mainly consists of three parts:

PMD implementation (p3c-pmd): using PMD https://pmd.github.io/ to implement code specification checking

Intellij IDEA plug-in

Eclipse plug-in

1. PMD

  P3C uses PMD. PMD is a static code scanning tool that can check whether Java code contains unused variables, empty grab blocks, unnecessary objects, and so on. PMD uses JavaCC generation parser to parse the source code and generate AST (Abstract Syntax Tree). By checking the AST, you can check the code directly from the text level of the source code, which is called a rule within PMD. That is, compliance with the rules means to enumerate all possible ways to write the source code, and then check on AST to see if it appears. The implementation of the rules focuses on the processing of AST.

1.1. AST

  has a lot of introductions about AST online, which can be searched directly. Here are two important points:

AST is a tree representation of the abstract syntax structure of the source code

The abstract syntax tree does not depend on the syntax of the original language, that is, it has nothing to do with the context used in the parsing phase.

  PMD uses JavaCC to generate AST. You can also view relevant information about JavaCC on the Internet, which is not introduced here, as long as you know that JavaCC is a lexical analysis generator and a syntax analysis generator.

1.2. Custom Rul

The official document of   PMD describes the implementation steps of custom rules. The process is relatively clear. I will not repeat it here, but will only introduce the steps that need to be designed in this article.

1.2.1. Define a rule set

The rules for   PMD need to be configured in the XML file

Create the following empty file to represent the rule set

My custom rules ````* reference custom rule `in the above ```ruleset ```tag * configure rule set # 1.2.2. Configuration rule   can configure a rule in the ```rule ```tag * configure prompt messages and alarm level ``5``` alarm priority is divided into 1-5 level,1 with the highest priority and 5 lowest * configuration operation parameters can assign class attributes # 1.2.3 through ```properties``` and ``propertie ```. The preparation of rules   rules is relatively simple, PMD has given us a supporting development framework and tools, as long as determine the occurrence of the rules, according to the fixed pattern to write. * make sure that the implementation method can be implemented using either pure Java or XPath. For the pure Java mode, the PMD framework itself realizes traversing the number of AST. Users only need to analyze and judge the various situations of the custom rules when traversing each node. The process is similar to the SAX parsing of DOM files, parsing AST content in the way of streams and events. For the XPath mode, it takes AST as a XML number and traverses the parsed content in the way of XPath. * determine what may happen according to the test code. PMD comes with a designer, which can be used to generate the AST content of the corresponding code. For the effect to be achieved in this article, the following code is involved: ```import com.alibaba.fastjson.parser.ParserConfig; public class NegativeExample {public static void main (String [] args) {ParserConfig.getGlobalInstance () .setAutoTypeSupport (true) }} ```you can get the following AST content in designer! [file] (the specific content of https://oscimg.oschina.net/oscnet/491a18dd2086a3919b55fe84e4de1007549.jpg) will not be posted here. You can download desigin and paste the above code. For the requirements of this article, you need to make sure that when there is an import ```ParserConfig ````class, the ```setAutoTypeSupport ```method is called and the parameter is ```true```. Of course, this condition is not stringent enough. You also need to determine whether `is called or not. You also need to consider whether the fully qualified name is directly written through import import. But considering the general way of writing, as well as the formatting of ide, this processing can satisfy most scenarios. * write a rule implementation class to determine the criteria for the rule, and then you can start writing code. For Java, you can directly inherit the ```net.sourceforge.pmd.lang.java.rule.AbstractJavaRule ```class, and then override the visit method of various nodes. For example, it is used to determine whether there is an import ```ParserConfig ```private final String PARSER_CONFIG_IMPORT_NAME = "com.alibaba.fastjson.parser.ParserConfig"; private boolean hasImport = false; @ Override public Object visit (ASTImportDeclaration node, Object data) {if (PARSER_CONFIG_IMPORT_NAME.equals (node.getImportedName () {hasImport = true } return super.visit (node, data);} ````for XPath, you can set the corresponding XPath by inheriting the ```net.sourceforge.pmd.lang.rule.XPathRule ```class and overriding the ```setXPath``` method. As mentioned above, the attributes of the class can be assigned through the ```property ```configuration. Therefore, for XPat mode, you can enable XPath by setting the following settings in the xml configuration. ```Rule Description 3 ```# 1.2.4. Test rules   PMD recommends that there should be at least one forward and reverse test case for each rule to verify that the rule occurs and does not occur. For regular testing, PMD also provides a framework for adding xml test files in the agreed manner.   PMD prescribes several rules for loading test cases * the test class inherits the ```net.sourceforge.pmd.testframework.PmdRuleTst ```class, which integrates Junt, in which you can add the test methods you need. * for adding a xml directory under the path corresponding to `and the test class, add a xml file with the same name as step 1, which is used to write the test set. For example, the example rule implementation classpath given on the official website is as follows: ```net.sourceforge.pmd.lang.java.rule.bestpractices.AbstractClassWithoutAbstractMethodTest ````test case set: ```src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/AbstractClassWithoutAbstractMethod.xml ``` The rules of xml can be introduced on the official website. I won't repeat it here. # 2. The main module implemented by p3c-pmd   code specification is implemented by pmd. The p3c-pmd module is neatly organized in code, and you can add custom rules / rule sets according to the same pattern. For the requirements of this article,   intends to add an extend module to this module to implement a custom rule set. The following is a good rule set path for the corresponding source code path! [file] (https://oscimg.oschina.net/oscnet/3e3f8a123f38290ab7992a2ac7db6e7d9d0.jpg)![file](https://oscimg.oschina.net/oscnet/2e451daf3afca20540f4802d6ae072b8c66.jpg)   this article uses pure Java to implement the rules, according to 1.2.3. Section, you can get the following implementation class

Public class AvoidFastJsonAutoTypeSupportRule extends AbstractAliRule {

Private final String PARSER_CONFIG_IMPORT_NAME = "com.alibaba.fastjson.parser.ParserConfig"; private final String SET_AUTO_TYPE_SUPPORT_NAME = "setAutoTypeSupport"; private boolean hasImport = false;@Overridepublic Object visit (ASTImportDeclaration node, Object data) {if (PARSER_CONFIG_IMPORT_NAME.equals (node.getImportedName () {hasImport = true;} return super.visit (node, data) } @ Overridepublic Object visit (ASTPrimaryExpression node, Object data) {if (hasImport) {int size = node.jjtGetNumChildren (); for (int I = 0; I

< size; i++) { Node child = node.jjtGetChild(i); String imageName = null; if (child instanceof ASTPrimaryPrefix) { ASTPrimaryPrefix prefix = (ASTPrimaryPrefix) child; imageName = prefix.jjtGetChild(0).getImage(); }else if (child instanceof ASTPrimarySuffix){ ASTPrimarySuffix suffix = (ASTPrimarySuffix) child; imageName = suffix.getImage(); } if (imageName == null) { continue; }else if (imageName.endsWith(SET_AUTO_TYPE_SUPPORT_NAME)){ ASTPrimarySuffix argumentSuffix = (ASTPrimarySuffix) node.jjtGetChild(i + 1); try { List booleanArgs = argumentSuffix.findChildNodesWithXPath("//PrimaryPrefix/Literal/BooleanLiteral"); if (booleanArgs.size() == 1) { ASTBooleanLiteral booleanLiteral = (ASTBooleanLiteral) booleanArgs.get(0); if (booleanLiteral.isTrue()) { ViolationUtils.addViolationWithPrecisePosition(this, argumentSuffix, data, I18nResources.getMessage("java.extend.AvoidFastJsonAutoTypeSupportRule.rule.msg" )); } } } catch (JaxenException e) { e.printStackTrace(); } finally { break; } } } } return super.visit(node, data);} }  对应规则集中的配置为 java.extend.AvoidFastJsonAutoTypeSupportRule.rule.desc 1 public class NegativeExample { public static void main(String[] args) { ParserConfig.getGlobalInstance().setAutoTypeSupport(true); } } ]]>

There are several points to note in  . Class ```AvoidFastJsonAutoTypeSupportRule ```inherits from ````com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule```, AbstractAliRule inherits from AbstractJavaRule, and overrides setDescription,setMessage and addViolationWithMessage methods. The three methods mentioned here add multi-language support. P3c-pmd uses Resource Bundle to provide multilingual support. Each message has a unique id to correspond, and p3c-pmd maps the method parameters to the id of the message by rewriting the method to unify the configuration of the message. The following is the local corresponding message prompt

Description: there is a security vulnerability in the setAutoTypeSupport feature of fastjson]] >

  for testing, follow 1. 2. 4. The introduction has the following file path! [file] (the content of https://oscimg.oschina.net/oscnet/67322e2edc5dcc7d1e8148149930404a64d.jpg) file is relatively simple, so we won't post it here. At this point,   has completed the implementation of custom rules, and now it's time to apply this content to ide. First of all, you need to compile the module, which is saved directly to the local maven reference for local debugging.   directly upgrades the version of p3c-pmd to 2.0.1, and then executes mvn install, and the corresponding version can be seen in the local warehouse! [file] (with this version in https://oscimg.oschina.net/oscnet/fe9ed36fd7ef30cb794e550782ee4d5d4c3.jpg), you can refer to this version in other modules to debug new features. Take the idea-plugin module as an example below. # 3. Idea-plugin   idea-plugin mainly implements the plug-in of idea, which can check the code in real time. Here involves the development of idea custom plug-ins, here is not in-depth, there are many tutorials online. Here is only how to connect the rules customized above to the module. 1. Modify the build.gradle file of the idea-plugin module to open the local repository configuration to load the latest p3c-pmd dependencies directly from the local.

Buildscript {repositories {maven {url "https://oss.sonatype.org/content/repositories/snapshots/"} maven {url 'http://dl.bintray.com/jetbrains/intellij-plugin-service'} mavenLocal () mavenCentral ()

} dependencies {classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}

}

Allprojects {group 'com.alibaba.p3c.idea' apply plugin:' java' apply plugin: 'kotlin' apply plugin:' maven-publish'

SourceCompatibility = 1.8compileJava.options.encoding = 'UTF-8'configurations.all {resolutionStrategy.cacheChangingModulesFor 0,' seconds'} repositories {mavenLocal () jcenter () mavenCentral ()} dependencies {compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" testCompile group: 'junit', name:' junit', version: '4.11'}

}

As above, add ```mavenLocal () ```2. Modify the build.gradle of p3c-common and change the version of p3c-pmd to 2. 0. 13. Modify p3c-common module resources/rulesets/java/ali=pmd.xml to add

`

To add custom rule checks.

4. Under the p3c-common module, execute gradle clean buildPlugin to generate the corresponding plug-in.

4. Verification

If the plug-in is installed locally by  , you can get the following results

This only verifies the effect, does not really introduce fastjson dependencies, and verifies that pmd checks the source text.

On how to use P3C to achieve custom code specification check is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report