From fdfc82f1dc0edf073d7414034b3a9cdcb3b56830 Mon Sep 17 00:00:00 2001 From: "caikang.ck" Date: Wed, 12 Jun 2019 14:56:03 +0800 Subject: [PATCH] v2.0.0 1. pmd -> 6.15.0 2. idea min version 2016.1 3. jdk min version 1.8 --- .../feature.xml | 2 +- .../pom.xml | 2 +- .../META-INF/MANIFEST.MF | 5 +- .../pom.xml | 8 +- .../smartfox/eclipse/job/CodeAnalysis.kt | 4 +- .../eclipse/pmd/rule/AbstractEclipseRule.kt | 4 +- .../pom.xml | 2 +- eclipse-plugin/pom.xml | 8 +- idea-plugin/build.gradle | 4 +- idea-plugin/gradle.properties | 9 +- .../gradle/wrapper/gradle-wrapper.properties | 2 +- idea-plugin/p3c-common/build.gradle | 6 +- .../p3c/idea/action/AliInspectionAction.kt | 2 +- .../action/ToggleProjectInspectionAction.kt | 4 +- .../com/alibaba/p3c/idea/config/P3cConfig.kt | 11 +- .../p3c/idea/config/SmartFoxProjectConfig.kt | 13 +- .../inspection/AliPmdInspectionInvoker.kt | 4 +- .../standalone/AliDeprecationInspection.kt | 4 +- .../AliMissingOverrideAnnotationInspection.kt | 2 +- ...yShouldOverrideHashCodeEqualsInspection.kt | 6 +- .../alibaba/p3c/idea/pmd/AliPmdProcessor.kt | 23 +- .../p3c/idea/pmd/SourceCodeProcessor.kt | 192 ++-- .../p3c/idea/pmd/index/AliPmdProcessor.kt | 51 - .../LowerCamelCaseVariableNamingQuickFix.kt | 16 +- idea-plugin/p3c-idea/build.gradle | 3 +- .../src/main/resources/META-INF/plugin.xml | 13 +- p3c-pmd/pom.xml | 174 ++- .../com/alibaba/p3c/pmd/I18nResources.java | 14 +- .../rule/comment/AbstractAliCommentRule.java | 2 +- .../rule/comment/ClassMustHaveAuthorRule.java | 62 +- .../CommentsMustBeJavadocFormatRule.java | 74 +- .../AvoidConcurrentCompetitionRandomRule.java | 6 +- .../AvoidManuallyCreateThreadRule.java | 5 +- .../ThreadLocalShouldRemoveRule.java | 23 +- .../concurrent/ThreadPoolCreationRule.java | 8 +- .../concurrent/ThreadShouldSetNameRule.java | 40 +- .../constant/UndefineMagicConstantRule.java | 8 +- .../TransactionMustHaveRollbackRule.java | 7 +- .../java/rule/flowcontrol/NeedBraceRule.java | 6 +- .../LowerCamelCaseVariableNamingRule.java | 25 +- .../TestClassShouldEndWithTestNamingRule.java | 2 +- .../BigDecimalAvoidDoubleConstructorRule.java | 78 ++ .../oop/PojoMustUsePrimitiveFieldRule.java | 6 +- .../java/rule/oop/PojoNoDefaultValueRule.java | 3 +- .../orm/IbatisMethodQueryForListRule.java | 10 +- .../AvoidDoubleOrFloatEqualCompareRule.java | 42 + .../AvoidPatternCompileInMethodRule.java | 3 +- .../java/rule/other/MethodTooLongRule.java | 90 +- .../other/UseRightCaseForDateFormatRule.java | 7 + .../pmd/lang/java/rule/util/NodeUtils.java | 5 + .../java/util/StringAndCharConstants.java | 2 + .../p3c/pmd/lang/java/util/VariableUtils.java | 18 + p3c-pmd/src/main/resources/messages.xml | 54 +- p3c-pmd/src/main/resources/messages_en.xml | 52 +- .../resources/rulesets/java/ali-comment.xml | 2 +- .../rulesets/java/ali-concurrent.xml | 20 +- .../resources/rulesets/java/ali-constant.xml | 12 +- .../resources/rulesets/java/ali-exception.xml | 1 + .../rulesets/java/ali-flowcontrol.xml | 1 + .../resources/rulesets/java/ali-naming.xml | 1 + .../main/resources/rulesets/java/ali-oop.xml | 33 +- .../main/resources/rulesets/java/ali-orm.xml | 1 + .../resources/rulesets/java/ali-other.xml | 29 +- .../main/resources/rulesets/java/ali-set.xml | 25 +- .../main/resources/rulesets/vm/ali-other.xml | 2 +- .../pmd/lang/java/rule/oop/OopRuleTest.java | 1 + .../lang/java/rule/other/OtherRulesTest.java | 8 +- ...hodOrInterfaceMethodMustUseJavadocRule.xml | 12 +- .../xml/AvoidCommentBehindStatementRule.xml | 4 +- .../comment/xml/ClassMustHaveAuthorRule.xml | 69 +- .../xml/CommentsMustBeJavadocFormatRule.xml | 4 +- .../xml/EnumConstantsMustHaveCommentRule.xml | 6 +- .../comment/xml/RemoveCommentedCodeRule.xml | 4 +- .../AvoidCallStaticSimpleDateFormatRule.xml | 6 +- .../AvoidConcurrentCompetitionRandomRule.xml | 4 +- .../xml/AvoidManuallyCreateThreadRule.xml | 4 +- .../rule/concurrent/xml/AvoidUseTimerRule.xml | 4 +- .../xml/CountDownShouldInFinallyRule.xml | 4 +- .../xml/ThreadLocalShouldRemoveRule.xml | 4 +- .../concurrent/xml/ThreadPoolCreationRule.xml | 4 +- .../xml/ThreadShouldSetNameRule.xml | 27 +- .../xml/UndefineMagicConstantRule.xml | 14 +- .../java/rule/constant/xml/UpperEllRule.xml | 6 +- .../xml/AvoidReturnInFinallyRule.xml | 4 +- .../xml/MethodReturnWrapperTypeRule.xml | 6 +- .../xml/TransactionMustHaveRollbackRule.xml | 31 +- .../xml/AvoidComplexConditionRule.xml | 76 +- .../xml/AvoidNegationOperatorRule.xml | 4 +- .../rule/flowcontrol/xml/NeedBraceRule.xml | 4 +- .../flowcontrol/xml/SwitchStatementRule.xml | 4 +- ...ClassShouldStartWithAbstractNamingRule.xml | 9 +- .../xml/ArrayNamingShouldHaveBracketRule.xml | 7 +- ...dStartWithDollarAndUnderLineNamingRule.xml | 6 +- ...ooleanPropertyShouldNotStartWithIsRule.xml | 6 +- .../xml/ClassNamingShouldBeCamelRule.xml | 6 +- .../ConstantFieldShouldBeUpperCaseRule.xml | 6 +- ...ceptionClassShouldEndWithExceptionRule.xml | 6 +- .../xml/LowerCamelCaseVariableNamingRule.xml | 60 +- .../rule/naming/xml/PackageNamingRule.xml | 6 +- ...ServiceOrDaoClassShouldEndWithImplRule.xml | 6 +- .../TestClassShouldEndWithTestNamingRule.xml | 10 +- .../BigDecimalAvoidDoubleConstructorRule.xml | 29 + .../java/rule/oop/xml/EqualsAvoidNullRule.xml | 298 ++--- .../oop/xml/PojoMustOverrideToStringRule.xml | 4 +- .../oop/xml/PojoMustUsePrimitiveFieldRule.xml | 10 +- .../rule/oop/xml/PojoNoDefaultValueRule.xml | 10 +- .../java/rule/oop/xml/StringConcatRule.xml | 6 +- .../rule/oop/xml/WrapperTypeEqualityRule.xml | 14 +- .../orm/xml/IbatisMethodQueryForListRule.xml | 6 +- .../xml/AvoidApacheBeanUtilsCopyRule.xml | 6 +- .../AvoidDoubleOrFloatEqualCompareRule.xml | 104 ++ .../xml/AvoidMissUseOfMathRandomRule.xml | 6 +- .../other/xml/AvoidNewDateGetTimeRule.xml | 6 +- .../xml/AvoidPatternCompileInMethodRule.xml | 6 +- .../java/rule/other/xml/MethodTooLongRule.xml | 1007 ++++++++++++----- .../xml/UseRightCaseForDateFormatRule.xml | 6 +- ...astExceptionWithSubListToArrayListRule.xml | 22 +- .../xml/ClassCastExceptionWithToArrayRule.xml | 22 +- ...CollectionInitShouldAssignCapacityRule.xml | 22 +- ...ntExceptionWithModifyOriginSubListRule.xml | 24 +- .../set/xml/DontModifyInForeachCircleRule.xml | 30 +- ...supportedExceptionWithModifyAsListRule.xml | 6 +- .../xml/UseQuietReferenceNotationRule.xml | 6 +- 123 files changed, 2362 insertions(+), 1083 deletions(-) delete mode 100644 idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/AliPmdProcessor.kt create mode 100644 p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java create mode 100644 p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java create mode 100644 p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java create mode 100644 p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml create mode 100644 p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml index 0a8a0ec..a86c41f 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/feature.xml @@ -2,7 +2,7 @@ diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml index 3f35461..b608e72 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.feature/pom.xml @@ -5,7 +5,7 @@ com.alibaba.smartfox.eclipse smartfox-eclipse - 1.0.6-SNAPSHOT + 2.0.0-SNAPSHOT com.alibaba.smartfox.eclipse.feature eclipse-feature diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF index e03d534..0076a1c 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.alibaba.smartfox.eclipse.plugin Bundle-SymbolicName: com.alibaba.smartfox.eclipse.plugin;singleton:=true -Bundle-Version: 1.0.6.qualifier +Bundle-Version: 2.0.0.qualifier Bundle-Activator: com.alibaba.smartfox.eclipse.SmartfoxActivator Bundle-Vendor: Alibaba Require-Bundle: org.eclipse.ui, @@ -22,7 +22,7 @@ Require-Bundle: org.eclipse.ui, org.eclipse.equinox.p2.metadata.repository, org.eclipse.equinox.p2.ui, org.eclipse.equinox.p2.metadata -Bundle-RequiredExecutionEnvironment: JavaSE-1.7 +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Bundle-ActivationPolicy: lazy Bundle-ClassPath: target/lib/antlr-runtime.jar, target/lib/antlr4-runtime.jar, @@ -51,6 +51,7 @@ Bundle-Localization: plugin Export-Package: com.alibaba.smartfox.eclipse, com.alibaba.smartfox.eclipse.handler, com.alibaba.smartfox.eclipse.job, + com.alibaba.smartfox.eclipse.marker, com.alibaba.smartfox.eclipse.pmd, com.alibaba.smartfox.eclipse.pmd.rule, com.alibaba.smartfox.eclipse.ui, diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml index a8a6818..7cb9b05 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/pom.xml @@ -5,7 +5,7 @@ com.alibaba.smartfox.eclipse smartfox-eclipse - 1.0.6-SNAPSHOT + 2.0.0-SNAPSHOT com.alibaba.smartfox.eclipse.plugin eclipse-plugin @@ -22,11 +22,11 @@ com.alibaba.p3c p3c-pmd - 1.3.5 + 2.0.0 org.jetbrains.kotlin - kotlin-stdlib + kotlin-stdlib-jdk8 com.google.guava @@ -63,7 +63,7 @@ org.apache.maven.plugins maven-dependency-plugin - 2.7 + 3.1.1 true false diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt index 989357a..166c8e3 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/job/CodeAnalysis.kt @@ -104,7 +104,7 @@ object CodeAnalysis { private fun processFile(file: IFile): List { val configuration = PMDConfiguration() - configuration.sourceEncoding = file.charset ?: Charsets.UTF_8.name() + configuration.setSourceEncoding(file.charset ?: Charsets.UTF_8.name()) configuration.inputPaths = file.fullPath.toPortableString() val ctx = RuleContext() ctx.setAttribute("eclipseFile", file) @@ -120,7 +120,7 @@ object CodeAnalysis { } } catch (pmde: PMDException) { log.debug("Error while processing file: " + niceFileName, pmde.cause) - report.addError(Report.ProcessingError(pmde.message, niceFileName)) + report.addError(Report.ProcessingError(pmde, niceFileName)) } catch (ioe: IOException) { log.error("Unable to read source file: " + niceFileName, ioe) } catch (re: RuntimeException) { diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt index 0b98fa5..cdae030 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/pmd/rule/AbstractEclipseRule.kt @@ -78,9 +78,9 @@ abstract class AbstractEclipseRule : AbstractJavaRule() { return data } - override fun setDescription(description: String) { + override fun setDescription(description: String?) { try { - super.setDescription(P3cBundle.getMessage(description)) + super.setDescription(P3cBundle.getMessage(description ?: "")) } catch (e: MissingResourceException) { super.setMessage(description) } diff --git a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml index 8bd132d..47f2c85 100644 --- a/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml +++ b/eclipse-plugin/com.alibaba.smartfox.eclipse.updatesite/pom.xml @@ -5,7 +5,7 @@ com.alibaba.smartfox.eclipse smartfox-eclipse - 1.0.6-SNAPSHOT + 2.0.0-SNAPSHOT com.alibaba.smartfox.eclipse.updatesite eclipse-repository diff --git a/eclipse-plugin/pom.xml b/eclipse-plugin/pom.xml index 9b157b3..55781b0 100644 --- a/eclipse-plugin/pom.xml +++ b/eclipse-plugin/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.alibaba.smartfox.eclipse smartfox-eclipse - 1.0.6-SNAPSHOT + 2.0.0-SNAPSHOT pom 2017 @@ -14,7 +14,7 @@ http://download.eclipse.org/releases/neon UTF-8 http://download.eclipse.org/tools/ajdt/46/dev/update - 1.2.21 + 1.3.30 juno @@ -34,7 +34,7 @@ org.jetbrains.kotlin - kotlin-stdlib + kotlin-stdlib-jdk8 ${kotlin.version} compile @@ -113,7 +113,7 @@ tycho-compiler-plugin ${tycho.version} - 1.7 + 1.8 diff --git a/idea-plugin/build.gradle b/idea-plugin/build.gradle index abe8684..64aa3db 100644 --- a/idea-plugin/build.gradle +++ b/idea-plugin/build.gradle @@ -20,7 +20,7 @@ allprojects { apply plugin: 'kotlin' apply plugin: 'maven-publish' - sourceCompatibility = 1.7 + sourceCompatibility = 1.8 compileJava.options.encoding = 'UTF-8' configurations.all { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' @@ -31,7 +31,7 @@ allprojects { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" + compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" testCompile group: 'junit', name: 'junit', version: '4.11' } } diff --git a/idea-plugin/gradle.properties b/idea-plugin/gradle.properties index b946289..5238fd2 100644 --- a/idea-plugin/gradle.properties +++ b/idea-plugin/gradle.properties @@ -1,9 +1,8 @@ -kotlin_version=1.2.21 +kotlin_version=1.3.30 #idea_version=171.3780.15 -idea_version=14.1.7 +idea_version=145.258.11 plugin_name=Alibaba Java Coding Guidelines -pmd_version=5.5.2 -gradle_jetbrains_version=0.2.13 +gradle_jetbrains_version=0.4.5 systemProp.file.encoding=UTF-8 -plugin_version=1.0.6 +plugin_version=2.0.0 diff --git a/idea-plugin/gradle/wrapper/gradle-wrapper.properties b/idea-plugin/gradle/wrapper/gradle-wrapper.properties index 143e48e..29bf84a 100644 --- a/idea-plugin/gradle/wrapper/gradle-wrapper.properties +++ b/idea-plugin/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-bin.zip diff --git a/idea-plugin/p3c-common/build.gradle b/idea-plugin/p3c-common/build.gradle index dcd28c9..e86c26a 100644 --- a/idea-plugin/p3c-common/build.gradle +++ b/idea-plugin/p3c-common/build.gradle @@ -1,5 +1,5 @@ plugins { - id "org.jetbrains.intellij" version '0.2.17' + id "org.jetbrains.intellij" version '0.4.5' } apply plugin: 'kotlin' apply plugin: 'idea' @@ -32,13 +32,13 @@ intellij { updateSinceUntilBuild false sandboxDirectory "$project.buildDir/idea-sandbox/$idea_version" } -version '1.0.6' +version '2.0.0' ext.isReleaseVersion = !version.endsWith("SNAPSHOT") dependencies { compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating' - compile 'com.alibaba.p3c:p3c-pmd:1.3.6' + compile 'com.alibaba.p3c:p3c-pmd:2.0.0' compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA' } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt index a3ddff9..e5c7199 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/AliInspectionAction.kt @@ -21,7 +21,7 @@ import com.alibaba.p3c.idea.ep.InspectionActionExtensionPoint import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliBaseInspection import com.alibaba.p3c.idea.util.NumberConstants -import com.beust.jcommander.internal.Lists +import com.google.common.collect.Lists import com.intellij.analysis.AnalysisScope import com.intellij.analysis.AnalysisUIOptions import com.intellij.analysis.BaseAnalysisActionDialog diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt index 1be5d36..a7ffd0b 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/action/ToggleProjectInspectionAction.kt @@ -45,8 +45,8 @@ class ToggleProjectInspectionAction : AnAction() { smartFoxConfig.projectInspectionClosed = !smartFoxConfig.projectInspectionClosed } - override fun update(e: AnActionEvent?) { - val project = e!!.project ?: return + override fun update(e: AnActionEvent) { + val project = e.project ?: return val smartFoxConfig = ServiceManager.getService(project, SmartFoxProjectConfig::class.java) e.presentation.text = if (smartFoxConfig.projectInspectionClosed) { e.presentation.icon = P3cIcons.PROJECT_INSPECTION_ON diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/P3cConfig.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/P3cConfig.kt index 9ec3a86..3bbe6f7 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/P3cConfig.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/P3cConfig.kt @@ -18,7 +18,6 @@ package com.alibaba.p3c.idea.config import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage -import com.intellij.openapi.components.StoragePathMacros import com.intellij.util.xmlb.XmlSerializerUtil import java.util.Locale @@ -28,7 +27,7 @@ import java.util.Locale * @author caikang * @date 2017/06/19 */ -@State(name = "P3cConfig", storages = arrayOf(Storage(file = "${StoragePathMacros.APP_CONFIG}/smartfox/p3c.xml"))) +@State(name = "P3cConfig", storages = [Storage(file = "smartfox/p3c.xml")]) class P3cConfig : PersistentStateComponent { var astCacheTime = 1000L var astCacheEnable = true @@ -58,16 +57,12 @@ class P3cConfig : PersistentStateComponent { return this } - override fun loadState(state: P3cConfig?) { - if (state == null) { - return - } + override fun loadState(state: P3cConfig) { XmlSerializerUtil.copyBean(state, this) } - companion object { val localeEn = Locale.ENGLISH.language!! val localeZh = Locale.CHINESE.language!! } -} \ No newline at end of file +} diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/SmartFoxProjectConfig.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/SmartFoxProjectConfig.kt index 2a0d2a0..20b9e62 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/SmartFoxProjectConfig.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/config/SmartFoxProjectConfig.kt @@ -15,10 +15,8 @@ */ package com.alibaba.p3c.idea.config -import com.google.common.collect.Sets import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State -import com.intellij.openapi.components.StoragePathMacros import com.intellij.util.xmlb.XmlSerializerUtil /** @@ -27,22 +25,15 @@ import com.intellij.util.xmlb.XmlSerializerUtil * @author caikang * @date 2017/03/01 */ -@State(name = "SmartFoxProjectConfig", - storages = arrayOf(com.intellij.openapi.components.Storage( - file = "${StoragePathMacros.PROJECT_CONFIG_DIR}/smartfox_info.xml"))) +@State(name = "SmartFoxProjectConfig", storages = [com.intellij.openapi.components.Storage(file = "smartfox_info.xml")]) class SmartFoxProjectConfig : PersistentStateComponent { - var inspectionProfileModifiedSet = Sets.newHashSet()!! - var projectInspectionClosed = false override fun getState(): SmartFoxProjectConfig? { return this } - override fun loadState(state: SmartFoxProjectConfig?) { - if (state == null) { - return - } + override fun loadState(state: SmartFoxProjectConfig) { XmlSerializerUtil.copyBean(state, this) } } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt index de0e755..63f3f0e 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt @@ -46,7 +46,7 @@ class AliPmdInspectionInvoker( private val manager: InspectionManager, private val rule: Rule ) { - val logger = Logger.getInstance(javaClass) + private val logger = Logger.getInstance(javaClass) private var violations: List = emptyList() @@ -140,4 +140,4 @@ class AliPmdInspectionInvoker( } data class FileRule(val filePath: String, val ruleName: String) -data class Offsets(val start: Int, val end: Int) \ No newline at end of file +data class Offsets(val start: Int, val end: Int) diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt index 1f19647..78532cc 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliDeprecationInspection.kt @@ -88,13 +88,13 @@ class AliDeprecationInspection : DeprecationInspection, AliBaseInspection { holder.manager, holder.file, onTheFly) { override fun registerProblem(psiElement: PsiElement, - @Nls(capitalization = Nls.Capitalization.Sentence) descriptionTemplate: String, + @Nls descriptionTemplate: String, fixes: Array?) { holder.registerProblem(psiElement, getMessage(descriptionTemplate), *(fixes ?: emptyArray())) } override fun registerProblem(psiElement: PsiElement, - @Nls(capitalization = Nls.Capitalization.Sentence) descriptionTemplate: String, + @Nls descriptionTemplate: String, highlightType: ProblemHighlightType, fixes: Array?) { holder.registerProblem(psiElement, getMessage(descriptionTemplate), highlightType, *(fixes ?: emptyArray())) } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt index 3bec9de..9b4d007 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliMissingOverrideAnnotationInspection.kt @@ -67,7 +67,7 @@ class AliMissingOverrideAnnotationInspection : MissingOverrideAnnotationInspecti override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val fix = super.buildFix(*infos) ?: return null return DecorateInspectionGadgetsFix(fix, - P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.standalone.AliMissingOverrideAnnotationInspection")) + P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.standalone.AliMissingOverrideAnnotationInspection")) } override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = buildFix(psiElement) diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt index bcf5ecd..6eea271 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/MapOrSetKeyShouldOverrideHashCodeEqualsInspection.kt @@ -15,12 +15,12 @@ */ package com.alibaba.p3c.idea.inspection.standalone -import com.alibaba.p3c.idea.util.NumberConstants -import com.alibaba.p3c.idea.util.ObjectConstants import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliBaseInspection import com.alibaba.p3c.idea.util.HighlightDisplayLevels -import com.beust.jcommander.internal.Sets +import com.alibaba.p3c.idea.util.NumberConstants +import com.alibaba.p3c.idea.util.ObjectConstants +import com.google.common.collect.Sets import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.ide.highlighter.JavaFileType import com.intellij.psi.CommonClassNames diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt index 8d4b751..ad742d2 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/AliPmdProcessor.kt @@ -25,11 +25,11 @@ import net.sourceforge.pmd.PMDException 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.util.ResourceLoader import java.io.IOException import java.io.StringReader @@ -42,38 +42,39 @@ class AliPmdProcessor(val rule: Rule) { private val configuration = PMDConfiguration() init { - ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration) + ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration, ResourceLoader()) } fun processFile(psiFile: PsiFile): List { - configuration.sourceEncoding = psiFile.virtualFile.charset.name() + configuration.setSourceEncoding(psiFile.virtualFile.charset.name()) configuration.inputPaths = psiFile.virtualFile.canonicalPath val document = FileDocumentManager.getInstance().getDocument(psiFile.virtualFile) ?: return emptyList() + if (document.lineCount > 10000) { + return emptyList() + } val ctx = RuleContext() val processor = SourceCodeProcessor(configuration) val niceFileName = psiFile.virtualFile.canonicalPath!! val report = Report.createReport(ctx, niceFileName) val ruleSets = RuleSets() - val ruleSet = RuleSet() - ruleSet.addRule(rule) + + val ruleSet = ruleSetFactory.createSingleRuleRuleSet(rule) ruleSets.addRuleSet(ruleSet) LOG.debug("Processing " + ctx.sourceCodeFilename) - ruleSets.start(ctx) try { ctx.languageVersion = null processor.processSourceCode(StringReader(document.text), ruleSets, ctx) } catch (pmde: PMDException) { - LOG.debug("Error while processing file: " + niceFileName, pmde.cause) - report.addError(Report.ProcessingError(pmde.message, niceFileName)) + LOG.debug("Error while processing file: $niceFileName", pmde.cause) + report.addError(Report.ProcessingError(pmde, niceFileName)) } catch (ioe: IOException) { - LOG.error("Unable to read source file: " + niceFileName, ioe) + LOG.error("Unable to read source file: $niceFileName", ioe) } catch (re: RuntimeException) { val root = Throwables.getRootCause(re) if (root !is ApplicationUtil.CannotRunReadActionException) { - LOG.error("RuntimeException while processing file: " + niceFileName, re) + LOG.error("RuntimeException while processing file: $niceFileName", re) } } - ruleSets.end(ctx) return ctx.report.toList() } diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt index 15e24b7..de4ce09 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt @@ -7,41 +7,72 @@ import com.alibaba.p3c.idea.config.P3cConfig import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import com.intellij.openapi.components.ServiceManager -import com.intellij.openapi.diagnostic.Logger import net.sourceforge.pmd.PMD import net.sourceforge.pmd.PMDConfiguration import net.sourceforge.pmd.PMDException import net.sourceforge.pmd.RuleContext import net.sourceforge.pmd.RuleSets -import net.sourceforge.pmd.benchmark.Benchmark -import net.sourceforge.pmd.benchmark.Benchmarker +import net.sourceforge.pmd.benchmark.TimeTracker +import net.sourceforge.pmd.benchmark.TimedOperationCategory +import net.sourceforge.pmd.lang.Language import net.sourceforge.pmd.lang.LanguageVersion import net.sourceforge.pmd.lang.LanguageVersionHandler import net.sourceforge.pmd.lang.Parser import net.sourceforge.pmd.lang.ast.Node import net.sourceforge.pmd.lang.ast.ParseException import net.sourceforge.pmd.lang.xpath.Initializer -import org.apache.commons.io.IOUtils +import java.io.IOException +import java.io.InputStream +import java.io.InputStreamReader import java.io.Reader import java.util.concurrent.TimeUnit class SourceCodeProcessor(private val configuration: PMDConfiguration) { - val logger = Logger.getInstance(javaClass) /** - * Processes the input stream against a rule set using the given input encoding. - * If the LanguageVersion is `null` on the RuleContext, it will - * be automatically determined. Any code which wishes to process files for - * different Languages, will need to be sure to either properly set the - * Language on the RuleContext, or set it to `null` first. + * Processes the input stream against a rule set using the given input + * encoding. + * + * @param sourceCode + * The InputStream to analyze. + * @param ruleSets + * The collection of rules to process against the file. + * @param ctx + * The context in which PMD is operating. + * @throws PMDException + * if the input encoding is unsupported, the input stream could + * not be parsed, or other error is encountered. + * @see .processSourceCode + */ + @Throws(PMDException::class) + fun processSourceCode(sourceCode: InputStream, ruleSets: RuleSets, ctx: RuleContext) { + try { + InputStreamReader(sourceCode, configuration.sourceEncoding).use { streamReader -> processSourceCode(streamReader, ruleSets, ctx) } + } catch (e: IOException) { + throw PMDException("IO exception: " + e.message, e) + } + } + + /** + * Processes the input stream against a rule set using the given input + * encoding. If the LanguageVersion is `null` on the RuleContext, + * it will be automatically determined. Any code which wishes to process + * files for different Languages, will need to be sure to either properly + * set the Language on the RuleContext, or set it to `null` + * first. + * * @see RuleContext.setLanguageVersion * @see PMDConfiguration.getLanguageVersionOfFile - * @param sourceCode The Reader to analyze. - * @param ruleSets The collection of rules to process against the file. - * @param ctx The context in which PMD is operating. - * @throws PMDException if the input encoding is unsupported, the input stream could - * not be parsed, or other error is encountered. + * @param sourceCode + * The Reader to analyze. + * @param ruleSets + * The collection of rules to process against the file. + * @param ctx + * The context in which PMD is operating. + * @throws PMDException + * if the input encoding is unsupported, the input stream could + * not be parsed, or other error is encountered. */ @Throws(PMDException::class) fun processSourceCode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) { @@ -49,63 +80,29 @@ class SourceCodeProcessor(private val configuration: PMDConfiguration) { // make sure custom XPath functions are initialized Initializer.initialize() - // Coarse check to see if any RuleSet applies to file, will need to do a finer RuleSet specific check later - try { - processSource(sourceCode, ruleSets, ctx) + try { + ruleSets.start(ctx) + processSource(sourceCode, ruleSets, ctx) } catch (pe: ParseException) { + configuration.analysisCache.analysisFailed(ctx.sourceCodeFile) throw PMDException("Error while parsing " + ctx.sourceCodeFilename, pe) } catch (e: Exception) { + configuration.analysisCache.analysisFailed(ctx.sourceCodeFile) throw PMDException("Error while processing " + ctx.sourceCodeFilename, e) - } catch (error: Error) { - throw PMDException("Error while processing ${ctx.sourceCodeFilename} ${error.message}") } finally { - IOUtils.closeQuietly(sourceCode) + ruleSets.end(ctx) } } - private fun parse(ctx: RuleContext, sourceCode: Reader, parser: Parser): Node { - val start = System.nanoTime() - val rootNode = parser.parse(ctx.sourceCodeFilename, sourceCode) - ctx.report.suppress(parser.suppressMap) - val end = System.nanoTime() - Benchmarker.mark(Benchmark.Parser, end - start, 0) - return rootNode - } - - private fun symbolFacade(rootNode: Node, languageVersionHandler: LanguageVersionHandler) { - val start = System.nanoTime() - languageVersionHandler.getSymbolFacade(configuration.classLoader).start(rootNode) - val end = System.nanoTime() - Benchmarker.mark(Benchmark.SymbolTable, end - start, 0) - } - - private fun usesDFA(languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets) { - val start = System.nanoTime() - val dataFlowFacade = languageVersion.languageVersionHandler.dataFlowFacade - dataFlowFacade.start(rootNode) - val end = System.nanoTime() - Benchmarker.mark(Benchmark.DFA, end - start, 0) - } - - private fun usesTypeResolution(languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets) { - if (ruleSets.usesTypeResolution(languageVersion.language)) { - val start = System.nanoTime() - languageVersion.languageVersionHandler.getTypeResolutionFacade(configuration.classLoader).start(rootNode) - val end = System.nanoTime() - Benchmarker.mark(Benchmark.TypeResolution, end - start, 0) + TimeTracker.startOperation(TimedOperationCategory.PARSER).use { + val rootNode = parser.parse(ctx.sourceCodeFilename, sourceCode) + ctx.report.suppress(parser.suppressMap) + return rootNode } } - private fun processSource(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) { - val start = System.currentTimeMillis() - val acus = listOf(getRootNode(sourceCode, ruleSets, ctx)) - logger.debug("elapsed ${System.currentTimeMillis() - start}ms to" + - " parse ast tree for file ${ctx.sourceCodeFilename}") - ruleSets.apply(acus, ctx, ctx.languageVersion.language) - } - private fun getRootNode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext): Node { if (!smartFoxConfig.astCacheEnable) { return parseNode(ctx, ruleSets, sourceCode) @@ -123,14 +120,79 @@ class SourceCodeProcessor(private val configuration: PMDConfiguration) { val parser = PMD.parserFor(languageVersion, configuration) val rootNode = parse(ctx, sourceCode, parser) symbolFacade(rootNode, languageVersionHandler) - usesDFA(languageVersion, rootNode, ruleSets) - usesTypeResolution(languageVersion, rootNode, ruleSets) + val language = languageVersion.language + usesDFA(languageVersion, rootNode, ruleSets, language) + usesTypeResolution(languageVersion, rootNode, ruleSets, language) nodeCache.put(ctx.sourceCodeFilename, rootNode) return rootNode } + private fun symbolFacade(rootNode: Node, languageVersionHandler: LanguageVersionHandler) { + TimeTracker.startOperation(TimedOperationCategory.SYMBOL_TABLE).use { to -> languageVersionHandler.getSymbolFacade(configuration.classLoader).start(rootNode) } + } + + private fun resolveQualifiedNames(rootNode: Node, handler: LanguageVersionHandler) { + TimeTracker.startOperation(TimedOperationCategory.QUALIFIED_NAME_RESOLUTION).use { to -> handler.getQualifiedNameResolutionFacade(configuration.classLoader).start(rootNode) } + } + + // private ParserOptions getParserOptions(final LanguageVersionHandler + // languageVersionHandler) { + // // TODO Handle Rules having different parser options. + // ParserOptions parserOptions = + // languageVersionHandler.getDefaultParserOptions(); + // parserOptions.setSuppressMarker(configuration.getSuppressMarker()); + // return parserOptions; + // } + + private fun usesDFA(languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets, language: Language) { + if (ruleSets.usesDFA(language)) { + TimeTracker.startOperation(TimedOperationCategory.DFA).use { to -> + val dataFlowFacade = languageVersion.languageVersionHandler.dataFlowFacade + dataFlowFacade.start(rootNode) + } + } + } + + private fun usesTypeResolution(languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets, + language: Language) { + + if (ruleSets.usesTypeResolution(language)) { + TimeTracker.startOperation(TimedOperationCategory.TYPE_RESOLUTION).use { to -> + languageVersion.languageVersionHandler.getTypeResolutionFacade(configuration.classLoader) + .start(rootNode) + } + } + } + + + private fun usesMultifile(rootNode: Node, languageVersionHandler: LanguageVersionHandler, ruleSets: RuleSets, + language: Language) { + + if (ruleSets.usesMultifile(language)) { + TimeTracker.startOperation(TimedOperationCategory.MULTIFILE_ANALYSIS).use { to -> languageVersionHandler.multifileFacade.start(rootNode) } + } + } + + + private fun processSource(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) { + val languageVersion = ctx.languageVersion + val languageVersionHandler = languageVersion.languageVersionHandler + + val rootNode = getRootNode(sourceCode, ruleSets, ctx) + resolveQualifiedNames(rootNode, languageVersionHandler) + symbolFacade(rootNode, languageVersionHandler) + val language = languageVersion.language + usesDFA(languageVersion, rootNode, ruleSets, language) + usesTypeResolution(languageVersion, rootNode, ruleSets, language) + usesMultifile(rootNode, languageVersionHandler, ruleSets, language) + + val acus = listOf(rootNode) + ruleSets.apply(acus, ctx, language) + } + private fun determineLanguage(ctx: RuleContext) { - // If LanguageVersion of the source file is not known, make a determination + // If LanguageVersion of the source file is not known, make a + // determination if (ctx.languageVersion == null) { val languageVersion = configuration.getLanguageVersionOfFile(ctx.sourceCodeFilename) ctx.languageVersion = languageVersion @@ -147,9 +209,9 @@ class SourceCodeProcessor(private val configuration: PMDConfiguration) { fun reInitNodeCache(expireTime: Long) { nodeCache = CacheBuilder.newBuilder().concurrencyLevel(16) - .expireAfterWrite(expireTime, TimeUnit.MILLISECONDS) - .maximumSize(100) - .build()!! + .expireAfterWrite(expireTime, TimeUnit.MILLISECONDS) + .maximumSize(100) + .build()!! } fun invalidateCache(file: String) { diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/AliPmdProcessor.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/AliPmdProcessor.kt deleted file mode 100644 index c457155..0000000 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/index/AliPmdProcessor.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 1999-2017 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.p3c.idea.pmd.index - -import com.beust.jcommander.internal.Lists -import com.intellij.util.indexing.FileContent -import net.sourceforge.pmd.PMD -import net.sourceforge.pmd.PMDConfiguration -import net.sourceforge.pmd.RuleContext -import net.sourceforge.pmd.RuleSetFactory -import net.sourceforge.pmd.RuleViolation -import net.sourceforge.pmd.RulesetsFactoryUtils -import net.sourceforge.pmd.renderers.Renderer -import net.sourceforge.pmd.util.datasource.DataSource - -/** - * @author caikang - * @date 2016/12/11 - */ -class AliPmdProcessor { - private val ruleSetFactory: RuleSetFactory - private val configuration = PMDConfiguration() - - init { - configuration.ruleSets = "java-ali-pmd,vm-ali-other" - configuration.threads = 0 - ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration) - } - - fun processFile(fileContent: FileContent): List { - val renderer = InspectionRenderer() - val dataSources = Lists.newArrayList() - dataSources.add(InspectionDataSource(fileContent)) - PMD.processFiles(configuration, ruleSetFactory, dataSources, RuleContext(), - listOf(renderer)) - return renderer.getViolations() - } -} diff --git a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt index adb9315..579025d 100644 --- a/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt +++ b/idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/quickfix/LowerCamelCaseVariableNamingQuickFix.kt @@ -16,7 +16,6 @@ package com.alibaba.p3c.idea.quickfix import com.alibaba.p3c.idea.i18n.P3cBundle -import com.google.common.base.Joiner import com.google.common.base.Splitter import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project @@ -46,16 +45,13 @@ object LowerCamelCaseVariableNamingQuickFix : AliQuickFix { } private fun toLowerCamelCase(identifier: String): String { - val list = Splitter.onPattern("[^a-z0-9A-Z]+").trimResults().omitEmptyStrings().splitToList(identifier) + val list = Splitter.onPattern("[^a-z0-9A-Z]+").trimResults() + .omitEmptyStrings().split(identifier).toList() val result = list.mapIndexed { i, s -> - if (i == 0) { - s.toLowerCase() - } else { - val charArray = s.toLowerCase().toCharArray() - charArray[0] = charArray[0].toUpperCase() - String(charArray) - } + val charArray = s.toCharArray() + charArray[0] = if (i == 0) charArray[0].toLowerCase() else charArray[0].toUpperCase() + String(charArray) } - return Joiner.on("").join(result) + return result.joinToString("") } } diff --git a/idea-plugin/p3c-idea/build.gradle b/idea-plugin/p3c-idea/build.gradle index 876b5af..34adcfa 100644 --- a/idea-plugin/p3c-idea/build.gradle +++ b/idea-plugin/p3c-idea/build.gradle @@ -1,5 +1,5 @@ plugins { - id "org.jetbrains.intellij" version '0.2.17' + id "org.jetbrains.intellij" version '0.4.5' } apply plugin: 'kotlin' apply plugin: 'idea' @@ -16,7 +16,6 @@ version plugin_version dependencies { compile group: 'org.freemarker', name: 'freemarker', version: '2.3.25-incubating' - //compile 'com.alibaba.p3c.idea:p3c-common:1.0.0' compile project(':p3c-common') compile group: 'org.javassist', name: 'javassist', version: '3.21.0-GA' } diff --git a/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml b/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml index 42537d5..f562e20 100755 --- a/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml +++ b/idea-plugin/p3c-idea/src/main/resources/META-INF/plugin.xml @@ -5,6 +5,17 @@ + 2.0.0 +
  • supported min idea version 2016.1(145.258.11)
  • +
  • supported min jdk version 1.8
  • +
  • fix persistent compatibility issue
  • +
  • fix https://github.com/alibaba/p3c/issues/430
  • +
  • fix https://github.com/alibaba/p3c/issues/454
  • +
  • fix https://github.com/alibaba/p3c/issues/409
  • +
  • add rule To judge the equivalence of floating-point numbers.
  • +
  • add annotation process for rule ClassMustHaveAuthorRule
  • +
      1.0.6
    • fix https://github.com/alibaba/p3c/issues/337 do not check annotation
    • PojoMustOverrideToStringRule do not check interface
    • @@ -51,7 +62,7 @@ ]]> alibaba - 1.0.0 + 2.0.0 com.intellij.velocity com.intellij.modules.java diff --git a/p3c-pmd/pom.xml b/p3c-pmd/pom.xml index 2673d2e..18c8bbe 100644 --- a/p3c-pmd/pom.xml +++ b/p3c-pmd/pom.xml @@ -1,22 +1,23 @@ + 4.0.0 org.sonatype.oss oss-parent 9 - 4.0.0 com.alibaba.p3c - p3c-pmd - 1.3.6 - jar - p3c-pmd + p3c-pmd + 2.0.0 + jar + p3c-pmd - UTF-8 - 5.5.2 + UTF-8 + 6.15.0 + 1.8 + 1.3.2 - Alibaba Java Coding Guidelines PMD implementations https://github.com/alibaba/p3c 2017 @@ -70,37 +71,104 @@ https://github.com/SeanCai sean.caikang@gmail.com + + MoYan + https://github.com/imu2008 + panhuawenmail@gmail.com + - - - - net.sourceforge.pmd - pmd-java - ${pmd.version} - - - net.sourceforge.pmd - pmd-vm - ${pmd.version} - - - net.sourceforge.pmd - pmd-test - ${pmd.version} - test + + + net.sourceforge.pmd + pmd-java + ${pmd.version} - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 1.7 - 1.7 - UTF-8 - + + net.sourceforge.pmd + pmd-vm + ${pmd.version} + + + net.sourceforge.pmd + pmd-test + ${pmd.version} + test + + + javax.annotation + javax.annotation-api + ${annotation.version} + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 3.11.0 + + ${project.build.sourceEncoding} + ${maven.compiler.target} + true + + rulesets/java/ali-comment.xml + rulesets/java/ali-concurrent.xml + rulesets/java/ali-constant.xml + rulesets/java/ali-exception.xml + rulesets/java/ali-flowcontrol.xml + rulesets/java/ali-naming.xml + rulesets/java/ali-oop.xml + rulesets/java/ali-orm.xml + rulesets/java/ali-other.xml + rulesets/java/ali-set.xml + + + **/FixClassTypeResolver.java + + + + + verify + + check + + + + + + com.alibaba.p3c + p3c-pmd + 2.0.0 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + ${maven.compiler.target} + ${maven.compiler.target} + UTF-8 + + + + maven-assembly-plugin + 3.0.0 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + org.apache.maven.plugins @@ -122,20 +190,20 @@ - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - - - + + + diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java index 27da9d3..c6c4973 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/I18nResources.java @@ -58,7 +58,15 @@ public class I18nResources { } public static String getMessage(String key) { - return resourceBundle.getString(key).trim(); + if (key == null) { + // 暂时返回空字符串 + return ""; + } + try { + return resourceBundle.getString(key).trim(); + } catch (MissingResourceException e) { + return key; + } } public static String getMessage(String key, Object... params) { @@ -70,6 +78,10 @@ public class I18nResources { } public static String getMessageWithExceptionHandled(String key) { + if (key == null) { + // 暂时返回空字符串 + return ""; + } try { return resourceBundle.getString(key).trim(); } catch (MissingResourceException e) { diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java index 54b5855..d56ea5b 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/AbstractAliCommentRule.java @@ -18,7 +18,7 @@ package com.alibaba.p3c.pmd.lang.java.rule.comment; import com.alibaba.p3c.pmd.I18nResources; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.java.rule.comments.AbstractCommentRule; +import net.sourceforge.pmd.lang.java.rule.documentation.AbstractCommentRule; /** * @author caikang diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java index 78615ee..78372b7 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/ClassMustHaveAuthorRule.java @@ -15,11 +15,16 @@ */ package com.alibaba.p3c.pmd.lang.java.rule.comment; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; import java.util.regex.Pattern; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; @@ -39,21 +44,21 @@ public class ClassMustHaveAuthorRule extends AbstractAliCommentRule { private static final String MESSAGE_KEY_PREFIX = "java.comment.ClassMustHaveAuthorRule.violation.msg"; + /** + * Immediately return after visiting class/interface/enum/annotation, + * so that we don't need to deal with inner class/interface/enum/annotation declarations. + * + * @param decl + * @param data + * @return + */ @Override public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) { - // Exclude nested classes - if (decl.isNested()) { - return super.visit(decl, data); + // If a CompilationUnit has multi class definition, only the public one will be checked. + if (decl.isPublic()) { + checkAuthorComment(decl, data); } - - // Exclude inner classes - if (!decl.isPublic()) { - return super.visit(decl, data); - } - - checkAuthorComment(decl, data); - - return super.visit(decl, data); + return data; } @Override @@ -70,8 +75,13 @@ public class ClassMustHaveAuthorRule extends AbstractAliCommentRule { } checkAuthorComment(decl, data); + return data; + } - return super.visit(decl, data); + @Override + public Object visit(ASTAnnotationTypeDeclaration decl, Object data) { + checkAuthorComment(decl, data); + return data; } @Override @@ -81,6 +91,32 @@ public class ClassMustHaveAuthorRule extends AbstractAliCommentRule { return super.visit(cUnit, data); } + @Override + protected SortedMap orderedCommentsAndDeclarations(ASTCompilationUnit cUnit) { + SortedMap itemsByLineNumber = new TreeMap<>(); + + List packageDecl = cUnit + .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class); + addDeclarations(itemsByLineNumber, packageDecl); + + List enumDecl = cUnit.findDescendantsOfType(ASTEnumDeclaration.class); + addDeclarations(itemsByLineNumber, enumDecl); + + List annotationDecl = cUnit + .findDescendantsOfType(ASTAnnotationTypeDeclaration.class); + addDeclarations(itemsByLineNumber, annotationDecl); + + addDeclarations(itemsByLineNumber, cUnit.getComments()); + + return itemsByLineNumber; + } + + private void addDeclarations(SortedMap map, List nodes) { + for (Node node : nodes) { + map.put((node.getBeginLine() << 16) + node.getBeginColumn(), node); + } + } + /** * Check if node's comment contains author tag. * diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java index b8908f1..7cf5844 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/comment/CommentsMustBeJavadocFormatRule.java @@ -25,6 +25,7 @@ import java.util.TreeMap; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.util.NodeSortUtils; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration; @@ -56,76 +57,53 @@ public class CommentsMustBeJavadocFormatRule extends AbstractAliCommentRule { @Override public Object visit(final ASTClassOrInterfaceDeclaration decl, Object data) { - checkComment(decl, data, new MessageMaker() { - @Override - public String make() { - return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".class", - decl.getImage()); - } - }); + checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".class", + decl.getImage())); return super.visit(decl, data); } @Override public Object visit(final ASTConstructorDeclaration decl, Object data) { - checkComment(decl, data, new MessageMaker() { - @Override - public String make() { - String constructorName = ((Token)decl.jjtGetFirstToken()).image; - if (decl.getParameters().getParameterCount() == 0) { - return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".constructor.default", - constructorName); - } - List formalParameters = decl.getParameters() - .findChildrenOfType(ASTFormalParameter.class); - List strings = new ArrayList<>(formalParameters.size()); - - for (ASTFormalParameter formalParameter : formalParameters) { - strings.add(formalParameter.jjtGetFirstToken().toString() + " " - + formalParameter.jjtGetLastToken().toString()); - } - return I18nResources - .getMessage(MESSAGE_KEY_PREFIX + ".constructor.parameter", - constructorName, - StringUtils.join(strings, ",")); + checkComment(decl, data, () -> { + String constructorName = ((Token)decl.jjtGetFirstToken()).image; + if (decl.getFormalParameters().getParameterCount() == 0) { + return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".constructor.default", + constructorName); } + List formalParameters = decl.getFormalParameters() + .findChildrenOfType(ASTFormalParameter.class); + List strings = new ArrayList<>(formalParameters.size()); + + for (ASTFormalParameter formalParameter : formalParameters) { + strings.add(formalParameter.jjtGetFirstToken().toString() + " " + + formalParameter.jjtGetLastToken().toString()); + } + return I18nResources + .getMessage(MESSAGE_KEY_PREFIX + ".constructor.parameter", + constructorName, + StringUtils.join(strings, ",")); }); return super.visit(decl, data); } @Override public Object visit(final ASTMethodDeclaration decl, Object data) { - checkComment(decl, data, new MessageMaker() { - @Override - public String make() { - return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", - decl.getMethodName()); - } - }); + checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", + decl.getMethodName())); return super.visit(decl, data); } @Override public Object visit(final ASTFieldDeclaration decl, Object data) { - checkComment(decl, data, new MessageMaker() { - @Override - public String make() { - return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".field", - decl.getVariableName()); - } - }); + checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".field", + VariableUtils.getVariableName(decl))); return super.visit(decl, data); } @Override public Object visit(final ASTEnumDeclaration decl, Object data) { - checkComment(decl, data, new MessageMaker() { - @Override - public String make() { - return I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".enum", - decl.getImage()); - } - }); + checkComment(decl, data, () -> I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".enum", + decl.getImage())); return super.visit(decl, data); } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java index 0608474..e5e6602 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidConcurrentCompetitionRandomRule.java @@ -20,6 +20,8 @@ import java.util.Random; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; @@ -67,7 +69,7 @@ public class AvoidConcurrentCompetitionRandomRule extends AbstractAliRule { return super.visit(node, data); } for (ASTFieldDeclaration fieldDeclaration : fieldDeclarations) { - if (fieldDeclaration.getType() == Random.class + if (NodeUtils.getNodeType(fieldDeclaration) == Random.class && fieldDeclaration.isStatic()) { checkRandom(fieldDeclaration, methodDeclarations, data); } @@ -101,7 +103,7 @@ public class AvoidConcurrentCompetitionRandomRule extends AbstractAliRule { for (ASTMethodDeclaration methodDeclaration : methodDeclarations) { try { List nodes = methodDeclaration.findChildNodesWithXPath(String.format(XPATH_TPL, - fieldDeclaration.getVariableName())); + VariableUtils.getVariableName(fieldDeclaration))); if (nodes == null || nodes.isEmpty()) { continue; } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java index b056ab6..1ad3a8c 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/AvoidManuallyCreateThreadRule.java @@ -20,6 +20,7 @@ import java.util.concurrent.ThreadFactory; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils; import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; import net.sourceforge.pmd.lang.java.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; @@ -68,12 +69,12 @@ public class AvoidManuallyCreateThreadRule extends AbstractAliRule { } ASTFieldDeclaration fieldDeclaration = node.getFirstParentOfType(ASTFieldDeclaration.class); //field declaration with thread allocated - if (fieldDeclaration != null && fieldDeclaration.getType() == Thread.class) { + if (fieldDeclaration != null && NodeUtils.getNodeType(fieldDeclaration) == Thread.class) { return addViolationAndReturn(node, data); } //Declare thread factory field use lambda if (node.getDataFlowNode() == null && node.getFirstParentOfType(ASTLambdaExpression.class) != null) { - if (fieldDeclaration == null || fieldDeclaration.getType() != ThreadFactory.class) { + if (fieldDeclaration == null || NodeUtils.getNodeType(fieldDeclaration) != ThreadFactory.class) { return addViolationAndReturn(node, data); } return super.visit(node, data); diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java index e8a61b6..c2c48c4 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadLocalShouldRemoveRule.java @@ -19,6 +19,8 @@ import java.util.List; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; @@ -30,9 +32,9 @@ import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import org.jaxen.JaxenException; /** - * [Mandatory] Customized ThreadLocal variables must be recycled, - * especially when using thread pools in which threads are often reused. - * Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak. + * [Mandatory] Customized ThreadLocal variables must be recycled, especially when using thread pools in which threads + * are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory + * leak. * * @author caikang * @date 2017/03/29 @@ -52,7 +54,7 @@ public class ThreadLocalShouldRemoveRule extends AbstractAliRule { return super.visit(node, data); } for (ASTFieldDeclaration fieldDeclaration : fieldDeclarations) { - if (fieldDeclaration.getType() == ThreadLocal.class) { + if (NodeUtils.getNodeType(fieldDeclaration) == ThreadLocal.class) { if (checkThreadLocalWithInitalValue(fieldDeclaration)) { continue; } checkThreadLocal(fieldDeclaration, node, data); } @@ -66,9 +68,11 @@ public class ThreadLocalShouldRemoveRule extends AbstractAliRule { if (variableDeclarator == null) { return false; } - ASTMethodDeclarator initialValueMethod = variableDeclarator.getFirstDescendantOfType(ASTMethodDeclarator.class); - if (initialValueMethod != null && METHOD_INITIAL_VALUE.equals(initialValueMethod.getImage())) { - return true; + // ASTClassOrInterfaceBodyDeclaration.isFindBoundary=true,使用getFirstDescendantOfType不能继续向方法内部查询 + List astMethodDeclaratorList = variableDeclarator.findDescendantsOfType( + ASTMethodDeclarator.class, true); + if (!astMethodDeclaratorList.isEmpty()) { + return METHOD_INITIAL_VALUE.equals(astMethodDeclaratorList.get(0).getImage()); } ASTName name = variableDeclarator.getFirstDescendantOfType(ASTName.class); return name != null && WITH_INITIAL.equals(name.getImage()); @@ -76,12 +80,13 @@ public class ThreadLocalShouldRemoveRule extends AbstractAliRule { private void checkThreadLocal(ASTFieldDeclaration fieldDeclaration, ASTCompilationUnit node, Object data) { try { + String variableName = VariableUtils.getVariableName(fieldDeclaration); List nodes = node.findChildNodesWithXPath(String.format(XPATH_TPL, - fieldDeclaration.getVariableName())); + variableName)); if (nodes == null || nodes.isEmpty()) { ViolationUtils.addViolationWithPrecisePosition(this, fieldDeclaration, data, I18nResources.getMessage("java.concurrent.ThreadLocalShouldRemoveRule.violation.msg", - fieldDeclaration.getVariableName())); + variableName)); } } catch (JaxenException ignore) { } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java index 2a3f250..4e57209 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadPoolCreationRule.java @@ -44,12 +44,14 @@ public class ThreadPoolCreationRule extends AbstractAliRule { private static final String EXECUTORS_NEW = Executors.class.getSimpleName() + DOT + NEW; private static final String FULL_EXECUTORS_NEW = Executors.class.getName() + DOT + NEW; private static final String BRACKETS = "()"; + private static final String NEW_SCHEDULED = "newScheduledThreadPool"; + private static final String NEW_SINGLE_SCHEDULED = "newSingleThreadScheduledExecutor"; @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); @@ -75,6 +77,10 @@ public class ThreadPoolCreationRule extends AbstractAliRule { private boolean checkInitStatement(Token token, Info info) { String fullAssignStatement = getFullAssignStatement(token); + // do not check newScheduledThreadPool and newSingleThreadScheduledExecutor + if (NEW_SCHEDULED.equals(fullAssignStatement) || NEW_SINGLE_SCHEDULED.equals(fullAssignStatement)) { + return true; + } if (fullAssignStatement.startsWith(EXECUTORS_NEW)) { return false; } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java index 4ed626a..efbe4c5 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/concurrent/ThreadShouldSetNameRule.java @@ -29,6 +29,8 @@ import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; +import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; +import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; @@ -37,7 +39,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; * [Mandatory] A meaningful thread name is helpful to trace the error information, * so assign a name when creating threads or thread pools. * - * Detection rule //TODO should review + * Detection rule * 1. Use specific constructor while create thread pool * 2. Use Executors.defaultThreadFactory() is not allowed * @@ -78,6 +80,9 @@ public class ThreadShouldSetNameRule extends AbstractAliRule { private Object checkThreadPoolExecutor(ASTAllocationExpression node, Object data) { ASTArgumentList argumentList = node.getFirstDescendantOfType(ASTArgumentList.class); + if (argumentList.jjtGetNumChildren() > ARGUMENT_LENGTH_6) { + return true; + } if (argumentList.jjtGetNumChildren() < ARGUMENT_LENGTH_6 || !checkThreadFactoryArgument((ASTExpression)argumentList.jjtGetChild(ARGUMENT_LENGTH_6 - INDEX_1))) { addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".ThreadPoolExecutor"); @@ -87,6 +92,9 @@ public class ThreadShouldSetNameRule extends AbstractAliRule { private Object checkSchedulePoolExecutor(ASTAllocationExpression node, Object data) { ASTArgumentList argumentList = node.getFirstDescendantOfType(ASTArgumentList.class); + if (argumentList.jjtGetNumChildren() > ARGUMENT_LENGTH_2) { + return true; + } if (argumentList.jjtGetNumChildren() < ARGUMENT_LENGTH_2 || !checkThreadFactoryArgument((ASTExpression)argumentList.jjtGetChild(ARGUMENT_LENGTH_2 - INDEX_1))) { addViolationWithMessage(data, node, MESSAGE_KEY_PREFIX + ".ScheduledThreadPoolExecutor"); @@ -104,15 +112,35 @@ public class ThreadShouldSetNameRule extends AbstractAliRule { } ASTLambdaExpression lambdaExpression = expression.getFirstDescendantOfType(ASTLambdaExpression.class); if (lambdaExpression != null) { - List variableDeclaratorIds = - lambdaExpression.findChildrenOfType(ASTVariableDeclaratorId.class); - if (variableDeclaratorIds == null || variableDeclaratorIds.size() != SINGLE_LENGTH) { - return false; - } + return isThreadFactoryLambda(lambdaExpression); } else if (expression.getType() != null && RejectedExecutionHandler.class.isAssignableFrom(expression.getType())) { return false; } return true; } + + private boolean isThreadFactoryLambda(ASTLambdaExpression lambdaExpression) { + List variableDeclaratorIds = + lambdaExpression.findChildrenOfType(ASTVariableDeclaratorId.class); + if (variableDeclaratorIds != null && !variableDeclaratorIds.isEmpty()) { + return variableDeclaratorIds.size() == SINGLE_LENGTH; + } + + // like (Runnable r) -> + ASTFormalParameters parameters = lambdaExpression.getFirstChildOfType(ASTFormalParameters.class); + if (parameters == null) { + return false; + } + + ASTFormalParameter parameter = parameters.getFirstChildOfType(ASTFormalParameter.class); + if (parameter == null) { + return false; + } + ASTVariableDeclaratorId variableDeclaratorId = parameter.getFirstChildOfType(ASTVariableDeclaratorId.class); + if (variableDeclaratorId == null) { + return false; + } + return Runnable.class == variableDeclaratorId.getType(); + } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java index 781a23e..70a3875 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/constant/UndefineMagicConstantRule.java @@ -29,6 +29,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTLiteral; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.util.StringUtil; +import org.apache.commons.lang3.StringUtils; import org.jaxen.JaxenException; /** @@ -66,7 +67,7 @@ public class UndefineMagicConstantRule extends AbstractAliRule { for (ASTLiteral literal : literals) { if (inBlackList(literal) && !currentLiterals.contains(literal)) { currentLiterals.add(literal); - String imageReplace = StringUtil.replaceString(literal.getImage(), "{", "'{"); + String imageReplace = StringUtils.replace(literal.getImage(), "{", "'{"); addViolationWithMessage(data, literal, "java.constant.UndefineMagicConstantRule.violation.msg", new Object[] {imageReplace}); } @@ -101,10 +102,7 @@ public class UndefineMagicConstantRule extends AbstractAliRule { if (ifStatement != null && lineNum == ifStatement.getBeginLine()) { ASTForStatement forStatement = ifStatement.getFirstParentOfType(ASTForStatement.class); ASTWhileStatement whileStatement = ifStatement.getFirstParentOfType(ASTWhileStatement.class); - if (forStatement != null || whileStatement != null) { - return false; - } - return true; + return forStatement == null && whileStatement == null; } // judge magic value belongs to for statement diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java index 1de7c61..583a119 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/exception/TransactionMustHaveRollbackRule.java @@ -39,6 +39,8 @@ public class TransactionMustHaveRollbackRule extends AbstractAliRule { + TRANSACTIONAL_ANNOTATION_NAME; private static final String ROLLBACK_PREFIX = "rollback"; + private static final String READ_ONLY = "readOnly"; + private static final String PROPAGATION_NOT_SUPPORTED = "Propagation.NOT_SUPPORTED"; private static final String XPATH_FOR_ROLLBACK = "//StatementExpression/PrimaryExpression" @@ -84,10 +86,11 @@ public class TransactionMustHaveRollbackRule extends AbstractAliRule { private boolean shouldSkip(List memberValuePairList) { for (ASTMemberValuePair pair : memberValuePairList) { - if (pair.getImage() == null) { + String image = pair.getImage(); + if (image == null) { continue; } - if (pair.getImage().startsWith(ROLLBACK_PREFIX)) { + if (image.startsWith(ROLLBACK_PREFIX) || image.startsWith(READ_ONLY)) { return true; } ASTName name = pair.getFirstDescendantOfType(ASTName.class); diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java index a73a520..20ca6d3 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/NeedBraceRule.java @@ -24,8 +24,8 @@ import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; /** - * [Mandatory] Braces are used with if, else, for, do and while statements, even if the body contains only - * a single statement. Avoid using the following example: + * [Mandatory] Braces are used with if, else, for, do and while statements, even if the body contains only a single + * statement. Avoid using the following example: *
        * if (condition) statements;
        * 
      @@ -49,7 +49,7 @@ public class NeedBraceRule extends AbstractAliRule { // IfStatement with else have 2 expression blocks, should never throws NPE ASTStatement elseStms = node.findChildrenOfType(ASTStatement.class).get(1); - if (!elseStms.hasDecendantOfAnyType(ASTBlock.class, ASTIfStatement.class)) { + if (!elseStms.hasDescendantOfAnyType(ASTBlock.class, ASTIfStatement.class)) { addViolationWithMessage(data, elseStms, MESSAGE_KEY, new Object[] {"else"}); } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java index 1ae3c0e..ad1ac1f 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/LowerCamelCaseVariableNamingRule.java @@ -15,10 +15,9 @@ */ package com.alibaba.p3c.pmd.lang.java.rule.naming; -import java.util.regex.Pattern; - import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.util.StringAndCharConstants; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; @@ -28,6 +27,8 @@ import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator; import net.sourceforge.pmd.lang.java.ast.ASTTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; +import java.util.regex.Pattern; + /** * [Mandatory] Method names, parameter names, member variable names, and local variable names should be written in * lowerCamelCase. @@ -38,10 +39,14 @@ import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; public class LowerCamelCaseVariableNamingRule extends AbstractAliRule { private static final String MESSAGE_KEY_PREFIX = "java.naming.LowerCamelCaseVariableNamingRule.violation.msg"; - private Pattern pattern = Pattern.compile("^[a-z|$][a-z0-9]*([A-Z][a-z0-9]*)*(DO|DTO|VO|DAO)?$"); + private Pattern pattern = Pattern.compile("^[a-z][a-z0-9]*([A-Z][a-z0-9]+)*(DO|DTO|VO|DAO)?$"); @Override public Object visit(final ASTVariableDeclaratorId node, Object data) { + //避免与 AvoidStartWithDollarAndUnderLineNamingRule 重复判断(例: $myTest) + if (variableNamingStartOrEndWithDollarAndUnderLine(node.getImage())) { + return super.visit(node, data); + } // Constant named does not apply to this rule ASTTypeDeclaration typeDeclaration = node.getFirstParentOfType(ASTTypeDeclaration.class); Node jjtGetChild = typeDeclaration.jjtGetChild(0); @@ -65,11 +70,12 @@ public class LowerCamelCaseVariableNamingRule extends AbstractAliRule { } @Override - public Object visit(ASTMethodDeclarator node, Object data) { - if (!(pattern.matcher(node.getImage()).matches())) { - ViolationUtils.addViolationWithPrecisePosition(this, node, data, - I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", node.getImage())); + if (!variableNamingStartOrEndWithDollarAndUnderLine(node.getImage())) { + if (!(pattern.matcher(node.getImage()).matches())) { + ViolationUtils.addViolationWithPrecisePosition(this, node, data, + I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".method", node.getImage())); + } } return super.visit(node, data); } @@ -79,4 +85,9 @@ public class LowerCamelCaseVariableNamingRule extends AbstractAliRule { //对所有注解内的内容不做检查 return null; } + + private boolean variableNamingStartOrEndWithDollarAndUnderLine(String variable) { + return variable.startsWith(StringAndCharConstants.DOLLAR) + || variable.startsWith(StringAndCharConstants.UNDERSCORE); + } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java index 61ae516..5097730 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/naming/TestClassShouldEndWithTestNamingRule.java @@ -23,7 +23,7 @@ import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; -import net.sourceforge.pmd.lang.java.rule.junit.AbstractJUnitRule; +import net.sourceforge.pmd.lang.java.rule.AbstractJUnitRule; /** * [Mandatory] Test cases shall be started with the class names to be tested and ended with Test. diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java new file mode 100644 index 0000000..5b724ca --- /dev/null +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/BigDecimalAvoidDoubleConstructorRule.java @@ -0,0 +1,78 @@ +/* + * Copyright 1999-2017 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.p3c.pmd.lang.java.rule.oop; + +import java.util.List; + +import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; + +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ASTLiteral; +import net.sourceforge.pmd.lang.java.ast.ASTName; +import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; +import net.sourceforge.pmd.lang.java.ast.ASTVariableInitializer; +import org.jaxen.JaxenException; + +/** + * [Mandatory] Avoid using the constructor BigDecimal(double) to convert double value to a BigDecimal object. + * + * @author zenghou.fw + * @date 2019/04/02 + */ +public class BigDecimalAvoidDoubleConstructorRule extends AbstractAliRule { + + private static final String XPATH = + "Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression/Arguments[preceding-sibling::ClassOrInterfaceType[@Image = 'BigDecimal']]" + + "/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix"; + + @Override + public Object visit(ASTVariableInitializer node, Object data) { + try { + List invocations = node.findChildNodesWithXPath(XPATH); + if (invocations == null || invocations.isEmpty()) { + return super.visit(node, data); + } + ASTPrimaryPrefix expression = (ASTPrimaryPrefix)invocations.get(0); + + if (isDoubleLiteral(expression) || isDoubleVariable(expression)) { + addViolationWithMessage(data, node, + "java.oop.BigDecimalAvoidDoubleConstructorRule.violation.msg", null); + } + + } catch (JaxenException e) { + throw new RuntimeException("XPath expression " + XPATH + " failed: " + e.getLocalizedMessage(), e); + } + return super.visit(node, data); + } + + + @Override + public void addViolation(Object data, Node node, String arg) { + ViolationUtils.addViolationWithPrecisePosition(this, node, data, + "java.oop.BigDecimalAvoidDoubleConstructorRule.violation.msg"); + } + + private boolean isDoubleLiteral(ASTPrimaryPrefix node) { + ASTLiteral literal = node.getFirstChildOfType(ASTLiteral.class); + return literal != null && literal.isDoubleLiteral(); + } + + private boolean isDoubleVariable(ASTPrimaryPrefix node) { + ASTName name = node.getFirstChildOfType(ASTName.class); + return name != null && Double.class == name.getType(); + } +} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java index a383024..9e42c99 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoMustUsePrimitiveFieldRule.java @@ -19,6 +19,8 @@ import java.util.List; import com.alibaba.p3c.pmd.lang.java.rule.AbstractPojoRule; +import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; @@ -53,12 +55,12 @@ public class PojoMustUsePrimitiveFieldRule extends AbstractPojoRule { if (!shouldProcess) { continue; } - Class type = field.getType(); + Class type = NodeUtils.getNodeType(field); // TODO works only in current compilation file, by crossing files will be null if (type != null && type.isPrimitive()) { addViolationWithMessage(data, field.getFirstDescendantOfType(ASTType.class), "java.oop.PojoMustUsePrimitiveFieldRule.violation.msg", - new Object[] {field.getVariableName()}); + new Object[] {VariableUtils.getVariableName(field)}); } } } catch (JaxenException e) { diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java index f409344..fd4e24f 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/oop/PojoNoDefaultValueRule.java @@ -19,6 +19,7 @@ import java.util.List; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.AbstractPojoRule; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; @@ -54,7 +55,7 @@ public class PojoNoDefaultValueRule extends AbstractPojoRule { } ViolationUtils.addViolationWithPrecisePosition(this, field, data, I18nResources.getMessage("java.oop.PojoNoDefaultValueRule.violation.msg", - field.getVariableName())); + VariableUtils.getVariableName(field))); } } catch (JaxenException e) { throw new RuntimeException(e.getMessage(), e); diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java index 86e4030..a13f1b5 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/orm/IbatisMethodQueryForListRule.java @@ -22,6 +22,7 @@ import java.util.Set; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; @@ -52,6 +53,7 @@ public class IbatisMethodQueryForListRule extends AbstractAliRule { private static final String PRIMARY_METHOD_ARGUMENT_XPATH = "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Literal"; private static final String FIELDS_XPATH = "ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration"; + private static final int LITERALS_SIZE = 3; @Override public Object visit(ASTCompilationUnit node, Object data) { @@ -65,12 +67,12 @@ public class IbatisMethodQueryForListRule extends AbstractAliRule { return super.visit(node, data); } for (ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration : classOrInterfaceDeclarations) { - visitASTClassOrInterfaceDeclaration(classOrInterfaceDeclaration, data); + visitAstClassOrInterfaceDeclaration(classOrInterfaceDeclaration, data); } return super.visit(node, data); } - private void visitASTClassOrInterfaceDeclaration(ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration, + private void visitAstClassOrInterfaceDeclaration(ASTClassOrInterfaceDeclaration classOrInterfaceDeclaration, Object data) { try { List fieldDeclarations = classOrInterfaceDeclaration.findChildNodesWithXPath(FIELDS_XPATH); @@ -95,7 +97,7 @@ public class IbatisMethodQueryForListRule extends AbstractAliRule { for (Node node : fieldDeclarations) { ASTFieldDeclaration fieldDeclaration = (ASTFieldDeclaration)node; if (sqlMapClientField(fieldDeclaration)) { - set.add(fieldDeclaration.getVariableName()); + set.add(VariableUtils.getVariableName(fieldDeclaration)); } } return set; @@ -146,7 +148,7 @@ public class IbatisMethodQueryForListRule extends AbstractAliRule { } //method parameters not match List literals = node.findChildNodesWithXPath(PRIMARY_METHOD_ARGUMENT_XPATH); - if (!(literals != null && (literals.size() == 3))) { + if (literals == null || (literals.size() != LITERALS_SIZE)) { continue; } boolean firstMethodArgumentString = "java.lang.String".equals( diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java new file mode 100644 index 0000000..fffb1ce --- /dev/null +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidDoubleOrFloatEqualCompareRule.java @@ -0,0 +1,42 @@ +package com.alibaba.p3c.pmd.lang.java.rule.other; + +import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; +import net.sourceforge.pmd.lang.java.ast.ASTEqualityExpression; +import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; + +import java.util.List; + +/** + * @author changle.lq + * @date 2018/12/12 + */ +public class AvoidDoubleOrFloatEqualCompareRule extends AbstractAliRule { + + private static final String FLOAT = "float"; + private static final String DOUBLE = "double"; + private static final int LIST_SIZE = 2; + + @Override + public Object visit(ASTEqualityExpression node, Object data) { + List list = node.findDescendantsOfType(ASTPrimaryExpression.class); + if (list.size() != LIST_SIZE) { + return super.visit(node, data); + } + + ASTPrimaryExpression left = list.get(0); + ASTPrimaryExpression right = list.get(1); + Class leftType = left.getType(); + Class rightType = right.getType(); + if (leftType == null || rightType == null) { + return super.visit(node, data); + } + + if (FLOAT.equals(leftType.getName()) && FLOAT.equals(rightType.getName())) { + ViolationUtils.addViolationWithPrecisePosition(this, node, data); + } else if (DOUBLE.equals(leftType.getName()) && DOUBLE.equals(rightType.getName())) { + ViolationUtils.addViolationWithPrecisePosition(this, node, data); + } + return super.visit(node, data); + } +} diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java index f571817..12cb1f2 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/AvoidPatternCompileInMethodRule.java @@ -17,6 +17,7 @@ package com.alibaba.p3c.pmd.lang.java.rule.other; import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.AbstractXpathRule; +import com.alibaba.p3c.pmd.lang.java.util.VariableUtils; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; @@ -51,7 +52,7 @@ public class AvoidPatternCompileInMethodRule extends AbstractXpathRule { } else { ViolationUtils.addViolationWithPrecisePosition(this, node, data, I18nResources.getMessage("java.other.AvoidPatternCompileInMethodRule.violation.msg", - localVariableDeclaration.getVariableName())); + VariableUtils.getVariableName(localVariableDeclaration))); } } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java index 4a276a1..4f4d29a 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/MethodTooLongRule.java @@ -15,20 +15,33 @@ */ package com.alibaba.p3c.pmd.lang.java.rule.other; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; +import java.util.TreeMap; + import com.alibaba.p3c.pmd.I18nResources; import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; +import com.alibaba.p3c.pmd.lang.java.rule.util.NodeSortUtils; import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration; +import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; +import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; +import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode; +import net.sourceforge.pmd.lang.java.ast.Comment; +import net.sourceforge.pmd.lang.java.ast.FormalComment; +import net.sourceforge.pmd.lang.java.ast.MultiLineComment; +import net.sourceforge.pmd.lang.java.ast.SingleLineComment; import net.sourceforge.pmd.lang.java.ast.Token; /** * [Recommended] The total number of lines for a method should not be more than 80. - * Note: The total number of lines, including the method signature, closing brace, codes, comments, - * blank lines, line breaks and any invisible lines, should not be more than 80. + * Note: The total number of lines, including the method signature, closing brace, codes, blank lines, + * line breaks and any invisible lines, should not be more than 80 (comments are not included). * * @author keriezhang * @date 2018/1/9 @@ -38,6 +51,17 @@ public class MethodTooLongRule extends AbstractAliRule { private static final int MAX_LINE_COUNT = 80; private static final String ANNOTATION_PREFIX = "@"; + /** + * sortedMap will be reinitialized for each source file. + */ + private SortedMap sortedNodeAndComment; + + @Override + public Object visit(ASTCompilationUnit cUnit, Object data) { + sortedNodeAndComment = orderedCommentsAndExpressions(cUnit); + return super.visit(cUnit, data); + } + @Override public Object visit(ASTMethodDeclaration node, Object data) { // Include method modifiers. @@ -62,10 +86,68 @@ public class MethodTooLongRule extends AbstractAliRule { } } - if (endLine - startLine + 1 > MAX_LINE_COUNT) { + // Get comment line count. + int commentLineCount = getCommentLineCount(node); + + if (endLine - startLine - commentLineCount + 1 > MAX_LINE_COUNT) { ViolationUtils.addViolationWithPrecisePosition(this, node, data, I18nResources.getMessage("java.other.MethodTooLongRule.violation.msg", node.getName())); } - return super.visit(node, data); + return data; + } + + /** + * Order comments and expressions. + * + * @param cUnit compilation unit + * @return sorted comments and expressions + */ + protected SortedMap orderedCommentsAndExpressions(ASTCompilationUnit cUnit) { + + SortedMap itemsByLineNumber = new TreeMap<>(); + + // expression nodes + List expressionNodes = cUnit.findDescendantsOfType(ASTExpression.class); + NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, expressionNodes); + + NodeSortUtils.addNodesToSortedMap(itemsByLineNumber, cUnit.getComments()); + + return itemsByLineNumber; + } + + /** + * Get number of comment lines + * + * @param methodDecl + * @return + */ + private int getCommentLineCount(ASTMethodDeclaration methodDecl) { + int lineCount = 0; + AbstractJavaNode lastNode = null; + + for (Entry entry : sortedNodeAndComment.entrySet()) { + Node value = entry.getValue(); + if (value.getBeginLine() <= methodDecl.getBeginLine()) { + continue; + } + if (value.getBeginLine() > methodDecl.getEndLine()) { + break; + } + + // value should be either expression or comment. + if (value instanceof AbstractJavaNode) { + lastNode = (AbstractJavaNode)value; + } else if (value instanceof FormalComment || value instanceof MultiLineComment) { + Comment comment = (Comment)value; + lineCount += comment.getEndLine() - comment.getBeginLine() + 1; + } else if (value instanceof SingleLineComment) { + SingleLineComment singleLineComment = (SingleLineComment)value; + // Comment may in the same line with node. + if (lastNode == null || singleLineComment.getBeginLine() != lastNode.getBeginLine()) { + lineCount += 1; + } + } + } + return lineCount; } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java index 053f640..68a8e23 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/other/UseRightCaseForDateFormatRule.java @@ -1,10 +1,17 @@ package com.alibaba.p3c.pmd.lang.java.rule.other; +import java.util.List; + import com.alibaba.p3c.pmd.lang.AbstractXpathRule; +import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule; import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; +import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTLiteral; +import net.sourceforge.pmd.lang.java.ast.ASTName; import org.apache.commons.lang3.StringUtils; +import org.jaxen.JaxenException; /** * [Mandatory] When doing date formatting, "y" should be written in lowercase for "year" in a pattern statement. diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java index b94e100..cc480e0 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/rule/util/NodeUtils.java @@ -18,6 +18,7 @@ package com.alibaba.p3c.pmd.lang.java.rule.util; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; +import net.sourceforge.pmd.lang.java.ast.AbstractJavaAccessTypeNode; import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper; /** @@ -59,4 +60,8 @@ public class NodeUtils { public static boolean isConstant(ASTFieldDeclaration field) { return field != null && field.isStatic() && field.isFinal(); } + + public static Class getNodeType(AbstractJavaAccessTypeNode node) { + return node == null ? null : node.getType(); + } } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java index c7b4757..6b0303d 100644 --- a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/StringAndCharConstants.java @@ -26,4 +26,6 @@ public final class StringAndCharConstants { } public static final char DOT = '.'; + public static final String DOLLAR = "$"; + public static final String UNDERSCORE = "_"; } diff --git a/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java new file mode 100644 index 0000000..494ee77 --- /dev/null +++ b/p3c-pmd/src/main/java/com/alibaba/p3c/pmd/lang/java/util/VariableUtils.java @@ -0,0 +1,18 @@ +package com.alibaba.p3c.pmd.lang.java.util; + +import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; +import net.sourceforge.pmd.lang.java.ast.AbstractJavaAccessNode; + +/** + * @author caikang + * @date 2019/04/22 + */ +public class VariableUtils { + public static String getVariableName(AbstractJavaAccessNode typeNode) { + ASTVariableDeclaratorId decl = typeNode.getFirstDescendantOfType(ASTVariableDeclaratorId.class); + if (decl != null) { + return decl.getImage(); + } + return null; + } +} diff --git a/p3c-pmd/src/main/resources/messages.xml b/p3c-pmd/src/main/resources/messages.xml index 4289746..b5b1cba 100644 --- a/p3c-pmd/src/main/resources/messages.xml +++ b/p3c-pmd/src/main/resources/messages.xml @@ -162,11 +162,11 @@ +说明:Executors返回的线程池对象的弊端如下: +1)FixedThreadPool和SingleThreadPool: +  允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。 +2)CachedThreadPool: +  允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。]]> @@ -275,7 +275,6 @@ - @@ -339,6 +338,16 @@ + + + + + + + + + + @@ -477,7 +486,7 @@ @@ -505,5 +514,36 @@ + + + + + + + + + diff --git a/p3c-pmd/src/main/resources/messages_en.xml b/p3c-pmd/src/main/resources/messages_en.xml index ab417e3..4666a7f 100644 --- a/p3c-pmd/src/main/resources/messages_en.xml +++ b/p3c-pmd/src/main/resources/messages_en.xml @@ -167,7 +167,7 @@ Note: In JDK8, Instant can be used to replace Date, Calendar is replaced by Loca Note: Below are the problems created by usage of Executors for thread pool creation: 1) FixedThreadPool and SingleThreadPool:  Maximum request queue size Integer.MAX_VALUE. A large number of requests might cause OOM. -2) CachedThreadPool and ScheduledThreadPool: +2) CachedThreadPool:  The number of threads which are allowed to be created is Integer.MAX_VALUE. Creating too many threads might lead to OOM.]]> @@ -339,6 +339,16 @@ Note: Below are the problems created by usage of Executors for thread pool creat + + + + + + + + + + @@ -385,13 +395,13 @@ Javadoc should include method instruction, description of parameters, return val - + - + @@ -478,7 +488,7 @@ Note: In order to get a more accurate time, use System.nanoTime(). In JDK8, use @@ -508,4 +518,38 @@ Note: If attribute is null or does not exist, ${var} will be shown directly on w + + + + + + + + + + diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml index ae6d44f..dd295d6 100644 --- a/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-comment.xml @@ -3,7 +3,7 @@ - + AlibabaJavaComments diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml index 7733a56..fc0ab14 100644 --- a/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-concurrent.xml @@ -3,6 +3,7 @@ xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd"> + AlibabaJavaConcurrent @@ -136,9 +135,9 @@ Positive example 3: @@ -146,11 +145,10 @@ Positive example 1: diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml index 4824a4a..5c1203c 100644 --- a/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-constant.xml @@ -3,7 +3,7 @@ - + AlibabaJavaConstants - + - + 3 - - + AlibabaJavaExceptions + AlibabaJavaFlowControl + AlibabaJavaNaming + AlibabaJavaOop + ]]> @@ -36,7 +37,7 @@ if (a.equals(b)) { // code } - ]]> + ]]> @@ -53,7 +54,7 @@ String str; Integer a; } - ]]> + ]]> @@ -69,7 +70,7 @@ String str; Integer a; } - ]]> + ]]> @@ -99,7 +100,7 @@ return "Super{" + "firstName=" + firstName + '\'' + '}'; } } - ]]> + ]]> @@ -131,4 +132,26 @@ Positive example: + + java.oop.StringConcatRule.rule.msg.desc + 3 + + + + + + + + + diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml index 7410b76..b2d07e8 100644 --- a/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-orm.xml @@ -3,6 +3,7 @@ + AlibabaJavaOrm + AlibabaJavaOthers + + + + + java.other.AvoidDoubleOrFloatEqualCompareRule.rule.desc + 2 + + + + + diff --git a/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml b/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml index a0c890a..1df6223 100644 --- a/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml +++ b/p3c-pmd/src/main/resources/rulesets/java/ali-set.xml @@ -3,17 +3,18 @@ - + AlibabaJavaSets + 2 - - + 2 - t = Arrays.asList("a","b","c"); //warn @@ -46,7 +47,7 @@ Positive example: java.set.ClassCastExceptionWithSubListToArrayListRule.rule.msg.desc 2 - list = new ArrayList(); list.add("22"); @@ -55,7 +56,7 @@ Negative example: ]]> - list2 = new ArrayList(list.subList(0, 1)); ]]> @@ -85,7 +86,7 @@ Negative example: 1 - originList = new ArrayList(); originList.add("22"); @@ -94,9 +95,9 @@ Negative example: list.add("bb"); } ]]> - + - it=b.iterator(); while(it.hasNext()){ @@ -115,14 +116,14 @@ Negative example: java.set.CollectionInitShouldAssignCapacityRule.rule.msg.desc 3 - map = new HashMap(); ]]> - + - map = new HashMap(16); ]]> diff --git a/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml b/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml index cf79db3..80e1491 100644 --- a/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml +++ b/p3c-pmd/src/main/resources/rulesets/vm/ali-other.xml @@ -3,7 +3,7 @@ - + AlibabaVelocityOthers diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java b/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java index 4235795..9ab81aa 100644 --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java +++ b/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/oop/OopRuleTest.java @@ -37,5 +37,6 @@ public class OopRuleTest extends SimpleAggregatorTst { addRule(RULESET, "PojoMustUsePrimitiveFieldRule"); addRule(RULESET, "PojoMustOverrideToStringRule"); addRule(RULESET, "StringConcatRule"); + addRule(RULESET, "BigDecimalAvoidDoubleConstructorRule"); } } diff --git a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java b/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java index ddcc714..7986c66 100644 --- a/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java +++ b/p3c-pmd/src/test/java/com/alibaba/p3c/pmd/lang/java/rule/other/OtherRulesTest.java @@ -20,7 +20,7 @@ import org.junit.Test; /** * Test for other java rules. - * + * * @author keriezhang * @date 2017/06/18 * @@ -37,12 +37,10 @@ public class OtherRulesTest extends SimpleAggregatorTst { addRule(RULESET, "AvoidMissUseOfMathRandomRule"); addRule(RULESET, "MethodTooLongRule"); addRule(RULESET,"UseRightCaseForDateFormatRule"); + addRule(RULESET,"AvoidDoubleOrFloatEqualCompareRule"); } - @Test - public void testUseRightCaseForDateFormatRule() { - runTests(findRule(RULESET, "UseRightCaseForDateFormatRule")); - } + } diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml index 9c54fb4..259f271 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AbstractMethodOrInterfaceMethodMustUseJavadocRule.xml @@ -1,5 +1,7 @@ - + 6 - 4 + 4,4,4,4,4,4 @@ -50,10 +52,10 @@ public abstract class AbstractClassOrInterfaceMethodMustUseJavadoc { * only function comment. */ public abstract void getFistName(); - + /** * function comment - * + * * @param firstName first name * @param secondName second name * @return full name @@ -115,7 +117,7 @@ public interface AbstractClassOrInterfaceMethodMustUseJavadoc { function, return, parameters and exceptions. 6 - 4 + 4,4,4,4,4,4 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml index 69ff63b..10c19ec 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/AvoidCommentBehindStatementRule.xml @@ -1,5 +1,7 @@ - + - + 0 - + 4 - + + + + + Annotation type without author + 1 + 1 + + + + + + + Annotation type with author + 0 + + + + + + + Annotation type inside class + 0 + + + + + + + Non public class + 0 + + + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml index cab7aab..d23bab1 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/CommentsMustBeJavadocFormatRule.xml @@ -1,5 +1,7 @@ - + - + - + \ No newline at end of file diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml index a8293e1..d7ebeb3 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/comment/xml/RemoveCommentedCodeRule.xml @@ -1,5 +1,7 @@ - + - + AvoidCallStaticSimpleDateFormatRule 4 - 30,22,18,45 + 18,22,30,45 - + AvoidConcurrentCompetitionRandomRule 1 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml index b8a823a..c2f321a 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidManuallyCreateThreadRule.xml @@ -1,5 +1,7 @@ - + AvoidManuallyCreateThreadRule 3 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml index 1689692..a434615 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/AvoidUseTimerRule.xml @@ -1,5 +1,7 @@ - + AvoidUseTimer 3 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml index d592b0b..f8a0c31 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/CountDownShouldInFinallyRule.xml @@ -1,5 +1,7 @@ - + CountDownShouldInFinallyRule 1 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml index cd199a0..fb9fdae 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadLocalShouldRemoveRule.xml @@ -1,5 +1,7 @@ - + ThreadLocalShouldRemoveRule 2 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml index 38987ed..61e24f7 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadPoolCreationRule.xml @@ -1,5 +1,7 @@ - + Executors.new 5 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml index eb82c4c..da4260c 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/concurrent/xml/ThreadShouldSetNameRule.xml @@ -1,5 +1,7 @@ - + ThreadShouldSetNameRule 3 @@ -65,6 +67,29 @@ public class TestScheduledExecutorService { right 0 { + Thread thread = new Thread(); + thread.setName("111"); + return thread; + }); + } +} + + ]]> + + + right + 0 + - + @@ -59,13 +61,13 @@ @@ -76,4 +78,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/constant/xml/UpperEllRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/constant/xml/UpperEllRule.xml index 832b136..1b4be65 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/constant/xml/UpperEllRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/constant/xml/UpperEllRule.xml @@ -1,5 +1,7 @@ - + 0 - + - + + If the return type is primitive, return a value of wrapper class may cause NullPointerException 8 - 11,19,23,27,31,35,39,43 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/exception/xml/TransactionMustHaveRollbackRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/exception/xml/TransactionMustHaveRollbackRule.xml index 29d5382..5eaa8f4 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/exception/xml/TransactionMustHaveRollbackRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/exception/xml/TransactionMustHaveRollbackRule.xml @@ -1,5 +1,7 @@ - + TransactionMustHaveRollbackRule 1 @@ -28,6 +30,33 @@ public class TestTransactional { ]]> + + readOnly + 0 + + + with rollback 0 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidComplexConditionRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidComplexConditionRule.xml index af5abf1..d987e42 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidComplexConditionRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidComplexConditionRule.xml @@ -1,25 +1,43 @@ - + + 0)) { - return 1; - } - return 0; - } + public class Example { + public int fn1(int a, int b, int c) { + if (a == 0 || (b !=0 && c > 0)) { + return 1; + } + return 0; + } - public int fn2(int a, int b, int c) { - return (a == 0 || b != 0 && c > 0) ? 1 : 0; - } - } - ]]> + public int fn2(int a, int b, int c) { + return (a == 0 || b != 0 && c > 0) ? 1 : 0; + } + + public int fn3(int a, int b, int c) { + if (a == 0 || b !=0 || c > 0) { + return 1; + } + return 0; + } + + public int fn4(int a, int b, int c) { + return (a == 0 && b != 0 && c > 0) ? 1 : 0; + } + + public int fn5(int a, int b, boolean c) { + return (a == 0 && b != 0 && c) ? 1 : 0; + } + } + ]]> complex conditional expression in if condition 2 - 3,10 0 0 ˘ 0 /expected-linenumbers> + 3,10 @@ -27,13 +45,13 @@ 0); - return flag ? 1 : 0; - } - } - ]]> + public class Example { + public int fn3(int a, int b, int c) { + boolean flag = (a == 0 || b != 0 && c > 0); + return flag ? 1 : 0; + } + } + ]]> complex conditional expression extracted as variable @@ -45,15 +63,15 @@ ids = new ArrayList<>(); - if (ids.size() > 0) { + public class Example { + public int fn() { + List ids = new ArrayList<>(); + if (ids.size() > 0) { - } - } - } - ]]> + } + } + } + ]]> simple conditional expression diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidNegationOperatorRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidNegationOperatorRule.xml index bd23fe4..414a9ed 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidNegationOperatorRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/flowcontrol/xml/AvoidNegationOperatorRule.xml @@ -1,5 +1,7 @@ - + - + - + + + abstract class name should start with Abstract or Base 1 - 1 + @@ -45,7 +48,7 @@ public abstract class baseAbstractNameRuleTest { abstract class name should start with Abstract or Base 1 - 1 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml index ba45a57..0e4e3a3 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ArrayNamingShouldHaveBracketRule.xml @@ -1,4 +1,7 @@ - + + array should be array[] 2 - 2,6 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml index 86b7cd0..41e7683 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/AvoidStartWithDollarAndUnderLineNamingRule.xml @@ -1,4 +1,6 @@ - + name should not be start with $ and _ 4 - 2,3,4,5 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml index c59b500..5de6df3 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/BooleanPropertyShouldNotStartWithIsRule.xml @@ -1,4 +1,6 @@ - + issuccess should not contain is 2 + 2,3 - 2,3 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml index 651fa16..b3d0ed8 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ClassNamingShouldBeCamelRule.xml @@ -1,4 +1,6 @@ - + Class Name Should Camel 6 - 4,5,7,13,14,18 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml index ed1d748..c7776d1 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ConstantFieldShouldBeUpperCaseRule.xml @@ -1,4 +1,6 @@ - + Constant name should be upper case 2 - 7,9 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml index 3b39fde..582d1a0 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ExceptionClassShouldEndWithExceptionRule.xml @@ -1,4 +1,6 @@ - + Exception class name should end with Exception 1 - 1 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml index 962c24c..bdc2d93 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/LowerCamelCaseVariableNamingRule.xml @@ -1,4 +1,6 @@ - + Variable name should be lowerCamelCase - 1 + 2 + 2,3 - 3 @@ -59,8 +61,8 @@ public class PluginConstants { Variable name should be lowerCamelCase3 2 - 2,3 + @@ -116,7 +118,7 @@ public interface BizConstants { public class MockTest{ @Mock void $clinit(){} - } + } ]]> @@ -140,17 +142,28 @@ public interface BizConstants { 0 - + + + + + + Variable Naming Start Or End With Dollar And UnderLine + 0 + + + + @@ -159,25 +172,6 @@ public interface BizConstants { 0 - - - - - - Variable name should be lowerCamelCase10 - 4 - - diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml index 02ee353..86c9da6 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/PackageNamingRule.xml @@ -1,4 +1,6 @@ - + Package Name should be lowercase 1 - 2 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml index fa14bf1..b592596 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/ServiceOrDaoClassShouldEndWithImplRule.xml @@ -1,4 +1,6 @@ - + Service Class Name should be end with Impl 2 - 1,2 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml index 1cf4f5c..7e36646 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/naming/xml/TestClassShouldEndWithTestNamingRule.xml @@ -1,6 +1,9 @@ - + Test Class Name Should End With Test - 0 + Test Class Name Should End With Test 1 + 2 - 1 diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml new file mode 100644 index 0000000..2256365 --- /dev/null +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/BigDecimalAvoidDoubleConstructorRule.xml @@ -0,0 +1,29 @@ + + + + + + + + BigDicimal initializer allocation + 2 + 3,8 + + + + + + \ No newline at end of file diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml index 54cedb4..dabb126 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/EqualsAvoidNullRule.xml @@ -1,169 +1,171 @@ - + - - + - - - argument of equals is string literal - 3 - 6,10,14 - - + Integer a; + if (a.equals(3)) { // OK, literal number has no equals method + return; + } + } + } + ]]> + + + argument of equals is string literal + 3 + 6,10,14 + + - + - - + - - - argument of equals is constant - 1 - 8 - - + public void bar() { + String label; + //"abc".equals(label); // OK + //"abc".equals(label.toString()); // OK + if (label.equals(TOM)) { // BAD + return; + }; + } + } + ]]> + + + argument of equals is constant + 1 + 8 + + - + - - - - - non literal with equals - 0 - - + + + + + non literal with equals + 0 + + - + - - - - - multiple nested class - 2 - - + + + + + multiple nested class + 2 + + - + - - LOCAL_TEST_FLAG = new ThreadLocal(); + + LOCAL_TEST_FLAG = new ThreadLocal(); - public static boolean isLoadTestFlag() { - return Boolean.TRUE.equals(LOCAL_TEST_FLAG.get()); - } - } - ]]> - - - caller of equals is constant - 0 - - + public static boolean isLoadTestFlag() { + return Boolean.TRUE.equals(LOCAL_TEST_FLAG.get()); + } + } + ]]> + + + caller of equals is constant + 0 + + - + - - - - - string literal equals constant - 0 - - + + + + + string literal equals constant + 0 + + - + - - - - - string literal equals string literal - 0 - - + + + + + string literal equals string literal + 0 + + - - \ No newline at end of file + + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml index 2d0a017..cb31a7a 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoMustOverrideToStringRule.xml @@ -1,5 +1,7 @@ - + - + - POJO has primitive type fileds + POJO has primitive type fields 3 - 14,4,5 + 4,5,14 - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml index 60fadbb..914e11d 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/PojoNoDefaultValueRule.xml @@ -1,5 +1,7 @@ - + POJO has fields with default value 3 - 12,3,5 + 3,5,12 @@ -83,8 +85,8 @@ not check static, transient or public fields 2 - 12,3 + 3,12 - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml index 515f192..6ab616b 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/StringConcatRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml index 879830c..5c1a2bc 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/oop/xml/WrapperTypeEqualityRule.xml @@ -1,5 +1,7 @@ - + compare wrapper type objects without equals - 3 - 11,23,34 + 4 + 11,23,31,34 @@ -148,4 +150,4 @@ 0 - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml index 692137e..ad9cba5 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/orm/xml/IbatisMethodQueryForListRule.xml @@ -1,4 +1,6 @@ - + should not use ibatis method queryForList 2 - 4,10 + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml index bd002e8..727a979 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidApacheBeanUtilsCopyRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml new file mode 100644 index 0000000..c9217f3 --- /dev/null +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidDoubleOrFloatEqualCompareRule.xml @@ -0,0 +1,104 @@ + + + + + + + + + float value compare + 1 + 5 + + + + + + + + + float value compare + 1 + 3 + + + + + + + + float value compare + 1 + 3 + + + + + + + + + float value compare + 1 + 5 + + + + + + + + + compare + 0 + + + + \ No newline at end of file diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml index 4add692..0b9cd0b 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidMissUseOfMathRandomRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml index e4ff31d..0d1fd45 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidNewDateGetTimeRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml index 7c4377b..bda9353 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/AvoidPatternCompileInMethodRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml index 0cab1b7..3328503 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/MethodTooLongRule.xml @@ -1,88 +1,90 @@ - + @@ -98,85 +100,85 @@ public class MethodTooLongRule { @@ -222,83 +224,83 @@ public class MethodTooLongRule { public void test() { - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment int i = 1; + i = 2; + i = 3; + i = 4; + i = 5; + i = 6; + i = 7; + i = 8; + i = 9; + i = 10; + i = 11; + i = 12; + i = 13; + i = 14; + i = 15; + i = 16; + i = 17; + i = 18; + i = 19; + i = 20; + i = 21; + i = 22; + i = 23; + i = 24; + i = 25; + i = 26; + i = 27; + i = 28; + i = 29; + i = 30; + i = 31; + i = 32; + i = 33; + i = 34; + i = 35; + i = 36; + i = 37; + i = 38; + i = 39; + i = 40; + i = 41; + i = 42; + i = 43; + i = 44; + i = 45; + i = 46; + i = 47; + i = 48; + i = 49; + i = 50; + i = 51; + i = 52; + i = 53; + i = 54; + i = 55; + i = 56; + i = 57; + i = 58; + i = 59; + i = 60; + i = 61; + i = 62; + i = 63; + i = 64; + i = 65; + i = 66; + i = 67; + i = 68; + i = 69; + i = 70; + i = 71; + i = 72; + i = 73; + i = 74; + i = 75; + i = 76; + i = 77; } } ]]> @@ -316,83 +318,83 @@ public class MethodTooLongRule { @Test public void test() { - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment - // 76 lines of comment int i = 1; + i = 2; + i = 3; + i = 4; + i = 5; + i = 6; + i = 7; + i = 8; + i = 9; + i = 10; + i = 11; + i = 12; + i = 13; + i = 14; + i = 15; + i = 16; + i = 17; + i = 18; + i = 19; + i = 20; + i = 21; + i = 22; + i = 23; + i = 24; + i = 25; + i = 26; + i = 27; + i = 28; + i = 29; + i = 30; + i = 31; + i = 32; + i = 33; + i = 34; + i = 35; + i = 36; + i = 37; + i = 38; + i = 39; + i = 40; + i = 41; + i = 42; + i = 43; + i = 44; + i = 45; + i = 46; + i = 47; + i = 48; + i = 49; + i = 50; + i = 51; + i = 52; + i = 53; + i = 54; + i = 55; + i = 56; + i = 57; + i = 58; + i = 59; + i = 60; + i = 61; + i = 62; + i = 63; + i = 64; + i = 65; + i = 66; + i = 67; + i = 68; + i = 69; + i = 70; + i = 71; + i = 72; + i = 73; + i = 74; + i = 75; + i = 76; + i = 77; } } ]]> @@ -404,4 +406,391 @@ public class MethodTooLongRule { - \ No newline at end of file + + + + + Method equal to 80 lines with formal comment + 0 + + + + + + + + + Method equal to 80 lines with multi-line comment + 0 + + + + + + + + Method equal to 80 lines with single-line comment + 0 + + + + + + + + Method equal to 80 lines with comment after expression + 0 + + + + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml index 9d157d0..bb6b892 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/other/xml/UseRightCaseForDateFormatRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml index c0abbba..e07ce30 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithSubListToArrayListRule.xml @@ -1,11 +1,13 @@ - + list = new ArrayList(); - } + } } ]]> @@ -15,14 +17,14 @@ 0 - + list = new ArrayList(); list.add("22"); - List test = (ArrayList) list.subList(0, 1); - } + List test = (ArrayList) list.subList(0, 1); + } } ]]> @@ -34,4 +36,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml index 855fa17..f9c5845 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ClassCastExceptionWithToArrayRule.xml @@ -1,11 +1,13 @@ - + @@ -15,12 +17,12 @@ 0 - + @@ -32,4 +34,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml index ef8cac5..72a1eb5 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/CollectionInitShouldAssignCapacityRule.xml @@ -1,14 +1,16 @@ - + map = new HashMap(); - private void method(long aLong) { + public class Foo { + Map map = new HashMap(); + private void method(long aLong) { Map map2 = new HashMap(16); Map map3 = new ConcurrentHashMap(16); List originList = new ArrayList(2048); - } + } } ]]> @@ -18,13 +20,13 @@ 0 - + map = new HashMap(); Map map3 = new ConcurrentHashMap(); - } + } } ]]> @@ -36,4 +38,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml index b444295..872500f 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/ConcurrentExceptionWithModifyOriginSubListRule.xml @@ -1,13 +1,15 @@ - + originList = new ArrayList(); originList.add("22"); - List subList = originList.subList(0, 1); - } + List subList = originList.subList(0, 1); + } } ]]> @@ -17,17 +19,17 @@ 0 - + originList = new ArrayList(); originList.add("22"); List subList = originList.subList(0, 1); originList.add("22"); originList.remove("22"); - originList.clear(); - } + originList.clear(); + } } ]]> @@ -39,4 +41,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml index 2ebcf70..73e8fe8 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/DontModifyInForeachCircleRule.xml @@ -1,16 +1,18 @@ - + originList = new ArrayList(); originList.add("22"); - for (String item : originList) { - - } + for (String item : originList) { + + } originList.add("bb"); - } + } } ]]> @@ -20,18 +22,18 @@ 0 - + originList = new ArrayList(); originList.add("22"); - for (String item : originList) { + for (String item : originList) { originList.add("bb"); originList.remove("cc"); originList.clear(); - } - } + } + } } ]]> @@ -43,4 +45,4 @@ - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml index ecc4edc..fdd8dcf 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/java/rule/set/xml/UnsupportedExceptionWithModifyAsListRule.xml @@ -1,5 +1,7 @@ - + - \ No newline at end of file + diff --git a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml index 0f87e02..1c19589 100644 --- a/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml +++ b/p3c-pmd/src/test/resources/com/alibaba/p3c/pmd/lang/vm/rule/other/xml/UseQuietReferenceNotationRule.xml @@ -1,5 +1,7 @@ - + 0 - \ No newline at end of file +