### Java Code Formatting Example Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/代码格式.md Demonstrates correct Java code formatting according to P3C standards, including brace usage, spacing, indentation, and conditional statements. This example serves as a reference for applying multiple formatting rules simultaneously. ```java public static void main(String[] args) { // 缩进4个空格 String say = "hello"; // 运算符的左右必须有一个空格 int flag = 0; // 关键词if与括号之间必须有一个空格,括号内的f与左括号,0与右括号不需要空格 if (flag == 0) { System.out.println(say); } // 左大括号前加空格且不换行;左大括号后换行 if (flag == 1) { System.out.println("world"); // 右大括号前换行,右大括号后有else,不用换行 } else { System.out.println("ok"); // 在右大括号后直接结束,则必须换行 } } ``` -------------------------------- ### Method Parameter Spacing Example Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/代码格式.md Provides an example of correct spacing after commas when defining or passing multiple parameters to a method. This rule enhances code readability across all programming languages. ```java method("a", "b", "c"); ``` -------------------------------- ### Direct P3C-PMD Local Scan Example (Java) Source: https://github.com/alibaba/p3c/wiki/FAQ This snippet demonstrates how to directly use the p3c-pmd package for local code scanning without an IDE. It requires packaging p3c-pmd into a fat-jar and executing a Java command with specific arguments for directory, rules, and report format. ```bash java -cp p3c-pmd.jar net.sourceforge.pmd.PMD -d /usr/src -R rule/ali-comment.xml -f text ``` -------------------------------- ### Java PMD Rule Testing Setup Source: https://context7.com/alibaba/p3c/llms.txt Sets up the test suite for concurrency rules in PMD, defining specific rules to be tested. This class extends SimpleAggregatorTst and uses an XML-based approach for defining test cases. ```java public class ConcurrentRuleTest extends SimpleAggregatorTst { private static final String RULE_NAME = "java-ali-concurrent"; @Override public void setUp() { addRule(RULE_NAME, "ThreadPoolCreationRule"); addRule(RULE_NAME, "AvoidUseTimerRule"); addRule(RULE_NAME, "AvoidManuallyCreateThreadRule"); addRule(RULE_NAME, "ThreadShouldSetNameRule"); addRule(RULE_NAME, "AvoidCallStaticSimpleDateFormatRule"); addRule(RULE_NAME, "ThreadLocalShouldRemoveRule"); addRule(RULE_NAME, "AvoidConcurrentCompetitionRandomRule"); addRule(RULE_NAME, "CountDownShouldInFinallyRule"); addRule(RULE_NAME, "LockShouldWithTryFinallyRule"); } } ``` -------------------------------- ### Comment Formatting Example Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/代码格式.md Illustrates the correct way to format comments in code, specifically ensuring there is exactly one space between the double-slash '//' and the comment text. This applies to all programming languages used within the project. ```java // 这是示例注释,请注意在双斜线之后有一个空格 String ygb = new String(); ``` -------------------------------- ### PMD Rule Engine Base Class and Example Rule for Java Source: https://context7.com/alibaba/p3c/llms.txt Demonstrates the base class 'AbstractAliRule' for P3C's PMD-based rules, handling internationalization and type resolution. Includes an example 'ThreadPoolCreationRule' that prevents the use of 'Executors.newXXX()' methods to enforce best practices for thread pool creation. ```java import com.alibaba.p3c.pmd.I18nResources; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.typeresolution.FixClassTypeResolver; import net.sourceforge.pmd.lang.ast.Token; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; // Base class for all P3C rules with automatic i18n and type resolution public abstract class AbstractAliRule extends AbstractJavaRule { private static final String DELIMITER = "#"; private static final String DOT = "."; private static final String NEW = "new"; private static final Map TYPE_RESOLVER_MAP = new ConcurrentHashMap<>(16); @Override public Object visit(ASTCompilationUnit node, Object data) { String sourceCodeFilename = ((RuleContext)data).getSourceCodeFilename(); String uniqueId = sourceCodeFilename + DELIMITER + node.hashCode(); if (!TYPE_RESOLVER_MAP.containsKey(uniqueId)) { resolveType(node, data); TYPE_RESOLVER_MAP.put(uniqueId, true); } return super.visit(node, data); } @Override public void setMessage(String message) { super.setMessage(I18nResources.getMessageWithExceptionHandled(message)); } private void resolveType(ASTCompilationUnit node, Object data) { FixClassTypeResolver classTypeResolver = new FixClassTypeResolver(AbstractAliRule.class.getClassLoader()); node.setClassTypeResolver(classTypeResolver); node.jjtAccept(classTypeResolver, data); } // Placeholder for checkInitStatement and Info class, assumed to be defined elsewhere protected boolean checkInitStatement(Token initToken, Info info) { // Implementation depends on specific rule logic return true; // Placeholder } protected void addViolationWithMessage(Object data, ASTPrimaryExpression node, String messageKey) { // Implementation depends on specific rule logic System.out.println("Violation: " + messageKey); } protected static class Info { boolean executorsUsed = false; // other fields as needed } } // Example usage: ThreadPoolCreationRule prevents Executors.newXXX() usage class ThreadPoolCreationRule extends AbstractAliRule { private static final String EXECUTORS_NEW = Executors.class.getSimpleName() + DOT + NEW; @Override public Object visit(ASTCompilationUnit node, Object data) { Object superResult = super.visit(node, data); Info info = new Info(); List importDeclarations = node.findChildrenOfType(ASTImportDeclaration.class); for (ASTImportDeclaration importDeclaration : importDeclarations) { ASTName name = importDeclaration.getFirstChildOfType(ASTName.class); if (name != null) { info.executorsUsed = info.executorsUsed || (name.getType() == Executors.class || Executors.class.getName().equals(name.getImage())); } } List primaryExpressions = node.findDescendantsOfType(ASTPrimaryExpression.class); for(ASTPrimaryExpression primaryExpression : primaryExpressions){ Token initToken = (Token)primaryExpression.jjtGetFirstToken(); if (!checkInitStatement(initToken, info)) { addViolationWithMessage(data, primaryExpression, "java.concurrent.ThreadPoolCreationRule.violation.msg"); } } return superResult; } } ``` -------------------------------- ### Java: Creating a Thread with a Specific Name Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/并发处理.md This example demonstrates how to create a custom Thread class and assign a meaningful name to it for better debugging and traceability in concurrent applications. ```java public class TimerTaskThread extends Thread { public TimerTaskThread() { super.setName("TimerTaskThread"); ... } } ``` -------------------------------- ### Code Alignment Recommendation Example Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/代码格式.md Illustrates the recommendation against aligning code with extra spaces for visual neatness. It shows that separate declarations with different types and values do not need to be vertically aligned, promoting simpler code maintenance. ```java int a = 3; long b = 4L; float c = 5F; StringBuffer sb = new StringBuffer(); ``` -------------------------------- ### Line Wrapping for Long Lines Example Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/代码格式.md Shows how to handle lines exceeding the 120-character limit by wrapping them. The example demonstrates the required 4-space indentation for wrapped lines and the placement of operators and method calls. ```java StringBuffer sb = new StringBuffer(); // 超过120个字符的情况下,换行缩进4个空格,点号和方法名称一起换行 sb.append("zi").append("xin")... .append("huang")... .append("huang")... .append("huang"); ``` -------------------------------- ### Configure P3C PMD in Gradle Source: https://context7.com/alibaba/p3c/llms.txt Integrates P3C PMD rules into a Gradle build script for continuous code quality enforcement. This setup applies the PMD plugin, specifies the PMD tool version, and configures the rulesets to be used. It also declares the p3c-pmd dependency. ```gradle apply plugin: 'pmd' pmd { toolVersion = '6.15.0' consoleOutput = true ruleSetFiles = files( "rulesets/java/ali-comment.xml", "rulesets/java/ali-concurrent.xml", "rulesets/java/ali-naming.xml", "rulesets/java/ali-oop.xml", "rulesets/java/ali-set.xml" ) sourceSets = [sourceSets.main] } dependencies { pmd 'com.alibaba.p3c:p3c-pmd:2.1.1' } // Run PMD check // gradle pmdMain ``` -------------------------------- ### Java: ThreadSafe Date Formatting with ThreadLocal Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/并发处理.md Demonstrates a thread-safe way to handle SimpleDateFormat by using ThreadLocal. This approach ensures each thread gets its own instance, preventing concurrency issues without requiring explicit synchronization. ```java private static final ThreadLocal df = new ThreadLocal() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; ``` -------------------------------- ### Configure P3C PMD Rule: ThreadPoolCreationRule Source: https://context7.com/alibaba/p3c/llms.txt Defines a custom PMD rule for Java, specifically 'ThreadPoolCreationRule', within an XML configuration file. This rule targets the creation of thread pools, specifying severity, description, and providing both negative and positive code examples for clarity. ```xml java.concurrent.ThreadPoolCreationRule.rule.desc 1 (1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); pool.execute(()-> System.out.println(Thread.currentThread().getName())); pool.shutdown(); ]]> ``` -------------------------------- ### Thread Naming Convention in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Provides a positive example of assigning a meaningful name to a thread when extending the Thread class in Java. This aids in debugging and error tracing, especially when dealing with multiple threads or thread pools. ```java public class TimerTaskThread extends Thread { public TimerTaskThread(){ super.setName("TimerTaskThread"); ... } } ``` -------------------------------- ### Get Current Milliseconds Efficiently Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/异常日志/其他.md Use `System.currentTimeMillis()` for obtaining the current time in milliseconds. `new Date().getTime()` is less efficient. For nanosecond precision, use `System.nanoTime()`, and for JDK 8+, consider using the `Instant` class for time-related operations. ```java long currentTimeMillis = System.currentTimeMillis(); ``` ```java long nanoTime = System.nanoTime(); ``` -------------------------------- ### Run P3C Idea Plugin Source: https://github.com/alibaba/p3c/blob/master/idea-plugin/README.md Commands to run the P3C Idea plugin, with an option to specify the IDEA version. ```shell cd p3c-idea ../gradlew runIde # run specific IDEA ../gradlew runIde -Pidea_version=2018.3 ``` -------------------------------- ### Execute P3C PMD Standalone via CLI Source: https://context7.com/alibaba/p3c/llms.txt Provides commands to build a fat JAR of P3C PMD with dependencies and then execute PMD scans directly from the command line. It demonstrates how to generate reports in different formats like text, HTML, and XML, suitable for various integration needs. ```bash # Build the fat JAR with dependencies mvn clean install assembly:single # Run PMD scan on Java source code java -cp p3c-pmd/target/p3c-pmd-jar-with-dependencies.jar \ net.sourceforge.pmd.PMD \ -d /path/to/source \ -R rulesets/java/ali-comment.xml,rulesets/java/ali-concurrent.xml,rulesets/java/ali-naming.xml \ -f text # Generate HTML report java -cp p3c-pmd/target/p3c-pmd-jar-with-dependencies.jar \ net.sourceforge.pmd.PMD \ -d /path/to/source \ -R rulesets/java/ali-comment.xml \ -f html \ -r report.html # XML format for CI/CD integration java -cp p3c-pmd/target/p3c-pmd-jar-with-dependencies.jar \ net.sourceforge.pmd.PMD \ -d src/main/java \ -R rulesets/java/ali-naming.xml \ -f xml \ -r violations.xml ``` -------------------------------- ### Build P3C Idea Plugin Source: https://github.com/alibaba/p3c/blob/master/idea-plugin/README.md Commands to clean and build the P3C Idea plugin. Requires Gradle 3.0+ and JDK 1.8+. ```shell cd p3c-idea ../gradlew clean buildPlugin ``` -------------------------------- ### Java: Javadoc for Classes, Methods, and Variables Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Mandates the use of Javadoc comments ('/** ... */') for classes, class variables, and methods to provide comprehensive documentation. This includes method instructions, parameter descriptions, return values, and potential exceptions, improving code discoverability and maintainability. ```java /** * This is a Javadoc comment for a class. * @author John Doe * @since 2023-10-27 */ public class MyClass { /** * Represents the name of the user. */ private String userName; /** * Initializes a new instance of the {@link MyClass} class. * @param name The name to set for the user. */ public MyClass(String name) { this.userName = name; } /** * Gets the user's name. * @return The current user's name. */ public String getUserName() { return userName; } } ``` -------------------------------- ### Register QuickFixes in a Map (Kotlin) Source: https://context7.com/alibaba/p3c/llms.txt This snippet shows how to register various QuickFix implementations in a mutable map in Kotlin. The map keys are rule names, and values are the corresponding QuickFix objects. It also includes a utility function to retrieve a QuickFix based on a rule name and an on-the-fly execution flag. ```kotlin object QuickFixes { val quickFixes = mutableMapOf( VmQuietReferenceQuickFix.ruleName to VmQuietReferenceQuickFix, ClassMustHaveAuthorQuickFix.ruleName to ClassMustHaveAuthorQuickFix, ConstantFieldShouldBeUpperCaseQuickFix.ruleName to ConstantFieldShouldBeUpperCaseQuickFix, AvoidStartWithDollarAndUnderLineNamingQuickFix.ruleName to AvoidStartWithDollarAndUnderLineNamingQuickFix, LowerCamelCaseVariableNamingQuickFix.ruleName to LowerCamelCaseVariableNamingQuickFix ) fun getQuickFix(rule: String, isOnTheFly: Boolean): LocalQuickFix? { val quickFix = quickFixes[rule] ?: return null if (!quickFix.onlyOnThFly) { return quickFix } if (!isOnTheFly && quickFix.onlyOnThFly) { return null } return quickFix } } ``` -------------------------------- ### Eclipse Plugin Configuration for Menu Contributions, Markers, and Views Source: https://context7.com/alibaba/p3c/llms.txt Defines extension points for an Eclipse plugin in `plugin.xml`. It configures views, commands, handlers, menu contributions, custom markers, and marker resolution generators for quick fixes. This XML file is essential for integrating P3C functionality into the Eclipse IDE. ```xml ``` -------------------------------- ### Java Whitelist Loader Service Source: https://context7.com/alibaba/p3c/llms.txt Loads and provides access to rule configurations defined in the namelist.properties file. It parses JSON arrays from the properties file into a map for efficient lookup. ```java public class NameListServiceImpl implements NameListService { private static final Map> NAME_LISTS = new HashMap<>(); static { Properties properties = new Properties(); try (InputStream is = NameListServiceImpl.class .getResourceAsStream("/namelist.properties")) { properties.load(is); for (String key : properties.stringPropertyNames()) { String value = properties.getProperty(key); List list = parseJsonArray(value); NAME_LISTS.put(key, list); } } catch (IOException e) { e.printStackTrace(); } } @Override public List getNameList(String ruleClass, String configKey) { String key = ruleClass + "_" + configKey; return NAME_LISTS.getOrDefault(key, Collections.emptyList()); } } ``` -------------------------------- ### Get Current Millisecond Time in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Use `System.currentTimeMillis()` to obtain the current time in milliseconds. For more accurate time measurements, especially for time statistics, `System.nanoTime()` or the `Instant` class (in JDK8+) is recommended. Avoid using `new Date().getTime()`. ```java import java.time.Instant; public class TimeUtils { public long getCurrentTimeMillis() { // Recommended way to get current time in milliseconds return System.currentTimeMillis(); } public long getCurrentTimeNanos() { // For more accurate time measurements return System.nanoTime(); } public Instant getInstantTime() { // Using Instant class in JDK8+ for time operations return Instant.now(); } } ``` -------------------------------- ### Java: Thread-Safe Singleton with Volatile Keyword Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/并发处理.md Illustrates a common pattern for implementing a thread-safe singleton using the double-checked locking mechanism combined with the `volatile` keyword. This ensures lazy initialization and prevents race conditions. ```java class Singleton { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other methods and fields... } class Helper {} ``` -------------------------------- ### IntelliJ IDEA Plugin Configuration Source: https://context7.com/alibaba/p3c/llms.txt Configuration file for an IntelliJ IDEA plugin. It defines the plugin's metadata, dependencies on other IntelliJ modules, and registers custom actions, services, and providers. This enables features like custom code inspections and check-in handlers within the IDE. Uses XML format specific to IntelliJ plugin development. ```xml com.alibaba.p3c.smartfox Alibaba Java Coding Guidelines 2.0.0 com.intellij.velocity com.intellij.modules.java com.intellij.modules.platform ``` -------------------------------- ### Java: Single and Multi-line Comments Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Specifies the correct placement and style for single-line ('//') and multi-line ('/* */') comments within methods. Single-line comments should precede the commented code, and alignment should be carefully considered for readability. ```java public void myMethod() { // This is a single-line comment above the code int x = 10; /* * This is a multi-line comment * explaining the following block. */ if (x > 5) { System.out.println("x is greater than 5"); } } ``` -------------------------------- ### Properties for Rule Configuration Whitelists Source: https://context7.com/alibaba/p3c/llms.txt Defines configurable whitelists and type mappings for various PMD rules using a properties file. This enables customization of rule behavior without modifying the rule code itself. ```properties # namelist.properties - Rule configuration ConstantFieldShouldBeUpperCaseRule_LOG_VARIABLE_TYPE_SET=["Log","Logger"] ConstantFieldShouldBeUpperCaseRule_WHITE_LIST=["serialVersionUID"] LowerCamelCaseVariableNamingRule_WHITE_LIST=["DAOImpl"] PojoMustOverrideToStringRule_POJO_SUFFIX_SET=["DO","DTO","VO","BO"] UndefineMagicConstantRule_LITERAL_WHITE_LIST=["0","1","\"\"","0.0","1.0","-1","0L","1L"] MethodReturnWrapperTypeRule_PRIMITIVE_TYPE_TO_WAPPER_TYPE={"int":"Integer","boolean":"Boolean","byte":"Byte","short":"Short","long":"Long","float":"Float","double":"Double","char":"Character"} CollectionInitShouldAssignCapacityRule_COLLECTION_TYPE=["HashMap","ConcurrentHashMap","Hashtable","HashSet","LinkedHashSet","LinkedHashMap"] ClassNamingShouldBeCamelRule_CLASS_NAMING_WHITE_LIST=["Hbase","HBase","ID"] ``` -------------------------------- ### Implement QuickFix for Missing @author JavaDoc Tag (Kotlin) Source: https://context7.com/alibaba/p3c/llms.txt This Kotlin snippet provides a QuickFix implementation to automatically add missing '@author' JavaDoc tags in class declarations. It handles both creating new JavaDoc comments and adding the tag to existing ones. The author's username is dynamically fetched from system properties or environment variables. ```kotlin object ClassMustHaveAuthorQuickFix : InspectionGadgetsFix(), AliQuickFix { val tag = "@author ${System.getProperty("user.name") ?: System.getenv("USER")}" override fun doFix(project: Project?, descriptor: ProblemDescriptor?) { descriptor ?: return val psiClass = descriptor.psiElement as? PsiClass ?: return val document = psiClass.docComment val psiFacade = JavaPsiFacade.getInstance(project) val factory = psiFacade.elementFactory if (document == null) { // Create new JavaDoc val doc = factory.createDocCommentFromText(""" /** * $tag */ """) if (psiClass.isEnum) { psiClass.containingFile.addAfter(doc, psiClass.prevSibling) } else { psiClass.addBefore(doc, psiClass.firstChild) } return } // Add to existing JavaDoc if (document.tags.isNotEmpty()) { document.addBefore(factory.createDocTagFromText(tag), document.tags[0]) return } document.add(factory.createDocTagFromText(tag)) } override val ruleName: String get() = "ClassMustHaveAuthorRule" override val onlyOnTheFly: Boolean get() = true override fun getName(): String { return I18nResources.getMessage("com.alibaba.p3c.idea.quickfix.ClassMustHaveAuthorQuickFix") } override fun getFamilyName(): String { return name } } ``` -------------------------------- ### Configure P3C PMD in Maven Source: https://context7.com/alibaba/p3c/llms.txt Integrates P3C PMD rules into a Maven project's build process for automated code quality checks. This configuration ensures that PMD scans Java code during the 'verify' phase using specified Alibaba rulesets. Dependencies on the p3c-pmd artifact are also managed. ```xml org.apache.maven.plugins maven-pmd-plugin 3.11.0 UTF-8 1.8 rulesets/java/ali-comment.xml rulesets/java/ali-concurrent.xml rulesets/java/ali-naming.xml rulesets/java/ali-oop.xml rulesets/java/ali-set.xml rulesets/java/ali-flowcontrol.xml rulesets/java/ali-exception.xml rulesets/java/ali-constant.xml rulesets/java/ali-other.xml rulesets/java/ali-orm.xml com.alibaba.p3c p3c-pmd 2.1.1 verify check ``` -------------------------------- ### Java: Javadoc for Abstract Methods and Interfaces Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Requires Javadoc comments for abstract methods and methods within interfaces. These comments must detail the method's purpose, parameters, return values, and any exceptions that might be thrown, ensuring clear understanding of contracts. ```java /** * An interface defining operations for data processing. * @author Jane Smith * @since 2023-10-27 */ public interface DataProcessor { /** * Processes the input data. * @param data The data to be processed. * @return The processed data. * @throws IllegalArgumentException if the input data is invalid. */ Object process(Object data) throws IllegalArgumentException; } ``` -------------------------------- ### Dynamically Generate Inspection Classes with Javassist (Kotlin) Source: https://context7.com/alibaba/p3c/llms.txt This snippet demonstrates the dynamic generation of inspection classes using Javassist in Kotlin. It takes PMD rules and creates corresponding inspection classes, injecting rule names as static fields. This approach allows for runtime creation of inspection tools based on defined rules. ```kotlin class AliLocalInspectionToolProvider : InspectionToolProvider { companion object { val ruleInfoMap: MutableMap = Maps.newHashMap() val ruleNames: MutableList = Lists.newArrayList() private val CLASS_LIST = Lists.newArrayList>() private val nativeInspectionToolClass = arrayListOf( AliMissingOverrideAnnotationInspection::class.java, AliAccessStaticViaInstanceInspection::class.java, AliDeprecationInspection::class.java, MapOrSetKeyShouldOverrideHashCodeEqualsInspection::class.java ) init { I18nResources.changeLanguage(P3cConfig::class.java.getService().locale) initPmdInspection() initNativeInspection() } private fun initPmdInspection() { for (ri in newRuleInfos()) { ruleNames.add(ri.rule.name) ruleInfoMap.put(ri.rule.name, ri) } val pool = ClassPool.getDefault() for (ruleInfo in ruleInfoMap.values) { // Dynamically create inspection class val cc = pool.get(DelegatePmdInspection::class.java.name) cc.name = ruleInfo.rule.name + "Inspection" // Inject rule name as static field val ctField = cc.getField("ruleName") cc.removeField(ctField) val value = """ + ruleInfo.rule.name + """ val newField = CtField.make("private String ruleName = $value;", cc) cc.addField(newField, value) CLASS_LIST.add(cc.toClass() as Class) } } fun getRuleSet(ruleSetName: String): RuleSet { val factory = RuleSetFactory() return factory.createRuleSet(ruleSetName.replace("/", "-")) } } override fun getInspectionClasses(): Array> { return CLASS_LIST.toTypedArray() } } ``` -------------------------------- ### Initialize Collection with Specific Capacity in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Recommends initializing Java collections, particularly `ArrayList`, with a specific initial capacity when the expected size is known. This can improve performance by reducing the number of internal array reallocations. The `ArrayList(int initialCapacity)` constructor should be used for this purpose. ```java ArrayList list = new ArrayList<>(10); // Initialize with capacity 10 ``` -------------------------------- ### Java Internationalization Resource Bundle Loader Source: https://context7.com/alibaba/p3c/llms.txt Custom XML-based resource bundle loader for internationalization. Supports loading messages from XML files based on the specified language (defaults to Chinese). It provides methods to change language and retrieve localized messages, handling missing resources gracefully. Dependencies include Java's `ResourceBundle` and `MessageFormat`. ```java public class I18nResources { private static String lang = System.getProperty("pmd.language", "zh"); private static Locale currentLocale; private static ResourceBundle resourceBundle = changeLanguage(lang); public static ResourceBundle changeLanguage(String language) { Locale locale = Locale.CHINESE.getLanguage().equals(language) ? Locale.CHINESE : Locale.ENGLISH; return changeLanguage(locale); } public static String getMessage(String key) { try { return resourceBundle.getString(key).trim(); } catch (MissingResourceException e) { return key; } } public static String getMessage(String key, Object... args) { String message = getMessage(key); return MessageFormat.format(message, args); } public static class XmlControl extends Control { @Override public List getFormats(String baseName) { return Collections.singletonList("xml"); } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IOException { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "xml"); InputStream stream = loader.getResourceAsStream(resourceName); return new XmlResourceBundle(stream); } } } ``` -------------------------------- ### Precompile Regex for Performance in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md When using regular expressions in Java, precompiling the pattern improves matching performance. The compiled pattern should preferably be stored as a constant to avoid repeated compilation within method bodies. ```java import java.util.regex.Pattern; public class RegexExample { // Precompile the pattern and store it as a constant private static final Pattern MY_PATTERN = Pattern.compile("your_regex_here"); public void processString(String text) { // Use the precompiled pattern for matching if (MY_PATTERN.matcher(text).matches()) { System.out.println("Matches the pattern."); } } } ``` -------------------------------- ### POJO Member Initialization Rule in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md When defining POJO classes (DO, DTO, VO, etc.), avoid assigning default values to members. This encourages explicit assignment and helps consumers identify potential issues like NullPointerExceptions. ```java // Correct POJO Definition (No Default Values) public class ProductDTO { private String name; private Double price; // No default values assigned here } // Incorrect POJO Definition (With Default Values - Avoid) // public class ProductDTO { // private String name = ""; // Avoid default empty string // private Double price = 0.0; // Avoid default zero // } ``` -------------------------------- ### Java: Atomic Operations with AtomicInteger Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/编程规约/并发处理.md Shows how to use `AtomicInteger` for thread-safe increment operations in high-concurrency scenarios. This is preferred over manual synchronization for simple counters. ```java AtomicInteger count = new AtomicInteger(); count.addAndGet(1); ``` -------------------------------- ### Maven Dependency for P3C-PMD Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Specifies how to include P3C-PMD as a dependency in a Maven project. This allows the project to leverage P3C-PMD's static analysis capabilities for enforcing Alibaba Java Coding Guidelines. ```xml com.alibaba.p3c p3c-pmd 2.1.1 ``` -------------------------------- ### Gradle Dependency for P3C-PMD Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Illustrates how to add P3C-PMD as a dependency in a Gradle project. This enables the use of P3C-PMD for code quality checks according to Alibaba's standards. ```groovy compile 'com.alibaba.p3c:p3c-pmd:2.1.1' ``` -------------------------------- ### Pre-compile Regular Expressions for Performance Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/异常日志/其他.md Pre-compiling regular expressions significantly improves matching speed. Avoid compiling patterns repeatedly within method bodies. ```java Pattern pattern = Pattern.compile(规则); // Use pattern for matching... ``` -------------------------------- ### Java: Class Author and Date Information Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Mandates that every class includes author(s) and date information within its Javadoc comments. This helps in tracking code ownership and understanding the history of changes. ```java /** * A sample class with author and date information. * @author Alice Wonderland * @date 2023-10-27 */ public class SampleClass {} ``` -------------------------------- ### Primitive vs. Wrapper Types in Java POJOs and RPCs Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md POJO members should be wrapper classes, while RPC method arguments and return values should also be wrappers. Local variables are recommended to be primitive types. This distinction helps manage nullability and explicitly indicate missing or erroneous data. ```java // POJO Member (Wrapper Class Recommended) public class UserProfile { private String username; // Wrapper class private Integer age; // Wrapper class } // RPC Method Signature (Wrapper Classes Recommended) public class UserService { public String getUserName(Long userId) { // Wrapper class argument // ... return userName; // Wrapper class return } } // Local Variable (Primitive Type Recommended) public void processData() { int count = 10; // Primitive type // ... } ``` -------------------------------- ### Implementing toString() in Java POJOs Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md The toString method must be implemented in all POJO classes. If the current class extends another POJO, call super.toString() at the beginning of the implementation. This aids in debugging by providing easy access to object property values. ```java public class Person { private String name; private int age; @Override public String toString() { return "Person{" + "name='" + name + '\'" + ", age=" + age + '}'; } } public class Employee extends Person { private String employeeId; @Override public String toString() { return "Employee{" + "employeeId='" + employeeId + '\'" + ", " + super.toString() + // Call super.toString() '}'; } } ``` -------------------------------- ### Java Test Case for Thread Pool Creation Rule Source: https://context7.com/alibaba/p3c/llms.txt An XML-defined test case for the ThreadPoolCreationRule, specifying expected violations and line numbers. It includes sample Java code that is expected to trigger violations related to thread pool creation. ```xml Executors.new violations 5 9,11,16,17,18 System.out.println("test")); } } ]]> ``` -------------------------------- ### Precise Violation Reporting Utility for Java AST Elements Source: https://context7.com/alibaba/p3c/llms.txt This Java utility class provides methods for reporting static analysis violations with precise positioning. It intelligently highlights specific AST elements like variable names, method names, or class names for clearer error reporting. ```java // ViolationUtils.java - Precise violation reporting public class ViolationUtils { public static void addViolationWithPrecisePosition( AbstractRule rule, Node node, Object data, String message) { // For field declarations, highlight the variable name if (node instanceof ASTFieldDeclaration) { ASTVariableDeclaratorId variableDeclaratorId = node.getFirstDescendantOfType(ASTVariableDeclaratorId.class); addViolation(rule, variableDeclaratorId, data, message); return; } // For methods, highlight the method name if (node instanceof ASTMethodDeclaration) { ASTMethodDeclarator declarator = node.getFirstChildOfType(ASTMethodDeclarator.class); addViolation(rule, declarator, data, message); return; } // For classes, highlight the class name if (node instanceof ASTClassOrInterfaceDeclaration) { ASTClassOrInterfaceDeclaration classNode = (ASTClassOrInterfaceDeclaration) node; int lineNumber = classNode.getBeginLine(); int columnNumber = classNode.getBeginColumn(); // Custom line/column for class name position addViolationAtPosition(rule, node, data, message, lineNumber, columnNumber); return; } addViolation(rule, node, data, message); } private static void addViolation(AbstractRule rule, Node node, Object data, String message) { rule.addViolationWithMessage(data, node, message); } } ``` -------------------------------- ### Add p3c-common as Plugin Dependency Source: https://github.com/alibaba/p3c/blob/master/idea-plugin/README.md Groovy code snippet to include p3c-common as a project dependency in an Idea plugin. ```groovy compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' ``` -------------------------------- ### Java: Handling NullPointerExceptions with Optional Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Promotes the use of `Optional` (Java 8+) to avoid `NullPointerException`. This is particularly useful for method chaining and handling potential null return values from collections, databases, or RPC calls, leading to more robust code. ```java import java.util.Optional; public class OptionalExample { public Optional findUserById(int id) { // Simulate a database call that might return null if (id == 1) { return Optional.of("Alice"); } else { return Optional.empty(); } } public static void main(String[] args) { OptionalExample example = new OptionalExample(); example.findUserById(1).ifPresent(user -> System.out.println("User found: " + user)); example.findUserById(2).ifPresentOrElse( user -> System.out.println("User found: " + user), () -> System.out.println("User not found.") ); } } ``` -------------------------------- ### Thread-Safe Date Formatting with ThreadLocal Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Demonstrates a thread-safe approach to handling date formatting in Java using `ThreadLocal` with `SimpleDateFormat`. This prevents issues that can arise from sharing a non-thread-safe `SimpleDateFormat` instance across multiple threads, particularly when defined as a static variable. ```java private static final ThreadLocal df = new ThreadLocal() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; ``` -------------------------------- ### Java: Javadoc for Enumeration Fields Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Requires all enumeration type fields to be commented using Javadoc style. This ensures that the purpose and meaning of each enum constant are clearly documented. ```java /** * Represents the days of the week. */ public enum Day { /** Monday */ MONDAY, /** Tuesday */ TUESDAY, /** Wednesday */ WEDNESDAY, /** Thursday */ THURSDAY, /** Friday */ FRIDAY, /** Saturday */ SATURDAY, /** Sunday */ SUNDAY } ``` -------------------------------- ### Java: Use Braces in Control Flow Statements Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Ensures readability and prevents errors by consistently using braces for if, else, for, do, and while statements, even when the body contains a single statement. This avoids the pitfall of single-line statements being unintentionally excluded from the control flow. ```java if (condition) { statements; } ``` -------------------------------- ### Comparing Wrapper Classes in Java Source: https://github.com/alibaba/p3c/blob/master/p3c-pmd/README.md Wrapper classes (e.g., Integer, Boolean) should be compared using the equals method, not the '==' operator. While '==' might work for cached values (-128 to 127 for Integer), relying on this behavior is fragile due to JVM implementation details. ```java // Example with Integer wrapper class Integer var1 = 100; Integer var2 = 100; // Recommended: using equals() boolean isEqual = var1.equals(var2); // Not recommended: relies on Integer caching for values between -128 and 127 // boolean isEqual = var1 == var2; ``` -------------------------------- ### Reduce TCP time_wait Timeout (Linux) Source: https://github.com/alibaba/p3c/blob/master/p3c-gitbook/工程结构/服务器.md This snippet shows how to reduce the TCP time_wait timeout in Linux by modifying the sysctl.conf file. The default timeout of 240 seconds can lead to too many connections in time_wait state under high concurrency, potentially preventing new connections. Setting it to 30 seconds is recommended. ```shell net.ipv4.tcp_fin_timeout = 30 ```